Progress towards MussaSetupDialog (Currently will cause crash! Be warned!)
[mussa.git] / qui / MussaWindow.cpp
1 #include <QAction>
2 #include <QDir>
3 #include <QFileDialog>
4 #include <QHBoxLayout>
5 #include <QIcon>
6 #include <QMenuBar>
7 #include <QMessageBox>
8 #include <QScrollBar>
9 #include <QStatusBar>
10 #include <QString>
11 #include <QWhatsThis>
12
13 #include "qui/MussaWindow.hpp"
14 #include "qui/mussa_setup_dialog/MussaSetupDialog.hpp"
15 #include "mussa_exceptions.hpp"
16
17 #include <iostream>
18
19 using namespace std;
20
21 MussaWindow::MussaWindow(Mussa *analysis_, QWidget *parent) :
22   QMainWindow(parent),
23   analysis(analysis_),
24   motif_editor(0),
25   browser(this),
26   mussaViewTB("Path Views"),
27   zoomBox(),
28   threshold(),
29   zoomLabel(),
30   closeAction(0) // initialize one of the pointers to null as a saftey flag
31 {
32   setupActions();
33   setupMainMenu();
34
35   //This next setWhatsThis function prevents
36   // a segfault when using WhatsThis feature with 
37   // opengl widget.
38   //scene->setWhatsThis(tr("Mussa in OpenGL!"));
39   setCentralWidget(&browser);
40   // well updatePosition isn't quite right as we really just need
41   // to call update()
42   connect(this, SIGNAL(changedAnnotations()), &browser, SLOT(update()));
43
44   mussaViewTB.addAction(toggleMotifsAction);
45   
46   zoomLabel.setPixmap(QIcon("icons/viewmag.png").pixmap(16, 16));
47   zoomLabel.setToolTip(tr("Zoom"));
48   zoomLabel.setWhatsThis(tr("Zoom magnification factor"));
49   mussaViewTB.addWidget(&zoomLabel);
50
51   zoomBox.setToolTip(tr("Zoom"));
52   zoomBox.setWhatsThis(tr("Zoom magnification factor"));
53   zoomBox.setRange(1,10000000);
54   mussaViewTB.addWidget(&zoomBox);
55   connect(&zoomBox, SIGNAL(valueChanged(int)), 
56           &browser, SLOT(setZoom(int)));
57   
58   threshold.setRange(19, 30);
59   threshold.setThreshold(19);
60   //scene->setClipPlane(20);
61   // FIXME: for when we get the paths drawn at the appropriate depth
62   //connect(&threshold, SIGNAL(thresholdChanged(int)),
63   //        this, SLOT(setClipPlane(int)));
64   connect(&threshold, SIGNAL(thresholdChanged(int)),
65           this, SLOT(setSoftThreshold(int)));
66   mussaViewTB.addWidget(&threshold);
67
68   addToolBar(&mussaViewTB);
69
70   statusBar()->showMessage("Welcome to mussa", 2000);
71   updateAnalysis();
72 }
73
74 void MussaWindow::setupActions()
75 {
76   // we really don't want to run this more than once.
77   assert (closeAction == 0);
78
79   // the ever popular about box
80   aboutAction = new QAction(tr("&About"), this);
81   connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
82   aboutAction->setIcon(QIcon("icons/info.png"));
83
84   // add exit
85   closeAction = new QAction(tr("&Close"), this);
86   closeAction->setStatusTip(tr("Close this window"));
87   connect(closeAction, SIGNAL(triggered()), this, SLOT(close()));
88   closeAction->setIcon(QIcon("icons/exit.png"));
89   
90   createNewAnalysisAction = new QAction(tr("Define Analysis"), this);
91   connect(createNewAnalysisAction, SIGNAL(triggered()), 
92           this, SLOT(createNewAnalysis()));
93   createNewAnalysisAction->setIcon(QIcon("icons/filenew.png"));
94   
95   createSubAnalysisAction = new QAction(tr("Define SubAnalysis"), this);
96   connect(createSubAnalysisAction, SIGNAL(triggered()), 
97           this, SLOT(createSubAnalysis()));
98
99   editMotifsAction = new QAction(tr("Edit Motifs"), this);;
100   connect(editMotifsAction, SIGNAL(triggered()), this, SLOT(editMotifs()));
101   
102   loadMotifListAction = new QAction(tr("Load Motif List"), this);
103   connect(loadMotifListAction, SIGNAL(triggered()), 
104           this, SLOT(loadMotifList()));
105   loadMotifListAction->setIcon(QIcon("icons/fileopen.png"));
106   
107   loadMupaAction = new QAction(tr("Load Mussa Parameters"), this);
108   connect(loadMupaAction, SIGNAL(triggered()), 
109           this, SLOT(loadMupa()));
110   loadMupaAction->setIcon(QIcon("icons/fileopen.png"));
111
112   loadSavedAnalysisAction = new QAction(tr("Load &Analysis"), this);
113   connect(loadSavedAnalysisAction, SIGNAL(triggered()), 
114           this, SLOT(loadSavedAnalysis()));
115   loadSavedAnalysisAction->setIcon(QIcon("icons/fileopen.png"));
116
117   saveMotifListAction = new QAction(tr("Save Motifs"), this);
118   connect(saveMotifListAction, SIGNAL(triggered()), 
119           this, SLOT(saveMotifList()));
120   saveMotifListAction->setIcon(QIcon("icons/filesave.png"));
121
122   showMussaViewToolbarAction = new QAction(tr("Show Toolbar"), this);
123   connect(showMussaViewToolbarAction, SIGNAL(triggered()), 
124           this, SLOT(showMussaToolbar()));
125   showMussaViewToolbarAction->setCheckable(true);
126   showMussaViewToolbarAction->setChecked(true);
127
128   toggleMotifsAction = new QAction(tr("Toggle Motifs"), this);
129   connect(toggleMotifsAction, SIGNAL(triggered()), 
130           this, SLOT(toggleMotifs()));
131   toggleMotifsAction->setCheckable(true);
132   toggleMotifsAction->setIcon(QIcon("icons/motif_icon.png"));
133   toggleMotifsAction->setWhatsThis(tr("Toggle motif annotations on/off\n\n"
134                                    "You can load motif annotations via "
135                                    "'File->Load Motif List' menu option."));
136
137   //Save pixel map action
138   saveBrowserPixmapAction = new QAction(tr("Save to image..."), this);
139   connect(saveBrowserPixmapAction, (SIGNAL(triggered())),
140           &browser, SLOT(promptSaveBrowserPixmap()));
141   saveBrowserPixmapAction->setIcon(QIcon("icons/image2.png"));
142
143   viewMussaAlignmentAction = new QAction(tr("View mussa alignment"), this);
144   connect(viewMussaAlignmentAction, SIGNAL(triggered()),
145           this, SLOT(viewMussaAlignment() ));
146   viewMussaAlignmentAction->setWhatsThis(tr("Create a zoomed in window "
147                                             "showing alignment of the seqcomp "
148                                             "defined paths"));
149
150   whatsThisAction = QWhatsThis::createAction(this);
151   whatsThisAction->setIcon(QIcon("icons/help.png"));
152
153 }
154
155 void MussaWindow::setupMainMenu()
156 {
157   // we need to run setupActions first
158   assert (closeAction != 0);
159   
160   QMenu *newMenu;
161   newMenu = menuBar()->addMenu(tr("&File"));
162   newMenu->addAction(createNewAnalysisAction);
163   newMenu->addAction(loadMupaAction);
164   newMenu->addAction(loadSavedAnalysisAction);
165   //newMenu->addAction(createSubAnalysisAction);
166   newMenu->addSeparator();
167   newMenu->addAction(loadMotifListAction);
168   newMenu->addAction(saveMotifListAction);
169   newMenu->addSeparator();
170   newMenu->addAction(saveBrowserPixmapAction);
171   newMenu->addSeparator();
172   newMenu->addAction(closeAction);
173
174   newMenu = menuBar()->addMenu(tr("&View"));
175   newMenu->addAction(editMotifsAction);
176   newMenu->addAction(viewMussaAlignmentAction);
177   newMenu->addAction(showMussaViewToolbarAction);
178
179   newMenu = menuBar()->addMenu(tr("&Help"));
180   newMenu->addAction(whatsThisAction);
181   newMenu->addSeparator();
182   newMenu->addAction(aboutAction);
183 }
184   
185 void MussaWindow::about()
186 {
187   QMessageBox::about(this, tr("About mussa"),
188       tr("Welcome to Multiple Species Sequence Analysis\n"
189          "(c) 2005-2006 California Institute of Technology\n"
190          "Tristan De Buysscher, Diane Trout\n"));
191 }
192
193 void MussaWindow::createNewAnalysis()
194 {
195   MussaSetupDialog *msd = new MussaSetupDialog(this);
196   if (msd->exec())
197   {
198     std::cout << "New mussa exp. defined!\n";
199     Mussa *m = 0;
200     m = msd->getMussa();
201     std::cout << " Mussa Object at: " << m << "\n";
202     delete m;
203   }
204   else
205   {
206     std::cout << "New mussa exp. aborted!\n";
207   }
208   delete msd;
209 }
210
211 void MussaWindow::createSubAnalysis()
212 {
213   NotImplementedBox();
214 }
215
216 void MussaWindow::editMotifs()
217 {
218   if (motif_editor != 0) {
219     motif_editor->hide();
220     delete motif_editor;
221   }
222   motif_editor = new MotifEditor(analysis);
223   connect(motif_editor, SIGNAL(changedMotifs()), 
224           this, SLOT(updateAnnotations()));
225   motif_editor->show();
226 }
227
228 void MussaWindow::loadMotifList()
229 {
230   QString caption("Load a motif list");
231   QString filter("Motif list(*.txt *.mtl)");
232   QString path = QFileDialog::getOpenFileName(this,
233                                                    caption, 
234                                                    QDir::currentPath(),
235                                                    filter);
236   // user hit cancel?
237   if (path.isNull()) 
238     return;
239   // try to load safely
240   try {
241     analysis->load_motifs(path.toStdString());
242   } catch (runtime_error e) {
243     QString msg("Unable to load ");
244     msg += path;
245     msg += "\n";
246     msg += e.what();
247     QMessageBox::warning(this, "Load Motifs", msg);
248   }
249   assert (analysis != 0);
250 }
251
252 void MussaWindow::saveMotifList()
253 {
254   NotImplementedBox();
255 }
256
257 void MussaWindow::loadMupa()
258 {
259   QString caption("Load a mussa parameter file");
260   QString filter("Mussa Parameters (*.mupa)");
261   QString mupa_path = QFileDialog::getOpenFileName(this,
262                                                    caption, 
263                                                    QDir::currentPath(),
264                                                    filter);
265   // user hit cancel?
266   if (mupa_path.isNull()) 
267     return;
268   // try to load safely
269   try {
270     Mussa *m = new Mussa;
271     m->load_mupa_file(mupa_path.toStdString());
272     m->analyze(0, 0, Mussa::TransitiveNway, 0.0);
273     // only switch mussas if we loaded without error
274     delete analysis;
275     analysis = m;
276     updateAnalysis();
277   } catch (mussa_load_error e) {
278     QString msg("Unable to load ");
279     msg += mupa_path;
280     msg += "\n";
281     msg += e.what();
282     QMessageBox::warning(this, "Load Parameter", msg);
283   }
284   assert (analysis != 0);
285 }
286
287 void MussaWindow::loadSavedAnalysis()
288 {
289   QString caption("Load a previously run analysis");
290   QString muway_dir = QFileDialog::getExistingDirectory(this,
291                                                         caption, 
292                                                         QDir::currentPath());
293   // user hit cancel?
294   if (muway_dir.isNull()) 
295     return;
296   // try to safely load
297   try {
298     Mussa *m = new Mussa;
299     m->load(muway_dir.toStdString());
300     // only switch mussas if we loaded without error
301     delete analysis;
302     analysis = m;
303     updateAnalysis();
304   } catch (mussa_load_error e) {
305     QString msg("Unable to load ");
306     msg += muway_dir;
307     msg += "\n";
308     msg += e.what();
309     QMessageBox::warning(this, "Load Parameter", msg);
310   }
311   assert (analysis != 0);
312 }
313
314 void MussaWindow::setSoftThreshold(int threshold)
315 {
316   if (analysis->get_soft_thres() != threshold) {
317     analysis->set_soft_thres(threshold);
318     analysis->nway();
319     updateLinks();
320     update();
321   }
322 }
323
324 void MussaWindow::showMussaToolbar()
325 {
326   if (mussaViewTB.isVisible())
327     mussaViewTB.hide();
328   else
329     mussaViewTB.show();
330 }
331
332 void MussaWindow::toggleMotifs()
333 {
334   NotImplementedBox();
335 }
336
337 void MussaWindow::NotImplementedBox()
338 {
339   QMessageBox::warning(this, QObject::tr("mussa"), QObject::tr("Not implemented yet"));
340 }      
341
342 void MussaWindow::viewMussaAlignment()
343 {
344   const set<int>& selected_paths = browser.selectedPaths();
345   if (selected_paths.size() == 0 ) {
346     QMessageBox::warning(this, 
347                          QObject::tr("mussa"),
348                          QObject::tr("you should probably select some paths "
349                                      "first"));
350   } else {
351     MussaAlignedWindow *ma_win = new MussaAlignedWindow(*analysis, 
352                                                         selected_paths);
353     connect(this, SIGNAL(changedAnnotations()), 
354             ma_win, SLOT(update()));
355     aligned_windows.push_back(ma_win);
356     ma_win->show();
357   }
358 }
359                         
360 void MussaWindow::updateAnalysis()
361 {
362   cout << "analysis updated" << endl;
363   for (list<MussaAlignedWindow *>::iterator maw_i = aligned_windows.begin();
364        maw_i != aligned_windows.end();
365        ++maw_i)
366   {
367     (*maw_i)->hide();
368     delete *maw_i;
369   }
370
371   browser.clear();
372   const vector<Sequence>& seqs = analysis->sequences();
373   browser.setSequences(seqs, analysis->colorMapper());
374   updateLinks();
375   browser.zoomOut();
376   cout << "browser zoom " <<  browser.zoom() << endl;
377   zoomBox.setValue(browser.zoom());
378 }
379
380 void MussaWindow::updateAnnotations()
381 {
382   // motifs were changed in the sequences by 
383   // Mussa::update_sequences_motifs
384   emit changedAnnotations();
385   browser.update();
386 }
387
388 void MussaWindow::updateLinks()
389 {
390   browser.clear_links();
391   bool reversed = false;
392   const NwayPaths& nway = analysis->paths();
393
394   typedef list<ExtendedConservedPath> conserved_paths;
395   typedef conserved_paths::const_iterator const_conserved_paths_itor;
396   for(const_conserved_paths_itor path_itor = nway.refined_pathz.begin();
397       path_itor != nway.refined_pathz.end();
398       ++path_itor)
399   {
400     // since we were drawing to the start of a window, and opengl lines
401     // are centered around the two connecting points our lines were slightly
402     // offset. the idea of window_offset is to adjust them to the
403     // right for forward compliment or left for reverse compliment
404     // FIXME: figure out how to unit test these computations
405     //GLfloat window_offset = (path_itor->window_size)/2.0;
406
407     size_t track_len = path_itor->track_indexes.size();
408     vector<int> normalized_path;
409     normalized_path.reserve(track_len);
410     vector<bool> rc_flags(false, track_len);
411     for (size_t track_i=0; track_i != track_len; ++track_i)
412     {
413       int x = path_itor->track_indexes[track_i];
414       // at some point when we modify the pathz data structure to keep
415       // track of the score we can put grab the depth here.
416       //
417       // are we reverse complimented?
418       if ( x>=0) {
419         reversed = false;
420       } else {
421         reversed = true;
422         x = -x; // make positive
423       }
424       normalized_path.push_back(x);
425       rc_flags.push_back(reversed);
426     }
427     browser.link(normalized_path, rc_flags, path_itor->window_size);
428   }
429   browser.update();
430 }
431