-
Notifications
You must be signed in to change notification settings - Fork 3
/
glwidget.cpp
1300 lines (1139 loc) · 40 KB
/
glwidget.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <QtGui>
#include <QtOpenGL>
#include <QBitmap>
#if defined(Q_WS_MAC)
#include <OpenGL/glu.h>
#else
#ifndef QT_LINUXBASE
# include <GL/glu.h>
#endif
#endif
#include <algorithm>
#include <math.h>
#include <sstream>
#include <vector>
#include <utility> //includes std::pair
#include <stdlib.h>
#include <ctime>
#include "glwidget.h"
#include "NucleotideDisplay.h"
#include "BiasDisplay.h"
#include "RepeatMap.h"
#include "AnnotationDisplay.h"
#include "CylinderDisplay.h"
#include "RepeatOverviewDisplay.h"
#include "OligomerDisplay.h"
#include "HighlightDisplay.h"
#include "GtfReader.h"
#include "FastaReader.h"
#include "SkittleUtil.h"
using std::string;
using std::pair;
/** ***********************************
GLWidget is the primary display interface for Skittle. It handles the OpenGL
rendering and layout of all of the Graph display classes (everything that inherits
AbstractGraph). It is the primary workhorse that instantiates all the file readers
and all the displays. It also handles mouse tracking inside of OpenGL coordinate frame
since it controls the OpenGL viewframe settings (position, zoom, etc). Skittle
uses a largely 2D isometric display surface.
GLWidget keeps track of what Graphs are currently displayed and arranges the position
of the Graphs on the screen accordingly. It handles all of the mouse driven tools from
the toolbar. For example, when the select tool is used and clicked at (302, 57) glwidget
figures out which display is within that x range (>302), adjusts the coordinate for margins
and then passes it to the Graph for processing. The left-right displacement of the
horizontal scrollbar is handled by GLWidget. Finally, key presses are sent to the active
GLWidget for interpretation.
There is one GLWidget per MdiChildWindow. Each on connects to exactly one file. New windows
with unique files can be created through the addViewAction which will create a new glWidget.
GLWidget inherits from QGLWidget which is the Qt interface layer.
Development: GLWidget has always threatened to be the god object of Skittle. It has been
stripped down several times but it is still one of the largest class files. More functionality,
such as mouse and keyboard interaction could be moved to new helper classes.
*/
GLWidget::GLWidget(UiVariables* gui, QWidget* parentWidget)
: QGLWidget(parentWidget)
{
ui = gui;
glWidget = this;
parent = dynamic_cast<MdiChildWindow*>(parentWidget);
setMouseTracking(true);
setMinimumWidth(100);
setMinimumHeight(100);
frame = 0;
setupColorTable();
reader = new FastaReader(this, ui);
trackReader = new GtfReader(ui);
nuc = new NucleotideDisplay(ui, this);
bias = new BiasDisplay(ui, this);
freq = new RepeatMap(ui, this);
freq->link(nuc);
cylinder = new CylinderDisplay(ui, this);
align = new RepeatOverviewDisplay(ui, this);
olig = new OligomerDisplay(ui, this);
highlight = new HighlightDisplay(ui, this);
addGraph(olig);
addGraph(align);
addGraph(freq);
addGraph(bias);
addGraph(highlight);
addGraph(nuc);
addGraph(cylinder);
selectionBoxVisible = false;
border = 10;
xPosition = 0;
mouseMovePosition = QPoint();//you may want to initialize press and release points, start/end
setTool(RESIZE_TOOL);
setMouseTracking(true);
setFocusPolicy(Qt::ClickFocus);
createConnections();
createCursors();
// createButtons();
srand(time(0));
}
GLWidget::~GLWidget()
{
delete reader;
delete trackReader;
for(int i = graphs.size() -1; i >= 0; --i)
{
delete graphs[i];
}
makeCurrent();
}
void GLWidget::addGraph(AbstractGraph* graph)
{
graphs.insert(graphs.begin(), graph );//these are added in reverse order for the sake of AnnotationDisplay
//Note: The connection between displayChanged and updateDisplay is specifically used
//for the case where the settingsUi tab causes an update that is only relevant to
//one of the graphs. This means that one graph is already invalidated and the others
//do not need to change their data.
connect( graph, SIGNAL(displayChanged()), this, SLOT(updateDisplay()) );
connect( graph, SIGNAL(hideSettings(QScrollArea*)), this, SIGNAL(hideSettings(QScrollArea*)));
connect( graph, SIGNAL(showSettings(QScrollArea*)), this, SIGNAL(showSettings(QScrollArea*)));
emit addGraphMode(graph);
}
void GLWidget::createButtons()
{
for(int i = (int)graphs.size()-1; i >= 0 ; --i)
emit addGraphMode( graphs[i] );
emit addDivider();
}
void GLWidget::createConnections()
{
connect(trackReader,SIGNAL(BookmarkAdded(track_entry,string)), this,SLOT(addTrackEntry(track_entry,string)));
/****CONNECT LOCAL VARIABLES*******/
connect(ui, SIGNAL(internalsUpdated()), this, SLOT(changeZoom()));
connect(ui, SIGNAL(colorsChanged(int)), this, SLOT(invalidateDisplayGraphs()));
}
QSize GLWidget::minimumSizeHint() const
{
return QSize(160, 60);
}
QSize GLWidget::sizeHint() const
{
return QSize(450, 300);
}
double GLWidget::pixelsToOpenGlGridRatio()
{
return ui->getZoom() / 100.0 * 3.0;//this make pixel->gl 3x size by default
//these are not 1:1 so that users have an easy time seeing the Skittle pixels
}
int GLWidget::setHorizontalScrollbarRange()
{
int fullPixelWidth = getTotalPixelWidth();
int val = (int)max(0.0, ((double)(fullPixelWidth)/(double)pixelsToOpenGlGridRatio() - openGlGridWidth()) ) ;
// qDebug() << "HorizontalBar Width: " << val;
emit totalWidthChanged(val);
return val;
}
//***********SLOTS*******************
const string* GLWidget::seq()
{
return reader->seq();
}
void GLWidget::displayString(const string* sequence)
{
ui->print("New sequence received. Size:", sequence->size());
for(int i = 0; i < (int)graphs.size(); ++i)
{
graphs[i]->setSequence(sequence);
graphs[i]->invalidate();
}
ui->setAllVariables(128, 1, 100, 1, -1);
}
void GLWidget::zoomExtents()
{
zoomRange(1,seq()->size());
}
void GLWidget::zoomRange(int startIndex, int endIndex)
{//TODO:refactor this with pixelToGlCoords
int newZoom = -1;
float pixelWidth = (float)ui->getWidth() / (float)ui->getScale();
float skixelsOnScreen = pixelWidth * (openGlGridHeight()-10);
int selectionSize = abs(endIndex - startIndex);
float requiredScale = (selectionSize) / skixelsOnScreen;
int newScale = max(1, (int)(requiredScale + 0.5) );
if (newScale == 1)
{
float requiredLines = selectionSize / pixelWidth;
float screenHeight = openGlGridHeight() * ((float)ui->getZoom() / 100); //how many pixels at zoom 100
float screenWidth = openGlGridWidth() * ((float)ui->getZoom() / 100) - 50;
float requiredZoom = (screenHeight / requiredLines); // not percent based
if (pixelWidth * (requiredZoom) > screenWidth) // if the zoom level makes the line wider than the screen just zoom to fit the widt
requiredZoom = screenWidth / pixelWidth;
newZoom = max(100,(int)(requiredZoom * 100)); //now it's in percent
}
ui->setAllVariables(-1, newScale, newZoom, min(startIndex,endIndex), -1 );
}
void GLWidget::on_moveButton_clicked()
{
setTool(MOVE_TOOL);
}
void GLWidget::on_selectButton_clicked()
{
setTool(SELECT_TOOL);
}
void GLWidget::on_findButton_clicked()
{
setTool(FIND_TOOL);
highlight->ensureVisible();
}
void GLWidget::on_addAnnotationButton_clicked()
{
ui->print("ANNOTATE selected");
setTool(ANNOTATE_TOOL);
}
void GLWidget::on_screenCaptureButton_clicked()
{
makeCurrent();
QImage image;
int pictureWidth = getTotalPixelWidth();
//Set the gl render width to the total graph's pixel widths
int tempWidth = width();
resize(pictureWidth, height());
paintGL();
if (format().rgba())
{
image = read_framebuffer(QSize(pictureWidth, height()), format().alpha(), false);
}
else
{
#if defined(Q_WS_WIN) && !defined(QT_OPENGL_ES)
image = QImage(pictureWidth, height(), QImage::Format_Indexed8);
glReadPixels(0, 0, pictureWidth, height(), GL_COLOR_INDEX, GL_UNSIGNED_BYTE, image.bits());
const QVector<QColor> pal = QColormap::instance().colormap();
if(pal.size())
{
image.setNumColors(pal.size());
for(int i = 0; i < pal.size(); i++)
{
image.setColor(i, pal.at(i).rgb());
}
}
image = image.mirrored();
#endif
}
stringstream namestream;
namestream << chromosomeName << "_width-" << ui->getWidth() << "_start-" << ui->getStart(glWidget) << "_scale-" << ui->getScale();
string g = string("_");
g.append( string((int)!nuc->hidden, 'n') );
g.append( string((int)!bias->hidden, 'b') );
g.append( string((int)!freq->hidden, 'm') );
g.append( string((int)!cylinder->hidden, 'c') );
g.append( string((int)!align->hidden, 'r') );
g.append( string((int)!olig->hidden, 'o') );
g.append( string((int)!highlight->hidden, 'h') );
namestream << g << ".png";
QString filename = QFileDialog::getSaveFileName(this, tr("Save Image"), namestream.str().c_str(), tr("Images (*.png *.jpg)"));
if(!filename.isEmpty())
{
image.save(filename);
filename.prepend("Saved image: ");
ui->print(filename.toStdString());
ui->print("Current settings are stored in the image filename.");
}
//Set width back to what it should be
this->resize(tempWidth, height());
paintGL();
}
int GLWidget::getTotalPixelWidth()
{
int skixelWidth = border;
for(int i = 0; i < (int)graphs.size(); ++i)
{
if(graphs[i]->hidden == false)
skixelWidth += graphs[i]->width() + border;
}
return skixelWidth * pixelsToOpenGlGridRatio();
}
QImage GLWidget::read_framebuffer(const QSize &size, bool alpha_format, bool include_alpha)
{
QImage image(size, alpha_format ? QImage::Format_ARGB32 : QImage::Format_RGB32);
int w = size.width();
int h = size.height();
glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, image.bits());
convertFromGLImage(image, w, h, alpha_format, include_alpha);
return image;
}
void GLWidget::convertFromGLImage(QImage &image, int w, int h, bool alpha_format, bool include_alpha)
{
if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
// OpenGL gives RGBA; Qt wants ARGB
uint *p = (uint*)image.bits();
uint *end = p + w*h;
if (alpha_format && include_alpha) {
while (p < end) {
uint a = *p << 24;
*p = (*p >> 8) | a;
p++;
}
} else {
// This is an old legacy fix for PowerPC based Macs, which
// we shouldn't remove
while (p < end) {
*p = 0xff000000 | (*p>>8);
++p;
}
}
} else {
// OpenGL gives ABGR (i.e. RGBA backwards); Qt wants ARGB
for (int y = 0; y < h; y++) {
uint *q = (uint*)image.scanLine(y);
for (int x=0; x < w; ++x) {
const uint pixel = *q;
*q = ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff) | (pixel & 0xff00ff00);
q++;
}
}
}
image = image.mirrored();
}
void GLWidget::on_resizeButton_clicked()
{
setTool(RESIZE_TOOL);
}
void GLWidget::on_zoomButton_clicked()
{
setTool(ZOOM_TOOL);
}
void GLWidget::setTool(int tool)
{
int oldTool = currentTool;
currentTool = tool;
switch(tool)
{
case MOVE_TOOL:
changeCursor(Qt::OpenHandCursor);//previously Qt::SizeAllCursor
break;
case RESIZE_TOOL:
changeCursor(Qt::SplitHCursor);//previously Qt::SizeHorCursor
break;
case FIND_TOOL:
changeCursor(Qt::CrossCursor);
break;
case SELECT_TOOL:
changeCursor(Qt::WhatsThisCursor);//previously Qt::CrossCursor);
break;
case ZOOM_TOOL:
setCursor(zoomInCursor);
break;
case ANNOTATE_TOOL:
changeCursor(Qt::IBeamCursor);
break;
default:
currentTool = oldTool;
ui->print("Error: Tool ID unrecognized: ", tool);
}
}
int GLWidget::tool()
{
return currentTool;
}
void GLWidget::slideHorizontal(int x)
{
if(x != xPosition && x > 0 && x < setHorizontalScrollbarRange())
{
xPosition = x;
emit xOffsetChange((int)(x));
updateDisplay();
}
}
void GLWidget::invalidateDisplayGraphs()
{
setupColorTable();
qDebug() << "GlWidget::invalidateDisplayGraphs " << ++frame;
for(int i = 0; i < (int)graphs.size(); ++i)
{
graphs[i]->invalidate();
}
updateDisplay();
}
void GLWidget::updateDisplay()
{
redraw();
}
void GLWidget::updateDisplaySize()
{
int w = ui->getWidth();
ui->setSize( w * openGlGridHeight() );
}
AnnotationDisplay* GLWidget::addAnnotationDisplay(QString fName)
{
string fileName = fName.toStdString();
if( fileName.empty() )
{
fileName = trackReader->outputFile();
}
AnnotationDisplay* tempTrackDisplay = findMatchingAnnotationDisplay(fileName);
if( tempTrackDisplay != NULL)
{
//if the display already exists, then it will simply return that one,
//otherwise it will create a new Display
// ErrorBox msg("The file is already open");
}
else
{
vector<track_entry> track = trackReader->readFile(QString(fileName.c_str()));
ui->print("Annotations Received: ", track.size());
if( track.size() > 0)// || trackReader->outputFile().compare(fileName) == 0 )//
{
tempTrackDisplay = new AnnotationDisplay(ui, this, fileName);
addGraph(tempTrackDisplay);
tempTrackDisplay->newTrack( track );
}
}
return tempTrackDisplay;
}
void GLWidget::jumpToAnnotation(bool forward)
{
//scan for all the AnnotationDisplays
vector<AnnotationDisplay*> annotations = getAllAnnotationDisplays();
int startPosition = 1000000000;//end of file
if (!forward)
startPosition = 1;
//have each submit the position of the next annotation
for(int i = 0; i < (int)annotations.size(); ++i)
{
if(forward)
startPosition = min(startPosition, annotations[i]->getNextAnnotationPosition());
else //go backwards
startPosition = max(startPosition, annotations[i]->getPrevAnnotationPosition());
}
//jump to the first one (min)
if(startPosition < (int)seq()->size())
ui->setStart(glWidget, startPosition);
else if (startPosition <= 1)
ui->print("You have reached the beginning of the file.");
else
ui->print("There are no annotations further in the file.");
}
AnnotationDisplay* GLWidget::findMatchingAnnotationDisplay(string fileName)
{
vector<AnnotationDisplay*> aDisplays = getAllAnnotationDisplays();
AnnotationDisplay* tempTrackDisplay = NULL;
for ( int n = 0; n < (int)aDisplays.size(); n++)
{
if (aDisplays[n] != NULL && aDisplays[n]->getFileName().compare(fileName) == 0 )
{
tempTrackDisplay = aDisplays[n];
break;
}
}
return tempTrackDisplay;
}
vector<AnnotationDisplay*> GLWidget::getAllAnnotationDisplays()
{
vector<AnnotationDisplay*> annotations;
for ( int n = 0; n < (int)graphs.size(); n++)
{
AnnotationDisplay* testPtr = dynamic_cast<AnnotationDisplay*>(graphs[n]);
if ( testPtr != NULL )
annotations.push_back(testPtr);
}
return annotations;
}
void GLWidget::addTrackEntry(track_entry entry, string gtfFileName)
{
AnnotationDisplay* trackDisplay = addAnnotationDisplay(QString(gtfFileName.c_str()));
if (trackDisplay != NULL )
{
trackDisplay->addEntry(entry);
}
makeCurrent();
}
/*****************FUNCTIONS*******************/
void GLWidget::zoomToolActivate(bool zoomOut)
{
if(zoomOut || (abs(endPoint.y - startPoint.y) < 2 && abs(endPoint.x - startPoint.x) < 2))
{
float zoomFactor = 1.2;
if(zoomOut)
zoomFactor = 0.8;
int scale = ui->getScale();//take current scale
int index = startPoint.y * (ui->getWidth()/scale) + startPoint.x;
index *= scale;
index = max(0, index + ui->getStart(glWidget));
int newSize = (int)(ui->getSize() / zoomFactor);//calculate new projected size
int newStart = index - (newSize/2);//set start as centered point - size/2
//size should recalculate
int newScale = (int)(scale / zoomFactor) + (zoomFactor > 1.0? 0 : 1);//reduce scale by 10-20% (Nx4)
int zoom = ui->getZoom();
int newZoom = -1;
if( zoomFactor > 1.0 ) // we're zooming in
{
if(scale == 1)
{
newZoom = zoom * zoomFactor ;
newScale = -1;
}
}
else //zooming out
{
if(zoom > 100)
{
newZoom = max(100, ((int) (zoom * zoomFactor))) ;
newScale = -1;
}
}
ui->setAllVariables(-1, newScale, newZoom, newStart, newSize);
}
else // user selected range
{
pair<int,int> results = getSelectionOutcome();
if(results.first != -1)
{
zoomRange(results.first, results.second);
}
}
}
pair<int, int> GLWidget::getSelectionOutcome(bool getGraphConstraints)
{
int startIndex = 1;
int endIndex = 1;
int xOffset = 0;
for(int i = 0; i < (int)graphs.size(); ++i)
{
if(!graphs[i]->hidden)
{
pair<int,int> indices = graphs[i]->getIndicesFromPoints(point2D((startPoint.x - xOffset),startPoint.y), point2D((endPoint.x - xOffset),endPoint.y));
startIndex = min(indices.first, indices.second);
endIndex = max(indices.first, indices.second);
if (startIndex > 0 && endIndex > 0 )//&& endIndex < seq()->size())
{
if(getGraphConstraints)
{
return pair<int,int>(xOffset,(xOffset + graphs[i]->width()));
}
else // default behavior returns indicies
return pair<int,int>(startIndex,endIndex);
}
xOffset += graphs[i]->width() + border;
}
}
return pair<int,int>(-1,-1);
}
//***********KEY HANDLING**************
void GLWidget::keyPressEvent( QKeyEvent *event )
{
if( event->modifiers() & Qt::SHIFT && tool() == ZOOM_TOOL)
setCursor(zoomOutCursor);
int step = 10;
int tenLines = ui->getWidth() * step;
switch ( event->key() )//the keys should be passed directly to the widgets
{
case Qt::Key_Down:
ui->setStart(glWidget, ui->getStart(glWidget) + tenLines);
break;
case Qt::Key_Up:
ui->setStart(glWidget, ui->getStart(glWidget) - tenLines);
break;
case Qt::Key_Right:
ui->setWidth(ui->getWidth() + ui->getScale());
break;
case Qt::Key_Left:
ui->setWidth(ui->getWidth() - ui->getScale());
break;
default:
event->ignore();
return;
}
event->accept();
}
void GLWidget::keyReleaseEvent( QKeyEvent *event )
{
if( event->key() == Qt::Key_Shift && tool() == ZOOM_TOOL)
{
setCursor(zoomInCursor);
event->accept();
}
else{
QGLWidget::keyReleaseEvent( event );
}
}
//***********Functions*************
point2D GLWidget::pixelToGlCoords(QPoint mouse)
{
int x = mouse.x() / pixelsToOpenGlGridRatio() - border + xPosition;//TODO: scrollbar problem may be here
int y = mouse.y() / pixelsToOpenGlGridRatio();
return point2D(x, y);
}
int GLWidget::openGlGridHeight()
{
QSize dimensions = size();
double pixelHeight = dimensions.height();
return pixelToGlCoords(QPoint(0,pixelHeight)).y;
}
int GLWidget::openGlGridWidth()
{
QSize dimensions = size();
double pixelWidth = dimensions.width();
// double adjustedX = pixelWidth;// + xPosition * pixelsToOpenGlGridRatio();//TODO: scrollbar problem may be here
return pixelWidth / pixelsToOpenGlGridRatio();
}
void GLWidget::initializeGL()
{
qglClearColor(QColor::fromRgbF(0.5, 0.5, 0.5));//50% grey
glShadeModel(GL_FLAT);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
// glEnable(GL_MULTISAMPLE_ARB );
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
marker = 0;//glGenLists(1);
for(int i = 0; i < (int)graphs.size(); ++i)
graphs[i]->setSequence(seq());
}
void GLWidget::paintGL()
{
updateDisplaySize();
setHorizontalScrollbarRange();
makeCurrent();
// paintText();
// qDebug() << "GlWidget Frame: " << ++frame;
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();
glTranslated(-xPosition * pixelsToOpenGlGridRatio() , 0, 0);
double zoom = pixelsToOpenGlGridRatio();
glScaled(zoom, zoom, zoom);
glTranslated(border,0,0);//to get zoom working right
if( tool() == SELECT_TOOL || tool() == FIND_TOOL)
{
glCallList(marker);//possibly replace this with a blinking cursor
}
if (selectionBoxVisible)// tool() == ZOOM_TOOL && )
{
drawSelectionBox(startPoint, endPoint);
}
for(int i = 0; i < (int)graphs.size(); ++i)
{
if(!graphs[i]->hidden)
{
graphs[i]->display();
graphs[i]->displayLegend(openGlGridWidth(), openGlGridHeight());
glTranslated(graphs[i]->width() + border, 0 , 0);
}
}
glPopMatrix();
}
void GLWidget::paintText()
{
saveGLState();
QPainter p(this); // used for text overlay
p.endNativePainting();
p.setPen(QColor(197, 197, 197, 157));
p.setBrush(QColor(197, 197, 197, 127));
p.drawRect(QRect(0, 0, width(), 50));
p.setPen(Qt::black);
p.setBrush(Qt::NoBrush);
const QString str1(tr("A simple OpenGL pbuffer example."));
const QString str2(tr("Use the mouse wheel to zoom, press buttons and move mouse to rotate, double-click to flip."));
QFontMetrics fm(p.font());
p.drawText(width()/2 - fm.width(str1)/2, 20, str1);
p.drawText(width()/2 - fm.width(str2)/2, 20 + fm.lineSpacing(), str2);
p.beginNativePainting();
restoreGLState();
}
void GLWidget::saveGLState()
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
}
void GLWidget::restoreGLState()
{
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
}
void GLWidget::resizeGL(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float left = 0;
float right = left + width;
float top = 0;
float bottom = top - height;
glOrtho(left, right, bottom, top, 0, 5000);
gluLookAt(0, 0, 40, //position and direction
0, 0, 0,
0, 1, 0);
glMatrixMode(GL_MODELVIEW);
setHorizontalScrollbarRange();
updateDisplaySize();
}
void pushNonEmpty(vector<string>& arr, string str)
{
if(!str.empty())
arr.push_back(str);
}
QString grabFirstNonEmpty(vector<string> array)
{
for(int i = 0; i < (int)array.size(); ++i)
if(!array[i].empty())
return QString(array[i].substr(0,1000).c_str());//truncating the string in the case where NucleotideDisplay dumps a 1Mbp sequence
return QString();
}
bool GLWidget::event(QEvent* event)
{
if (event->type() == QEvent::ToolTip)
{
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
point2D oglCoords = pixelToGlCoords(helpEvent->pos());
QString text = grabFirstNonEmpty(mouseOverText(oglCoords));
if( !text.isEmpty() )
{
QToolTip::showText(helpEvent->globalPos(), text);
}
else{
QToolTip::hideText();
event->ignore();
}
return true;
}
return QGLWidget::event(event);
}
vector<string> GLWidget::mouseOverText(point2D oglCoords)
{
vector<string> responses;
/*Progressively decrement x based on the cumulative width of modules
The order here is important and should match the left to right display order*/
for(int i = 0; i < (int)graphs.size(); ++i)
{
if(!graphs[i]->hidden)
{
if(tool() == SELECT_TOOL )
pushNonEmpty(responses, graphs[i]->SELECT_MouseClick(oglCoords));
if(tool() == FIND_TOOL)
pushNonEmpty(responses, graphs[i]->FIND_MouseClick(oglCoords));
oglCoords.x -= graphs[i]->width() + border;
}
}
return responses;
}
void GLWidget::mousePressEvent(QMouseEvent* event)
{
parent->mousePressEvent(event);
startPoint = pixelToGlCoords(event->pos());
if(tool() == SELECT_TOOL || tool() == FIND_TOOL)
placeMarker(event->pos());
if(tool() == SELECT_TOOL || tool() == FIND_TOOL)
{
vector<string> responses = mouseOverText( startPoint);
if(tool() == SELECT_TOOL)
{
for(int i = 0; i < (int)responses.size(); ++i)
ui->print(responses[i]);
}
if(tool() == FIND_TOOL)
{
for(int i = 0; i < (int)responses.size(); ++i)
highlight->setHighlightSequence(QString(responses[i].c_str()));
}
}
if(tool() == MOVE_TOOL )
changeCursor(Qt::ClosedHandCursor);
if(tool() == ZOOM_TOOL || tool() == ANNOTATE_TOOL )
{
selectionBoxVisible = true;
}
endPoint = startPoint;
mousePressPosition = event->pos();
}
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
point2D old = pixelToGlCoords(mouseMovePosition);
endPoint = pixelToGlCoords(event->pos());
if(tool() == SELECT_TOOL || tool() == FIND_TOOL)
placeMarker(event->pos());
float dx = (endPoint.x - old.x);
float dy = (endPoint.y - old.y);
if (event->buttons() & Qt::LeftButton)
{
if((tool()== RESIZE_TOOL || tool()== MOVE_TOOL) && (event->modifiers() & Qt::ControlModifier))
{
translateOffset(-dx, dy);
}
else{
if(tool() == MOVE_TOOL)
translate(-dx, dy);
if(tool() == RESIZE_TOOL)
{
translate(0, dy);//still scroll up/down
int value = static_cast<int>(dx * ui->getScale() + ui->getWidth() + 0.5);
ui->setWidth(value);
}
}
if(tool() == ZOOM_TOOL && selectionBoxVisible )
{
}
invalidateDisplayGraphs();
}
mouseMovePosition = event->pos();
}
void GLWidget::mouseReleaseEvent(QMouseEvent *event)
{
mouseReleasePosition = event->pos();
endPoint = pixelToGlCoords(event->pos());
if(tool() == MOVE_TOOL )
changeCursor(Qt::OpenHandCursor);
if( selectionBoxVisible)
{
selectionBoxVisible = false;
if(tool() == ZOOM_TOOL )
{
bool zoomingOut = (event->modifiers() & Qt::SHIFT) || (event->button() == Qt::RightButton);
if(zoomingOut)
setCursor(zoomOutCursor);
else
setCursor(zoomInCursor);
zoomToolActivate(zoomingOut);
}
if (tool() == ANNOTATE_TOOL )
{
pair<int,int> results = getSelectionOutcome();
if(results.first != -1)
trackReader->addBookmark(results.first, results.second);
}
}
}
//m:draw Selection box
void GLWidget::drawSelectionBox(point2D start,point2D end) //, int lineStart, int lineEnd
{
if(selectionBoxVisible)
{
if (start.y > end.y || (start.y == end.y && start.x > end.x)) //if you drag up,
{
point2D temp = start;//swap the top and bottom of the box
start = end;
end = temp;
}
pair<int,int> graphConstraints = getSelectionOutcome(true); //
int lineStart = graphConstraints.first;
int lineEnd = graphConstraints.second;
if (lineStart != -1) // force points to be in bounds and make pretty squared off boxes
{
if (start.x < lineStart)
start.x = lineStart;
if (start.x >= lineEnd)
{
start.x = lineStart;
++start.y;
}
if (end.x > lineEnd)
end.x = lineEnd;
if (end.x < lineStart)
{
end.x = lineEnd;
--end.y;
}
// hairline edge
color c = color(200,185,60);
double lineThickness = 0.3;
//draw the ragged box edge
nuc->paint_line(point((lineStart - lineThickness), -(start.y + 1 - lineThickness),0), point(start.x, -(start.y + 1),0), c); //top left
nuc->paint_line(point((start.x - lineThickness), -(start.y - lineThickness),0), point(start.x, -(start.y + 1),0), c); //top jog
nuc->paint_line(point((start.x - lineThickness), -(start.y - lineThickness),0), point((lineEnd + lineThickness), -start.y,0), c); //top right
nuc->paint_line(point((lineStart - lineThickness), -(end.y + 1),0), point((end.x + lineThickness), -(end.y + 1 + lineThickness),0), c); //bottom left
nuc->paint_line(point(end.x, -end.y,0), point((end.x + lineThickness), -(end.y + 1 + lineThickness),0), c); //bottom jog
nuc->paint_line(point(end.x, -end.y,0), point((lineEnd + lineThickness), -(end.y + lineThickness),0), c); //bottom right
nuc->paint_line(point((lineStart - lineThickness), -(start.y + 1 - lineThickness),0), point(lineStart, -(end.y + 1 + lineThickness),0), c); //left
nuc->paint_line(point(lineEnd, -start.y,0), point((lineEnd + lineThickness), -(end.y + lineThickness),0), c); //right
// adjust to taste