There can be only one (filename convention)
[mussa.git] / qui / PathScene.cpp
1 #include <QDir>
2 #include <QFileDialog>
3 #include <QMessageBox>
4 #include <QMouseEvent>
5 #include <QRubberBand>
6 #include <QRect>
7 #include <QString>
8 #include <iostream>
9 #include <set>
10
11 #include <GL/gl.h>
12 #include <math.h>
13
14 #include "qui/PathScene.hpp"
15 #include "alg/glsequence.hpp"
16 #include "mussa_exceptions.hpp"
17
18 using namespace std;
19
20 PathScene::PathScene(Mussa* analysis, QWidget *parent) : 
21   QGLWidget(parent),
22   viewport_height(0),
23   viewport_width(0),
24   clipZ(30.0),
25   zoom(2),
26   maxOrtho2d(-50.0, -50, 3000000.0, 300.0),
27   curOrtho2d(maxOrtho2d),
28   viewport_center(((curOrtho2d.right()-curOrtho2d.left())/2)+curOrtho2d.left()),
29   selectedMode(false),
30   rubberBand(0),
31   drawingBand(false)
32
33   if (analysis == 0)
34   {
35     mussaAnalysis = new Mussa;
36   }
37   else
38   {
39     mussaAnalysis = analysis;
40   }
41   updateScene();
42 }
43
44 QSize PathScene::sizeHint() const
45 {
46   return QSize(400, 400);
47 }
48
49 float PathScene::left()
50 {
51   return maxOrtho2d.left();
52 }
53
54 float PathScene::right()
55 {
56   return maxOrtho2d.right();
57 }
58
59 float PathScene::viewportLeft()
60 {
61   return curOrtho2d.left();
62 }
63
64 float PathScene::viewportRight()
65 {
66   return curOrtho2d.right();
67 }
68
69 float PathScene::viewportCenter()
70 {
71   return viewport_center;
72 }
73
74 void PathScene::updateViewport(float center, int new_zoom)
75 {
76   float max_width = maxOrtho2d.width();
77   if (new_zoom < 1) new_zoom = 1;
78   float new_max_width = max_width / new_zoom;
79   //curOrtho2d.setLeft(max(center-new_max_width, maxOrtho2d.left()));
80   //curOrtho2d.setRight(min(center+new_max_width, maxOrtho2d.right()));
81   curOrtho2d.setLeft(center-new_max_width);
82   curOrtho2d.setRight(center+new_max_width);
83   emit viewportChanged();
84 }
85
86 void PathScene::setViewportX(float x)
87 {
88   //hopefully this calculates a sufficiently reasonable == for a float
89   if (x != viewport_center )
90   {
91     updateViewport(x, zoom);
92     viewport_center = x;
93     update();
94   }
95 }
96
97 void PathScene::setZoom(int new_zoom)
98 {
99   if (zoom != new_zoom) {
100     // try to figure out where we should be now?
101     updateViewport(viewport_center, new_zoom);
102     zoom = new_zoom;
103     update();
104   }
105 }
106
107 void PathScene::setClipPlane(int newZ)
108 {
109   if (clipZ != (double) newZ){
110     clipZ = (double) newZ;
111     update();
112   }
113 }
114
115 void PathScene::loadMupa()
116 {
117   QString caption("Load a mussa parameter file");
118   QString filter("Mussa Parameters (*.mupa)");
119   QString mupa_path = QFileDialog::getOpenFileName(this,
120                                                    caption, 
121                                                    QDir::currentPath(),
122                                                    filter);
123   // user hit cancel?
124   if (mupa_path.isNull()) 
125     return;
126   // try to load safely
127   try {
128     Mussa *m = new Mussa;
129     m->load_mupa_file(mupa_path.toStdString());
130     m->analyze(0, 0, Mussa::TransitiveNway, 0.0);
131     // only switch mussas if we loaded without error
132     delete mussaAnalysis;
133     mussaAnalysis = m;
134     updateScene();
135   } catch (mussa_load_error e) {
136     QString msg("Unable to load ");
137     msg += mupa_path;
138     msg += "\n";
139     msg += e.what();
140     QMessageBox::warning(this, "Load Parameter", msg);
141   }
142   assert (mussaAnalysis != 0);
143 }
144
145 void PathScene::loadSavedAnalysis()
146 {
147   QString caption("Load a previously run analysis");
148   QString muway_dir = QFileDialog::getExistingDirectory(this,
149                                                         caption, 
150                                                         QDir::currentPath());
151   // user hit cancel?
152   if (muway_dir.isNull()) 
153     return;
154   // try to safely load
155   try {
156     Mussa *m = new Mussa;
157     m->load(muway_dir.toStdString());
158     // only switch mussas if we loaded without error
159     delete mussaAnalysis;
160     mussaAnalysis = m;
161     updateScene();
162   } catch (mussa_load_error e) {
163     QString msg("Unable to load ");
164     msg += muway_dir;
165     msg += "\n";
166     msg += e.what();
167     QMessageBox::warning(this, "Load Parameter", msg);
168   }
169   assert (mussaAnalysis != 0);
170 }
171
172 void PathScene::setSoftThreshold(int threshold)
173 {
174   if (mussaAnalysis->get_threshold() != threshold) {
175     mussaAnalysis->set_soft_thres(threshold);
176     mussaAnalysis->nway();
177     update();
178   }
179 }
180
181 ////////////////////
182 // Rendering code
183 void PathScene::initializeGL()
184 {
185   glEnable(GL_DEPTH_TEST);
186   glClearColor(1.0, 1.0, 1.0, 0.0);
187   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
188   glShadeModel(GL_FLAT);
189 }
190
191 void PathScene::resizeGL(int width, int height)
192 {
193   viewport_width = width;
194   viewport_height = height;
195   assert (geometry().width() == width);
196   assert (geometry().height() == height);
197   glViewport(0, 0, (GLsizei)width, (GLsizei)height);
198   glMatrixMode(GL_PROJECTION);
199   glLoadIdentity();
200   // I'm abusing this as Qt and OpenGL disagree about the direction of the
201   // y axis
202   glOrtho(curOrtho2d.left(), curOrtho2d.right(), 
203           curOrtho2d.top(), curOrtho2d.bottom(), 
204           -50.0, clipZ);
205 }
206
207 void PathScene::paintGL()
208 {
209   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
210
211   glPushMatrix();
212   glMatrixMode(GL_PROJECTION);
213   glLoadIdentity();
214   glOrtho(curOrtho2d.left(), curOrtho2d.right(), 
215           curOrtho2d.top(), curOrtho2d.bottom(), 
216           -50.0, clipZ);
217   glMatrixMode(GL_MODELVIEW);
218   mussaesque();
219   glEnable(GL_BLEND);
220   glDepthMask(GL_FALSE);
221   if (selectedMode && !drawingBand) {
222     glColor4f(0.6, 0.6, 0.6, 0.9);
223     glRectf(previousBand.x(), previousBand.y(),
224             previousBand.right(), previousBand.bottom());
225   }
226   glDepthMask(GL_TRUE);
227   glDisable(GL_BLEND);
228   glPopMatrix();
229   glFlush();
230 }
231
232 void PathScene::updateScene()
233 {
234   // Delete old glsequences
235   // FIXME: does this actually free the memory from the new'ed GlSequences?
236   tracks.clear();
237
238   // save a reference to our GlSequences
239   GlSequence *gl_seq;
240   float y = mussaAnalysis->sequences().size() * 100 ;
241   float max_base_pairs = 0;
242   typedef vector<Sequence>::const_iterator seqs_itor_t;
243   for(seqs_itor_t seq_itor = mussaAnalysis->sequences().begin();
244       seq_itor != mussaAnalysis->sequences().end();
245       ++seq_itor)
246   {
247     y = y - 100;
248     gl_seq = new GlSequence(*seq_itor);
249     gl_seq->setX(0);
250     gl_seq->setY(y);
251     if (gl_seq->length() > max_base_pairs ) max_base_pairs = gl_seq->length();
252     tracks.push_back( *gl_seq );
253   }
254   maxOrtho2d.setWidth(max_base_pairs + 100.0);
255   maxOrtho2d.setHeight((mussaAnalysis->sequences().size()) * 100 );
256   curOrtho2d = maxOrtho2d;
257   viewport_center = (curOrtho2d.right()-curOrtho2d.left())/2+curOrtho2d.left();
258 }
259
260 void PathScene::processSelection(GLuint hits, GLuint buffer[], GLuint bufsize)
261 {
262   const size_t pathz_count = mussaAnalysis->paths().refined_pathz.size();
263   GLuint *ptr;
264   GLuint names;
265   float z1;
266   float z2;
267   GLuint objtype;
268   GLuint objid;
269
270   selectedPaths.clear();
271   selectedPaths.reserve(pathz_count);
272   selectedPaths.insert(selectedPaths.begin(), pathz_count, false);
273   selectedTrack = 0x7fffffff;
274   
275   std::cout << "hits = " << hits << " " << pathz_count << std::endl;
276   ptr = (GLuint *) buffer;
277   if (hits > 0)
278     selectedMode = true;
279   for (GLuint i=0; i < hits; ++i)
280   {
281     if ((i + 5) > bufsize) {
282       std::clog << "*** selection overflow***" << std::endl;
283     } else {
284       names = *ptr++;
285       z1 = ((float)*ptr++)/0x7fffffff;
286       z2 = ((float)*ptr++)/0x7fffffff;
287       objtype = *ptr++;
288       objid = *ptr++;
289       if (names != 2) {
290         std::clog << "wrong number of glNames, selection is having trouble ";
291         std::clog << " got " << names << std::endl;
292         std::clog << " names: " ;
293         for (GLuint j = 0 ; j < names-2; ++j) {
294           std::clog << *ptr++ << " ";
295         }
296         std::clog << endl;
297         return;
298       } 
299       switch (objtype) {
300         case MussaPaths:
301           selectedPaths[objid] = true;
302         break;
303         case MussaTracks:
304           if (objid < selectedTrack) {
305             selectedTrack = objid; 
306           }
307         break;
308       }
309     }
310   }
311 }
312
313 void PathScene::mousePressEvent( QMouseEvent *e)
314 {
315   drawingBand = true;
316   std::cout << "x=" << e->x() << " y=" << e->y() << std::endl;
317
318   selectedMode = false;
319   bandOrigin = e->pos();
320   if (!rubberBand)
321     rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
322   
323   rubberBand->setGeometry(QRect(bandOrigin, QSize()));
324   rubberBand->show();
325 }
326
327 void PathScene::mouseMoveEvent( QMouseEvent *e)
328 {
329   if (drawingBand)
330     rubberBand->setGeometry(QRect(bandOrigin, e->pos()).normalized());
331 }
332
333 void dumpRect(const QRect &r)
334 {
335   std::cout << "x=" << r.x() << " y=" << r.y() 
336             << " w=" << r.width() << " h=" << r.height() << std::endl;
337 }
338
339 void PathScene::mouseReleaseEvent( QMouseEvent *e)
340 {
341   drawingBand = false;
342   rubberBand->hide();
343   QRect r = QRect(bandOrigin, e->pos()).normalized();
344   bandOrigin = r.topLeft();
345   std::cout << "band ";
346   dumpRect(r);
347
348   std::cout << "window ";
349   dumpRect(geometry());
350
351   GLfloat x_scale = curOrtho2d.width()/((float)geometry().width());
352   GLfloat y_scale = curOrtho2d.height()/((float)geometry().height());
353   GLfloat x_left = curOrtho2d.left() + (r.x()*x_scale);
354   GLfloat x_right = x_left + r.width() * x_scale;
355   // using QRectF with Y axis swapped
356   GLfloat y_top = curOrtho2d.bottom()-(r.y()*y_scale);
357   GLfloat y_bottom = y_top - r.height() * y_scale;
358   previousBand.setCoords(x_left, y_top, x_right, y_bottom);
359   std::cout << x_left << " " << x_right << " " << y_top << " " << y_bottom 
360             << std::endl;
361
362   // hopefully this will make a buffer big enough to receive 
363   // everything being selected
364   const size_t pathz_count = mussaAnalysis->paths().refined_pathz.size();
365   const GLuint select_buf_size = 1 + 5 * (pathz_count + tracks.size()) ;
366   GLuint selectBuf[select_buf_size];
367   glSelectBuffer(select_buf_size, selectBuf);
368   GLint hits;
369
370   (void)glRenderMode(GL_SELECT);
371   glPushMatrix();
372   glMatrixMode(GL_PROJECTION);
373   glLoadIdentity();
374   glOrtho(x_left, x_right, y_top, y_bottom, -50.0, 50.0);
375   glMatrixMode(GL_MODELVIEW);
376   glLoadIdentity();
377  
378   mussaesque();
379   glFlush();
380
381   glPopMatrix();
382   hits = glRenderMode(GL_RENDER);
383   processSelection(hits, selectBuf, select_buf_size);
384
385   resizeGL(geometry().width(), geometry().height());
386 }
387
388
389 //////
390 // openGl rendering code
391
392 void PathScene::draw_tracks() const
393 {
394   glPushMatrix();
395   glPushName(0);
396   for (vector<GlSequence>::size_type i = 0; i != tracks.size(); ++i )
397   {
398     glLoadName(i);
399     tracks[i].draw(curOrtho2d.left(), curOrtho2d.right());
400   }
401   glPopName();
402   glPopMatrix();
403 }
404
405 void PathScene::draw_lines() const
406 {
407   GLfloat x;
408   GLfloat y;
409   GLuint pathid=0;
410   GLint objid=0;
411   bool reversed = false;
412   bool prevReversed = false;
413   const NwayPaths& nway = mussaAnalysis->paths();
414
415   glPushName(pathid);
416   glLineWidth(2);
417   vector<GlSequence>::const_iterator track_itor;
418   
419   typedef list<ExtendedConservedPath> conserved_paths;
420   typedef conserved_paths::const_iterator const_conserved_paths_itor;
421   for(const_conserved_paths_itor path_itor = nway.refined_pathz.begin();
422       path_itor != nway.refined_pathz.end();
423       ++path_itor, ++objid)
424   {
425     track_itor = tracks.begin();
426     // since we were drawing to the start of a window, and opengl lines
427     // are centered around the two connecting points our lines were slightly
428     // offset. the idea of window_offset is to adjust them to the
429     // right for forward compliment or left for reverse compliment
430     // FIXME: figure out how to unit test these computations
431     GLfloat window_offset = (path_itor->window_size)/2.0;
432     
433     glBegin(GL_LINE_STRIP);
434     for (vector<int>::const_iterator sp_itor = path_itor->begin();
435          sp_itor != path_itor->end();
436          ++sp_itor, ++track_itor)
437     {
438       x = *sp_itor;
439       y = track_itor->y();
440       // at some point when we modify the pathz data structure to keep
441       // track of the score we can put grab the depth here.
442       //
443       // are we reverse complimented? 
444       if ( x>=0) {
445         reversed = false;
446       } else {
447         reversed = true;
448         x = -x; // make positive
449       }
450       if (!reversed)
451         x += window_offset; // move right for forward compliment
452       else
453         x -= window_offset; // move left for reverse compliment
454       // the following boolean implements logical xor
455       if ( (reversed || prevReversed) && (!reversed || !prevReversed)) { 
456         // we have a different orientation
457         if (not selectedMode or selectedPaths[objid] == true) {
458           // if we have nothing selected, or we're the highlight, be bright
459           glColor3f(0.0, 0.0, 1.0);
460         } else {
461           // else be dim
462           glColor3f(0.7, 0.7, 1.0);
463         }
464       } else {
465         // both current and previous path have the same orientation
466         if (not selectedMode or selectedPaths[objid] == true) {
467           glColor3f(1.0, 0.0, 0.0);
468         } else {
469           glColor3f(1.0, 0.7, 0.7);
470         }
471       }
472       prevReversed = reversed;
473       glVertex3f(x, y, -1.0);
474     }
475     glEnd();
476     glLoadName(++pathid);
477   }
478   glPopName();
479 }
480
481 GLuint PathScene::make_line_list()
482 {
483   GLuint line_list = glGenLists(1);
484   glNewList(line_list, GL_COMPILE);
485
486   draw_lines();
487
488   glEndList();
489   return line_list;
490
491 }
492
493 void PathScene::mussaesque()
494 {
495   //static GLuint theLines = make_line_list();
496
497   glInitNames();
498   glPushName(MussaPaths);
499   //glCallList(theLines);
500   draw_lines();
501   glLoadName(MussaTracks);
502   draw_tracks();
503   glPopName();
504 }
505