8f87a1ffa13f1fdd6acab9f057342b79c640744b
[mussa.git] / qui / MussaWindow.cpp
1 #include "py/python.hpp"
2 #include "qui/MussaWindow.hpp"
3 #include "mussa_exceptions.hpp"
4
5 #include <QAction>
6 #include <QApplication>
7 #include <QAssistantClient>
8 #include <QCloseEvent>
9 #include <QDir>
10 #include <QFileDialog>
11 #include <QHBoxLayout>
12 #include <QIcon>
13 #include <QMenuBar>
14 #include <QMessageBox>
15 #include <QScrollBar>
16 #include <QStatusBar>
17 #include <QString>
18 #include <QStringList>
19 #include <QWhatsThis>
20
21 #include <memory>
22 #include <iterator>
23 #include <iostream>
24
25 #include <boost/filesystem/path.hpp>
26 #include <boost/filesystem/operations.hpp>
27 namespace fs = boost::filesystem;
28 #include <boost/bind.hpp>
29
30 using namespace std;
31
32 MussaWindow::MussaWindow(Mussa *analysis_, QWidget *parent) :
33   QMainWindow(parent),
34   analysis(analysis_),
35   motif_editor(0),
36   setup_analysis_dialog(this),
37   browser(this),
38   mussaViewTB("Path Views"),
39   zoom(),
40   threshold(),
41   progress_dialog(0),
42   aboutAction(0),
43   closeAction(0),
44   createNewAnalysisAction(0),
45   createSubAnalysisAction(0),
46   editMotifsAction(0),
47   loadMotifListAction(0),
48   loadMupaAction(0),
49   loadSavedAnalysisAction(0),
50   mussaManualAssistantAction(0),
51   newMussaWindowAction(0),
52   saveMotifListAction(0),
53   showMussaViewToolbarAction(0),
54   toggleMotifsAction(0),
55   saveBrowserPixmapAction(0),
56   whatsThisAction(0),
57   viewMussaAlignmentAction(0),
58   manualAssistant(0)
59 {
60   setupActions();
61   setupMainMenu();
62   setupAssistant();
63
64   //This next setWhatsThis function prevents
65   // a segfault when using WhatsThis feature with 
66   // opengl widget.
67   //scene->setWhatsThis(tr("Mussa in OpenGL!"));
68   setCentralWidget(&browser);
69   // well updatePosition isn't quite right as we really just need
70   // to call update()
71   connect(this, SIGNAL(changedAnnotations()), &browser, SLOT(update()));
72
73   //mussaViewTB.addAction(toggleMotifsAction);
74   mussaViewTB.addWidget(&zoom);
75   
76   connect(&zoom, SIGNAL(valueChanged(double)), 
77           &browser, SLOT(setZoom(double)));
78   
79   // threshold range is set in updateAnalysis
80   
81   //scene->setClipPlane(20);
82   // FIXME: for when we get the paths drawn at the appropriate depth
83   //connect(&threshold, SIGNAL(thresholdChanged(int)),
84   //        this, SLOT(setClipPlane(int)));
85   connect(&threshold, SIGNAL(thresholdChanged(int)),
86           this, SLOT(setSoftThreshold(int)));
87   mussaViewTB.addWidget(&threshold);
88
89   addToolBar(&mussaViewTB);
90
91   statusBar()->showMessage("Welcome to mussa", 2000);
92   connect(analysis, SIGNAL(progress(const std::string&, int, int)),
93           this, SLOT(updateProgress(const std::string&, int, int)));
94   updateAnalysis();
95 }
96
97 void MussaWindow::setAnalysis(Mussa *new_analysis)
98 {
99   if (new_analysis != 0) {
100     // only switch mussas if we loaded without error
101     clear();
102     delete analysis;
103     analysis = new_analysis;
104     setWindowTitle(analysis->get_name().c_str());
105     updateAnalysis();
106   }
107 }
108
109 void MussaWindow::setupActions()
110 {
111   // we really don't want to run this more than once.
112   assert (closeAction == 0);
113
114   // the ever popular about box
115   aboutAction = new QAction(tr("&About"), this);
116   connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
117   aboutAction->setIcon(QIcon(":/icons/info.png"));
118
119   // add exit
120   closeAction = new QAction(tr("&Close"), this);
121   closeAction->setStatusTip(tr("Close this window"));
122   connect(closeAction, SIGNAL(triggered()), this, SLOT(close()));
123   closeAction->setIcon(QIcon(":/icons/exit.png"));
124   
125   createNewAnalysisAction = new QAction(tr("Create Analysis"), this);
126   connect(createNewAnalysisAction, SIGNAL(triggered()), 
127           this, SLOT(createNewAnalysis()));
128   createNewAnalysisAction->setIcon(QIcon(":/icons/filenew.png"));
129   
130   createSubAnalysisAction = new QAction(tr("Add to Subanalysis"), this);
131   connect(createSubAnalysisAction, SIGNAL(triggered()), 
132           this, SLOT(createSubAnalysis()));
133
134   saveAnalysisAction = new QAction(tr("&Save Analysis"), this);
135   connect(saveAnalysisAction, SIGNAL(triggered()), 
136           this, SLOT(saveAnalysis()));
137   saveAnalysisAction->setIcon(QIcon(":/icons/filesave.png"));
138
139   saveAnalysisAsAction = new QAction(tr("Save Analysis &As"), this);
140   connect(saveAnalysisAsAction, SIGNAL(triggered()), 
141           this, SLOT(saveAnalysisAs()));
142   saveAnalysisAsAction->setIcon(QIcon(":/icons/filesave.png"));
143
144   editMotifsAction = new QAction(tr("Edit Motifs"), this);;
145   connect(editMotifsAction, SIGNAL(triggered()), this, SLOT(editMotifs()));
146   
147   loadMotifListAction = new QAction(tr("Load Motif List"), this);
148   connect(loadMotifListAction, SIGNAL(triggered()), 
149           this, SLOT(loadMotifList()));
150   loadMotifListAction->setIcon(QIcon(":/icons/fileopen.png"));
151   
152   loadMupaAction = new QAction(tr("Create Analysis from File"), this);
153   connect(loadMupaAction, SIGNAL(triggered()), 
154           this, SLOT(loadMupa()));
155   loadMupaAction->setIcon(QIcon(":/icons/fileopen.png"));
156
157   loadSavedAnalysisAction = new QAction(tr("Load Existing &Analysis"), this);
158   connect(loadSavedAnalysisAction, SIGNAL(triggered()), 
159           this, SLOT(loadSavedAnalysis()));
160   loadSavedAnalysisAction->setIcon(QIcon(":/icons/fileopen.png"));
161
162   mussaManualAssistantAction = new QAction(tr("Mussagl Manual..."), this);
163   mussaManualAssistantAction->setIcon(QIcon(":/icons/contents.png"));
164   connect(mussaManualAssistantAction, SIGNAL(triggered()),
165           this, SLOT(showManual()));
166
167   newMussaWindowAction = new QAction(tr("&New Mussa Window"), this);
168   newMussaWindowAction->setStatusTip("open another mussa window to allow comparing results");
169   connect(newMussaWindowAction, SIGNAL(triggered()), 
170           this, SLOT(newMussaWindow()));
171   newMussaWindowAction->setIcon(QIcon(":/icons/window_new.png"));
172
173   saveMotifListAction = new QAction(tr("Save Motifs"), this);
174   connect(saveMotifListAction, SIGNAL(triggered()), 
175           this, SLOT(saveMotifList()));
176   saveMotifListAction->setIcon(QIcon(":/icons/filesave.png"));
177
178   showMussaViewToolbarAction = new QAction(tr("Show Toolbar"), this);
179   connect(showMussaViewToolbarAction, SIGNAL(triggered()), 
180           this, SLOT(showMussaToolbar()));
181   showMussaViewToolbarAction->setCheckable(true);
182   showMussaViewToolbarAction->setChecked(true);
183
184   toggleMotifsAction = new QAction(tr("Toggle Motifs"), this);
185   connect(toggleMotifsAction, SIGNAL(triggered()), 
186           this, SLOT(toggleMotifs()));
187   toggleMotifsAction->setCheckable(true);
188   toggleMotifsAction->setIcon(QIcon(":/icons/motif_icon.png"));
189   toggleMotifsAction->setWhatsThis(tr("Toggle motif annotations on/off\n\n"
190                                    "You can load motif annotations via "
191                                    "'File->Load Motif List' menu option."));
192
193   //Save pixel map action
194   saveBrowserPixmapAction = new QAction(tr("Save to image..."), this);
195   connect(saveBrowserPixmapAction, (SIGNAL(triggered())),
196           &browser, SLOT(promptSaveBrowserPixmap()));
197   saveBrowserPixmapAction->setIcon(QIcon(":/icons/image2.png"));
198
199   viewMussaAlignmentAction = new QAction(tr("View sequence alignment"), this);
200   connect(viewMussaAlignmentAction, SIGNAL(triggered()),
201           this, SLOT(viewMussaAlignment() ));
202   viewMussaAlignmentAction->setWhatsThis(tr("Create a zoomed in window "
203                                             "showing alignment of the seqcomp "
204                                             "defined paths"));
205
206   whatsThisAction = QWhatsThis::createAction(this);
207   whatsThisAction->setIcon(QIcon(":/icons/help.png"));
208
209
210 }
211
212 void MussaWindow::closeEvent(QCloseEvent *event)
213 {
214   if(isClearingAnalysisSafe()) {
215     event->accept();
216   } else {
217     event->ignore();
218   }
219 }
220
221 void MussaWindow::setupMainMenu()
222 {
223   // we need to run setupActions first
224   assert (closeAction != 0);
225
226   QMenu *newMenu = menuBar()->addMenu(tr("&File"));
227   
228   newMenu->addAction(newMussaWindowAction);
229   newMenu->addAction(createNewAnalysisAction);
230   newMenu->addAction(loadMupaAction);
231   newMenu->addAction(loadSavedAnalysisAction);
232   newMenu->addAction(saveAnalysisAction);
233   newMenu->addAction(saveAnalysisAsAction);
234   newMenu->addSeparator();
235   newMenu->addAction(loadMotifListAction);
236   newMenu->addAction(saveMotifListAction);
237   newMenu->addSeparator();
238   newMenu->addAction(saveBrowserPixmapAction);
239   newMenu->addSeparator();
240   newMenu->addAction(closeAction);
241
242   newMenu = menuBar()->addMenu(tr("&Edit"));
243   newMenu->addAction(editMotifsAction);
244   newMenu->addAction(&browser.getCopySelectedSequenceAsFastaAction());
245   newMenu->addAction(createSubAnalysisAction);
246  
247   newMenu = menuBar()->addMenu(tr("&View"));
248   newMenu->addAction(viewMussaAlignmentAction);
249   newMenu->addAction(showMussaViewToolbarAction);
250
251   newMenu = menuBar()->addMenu(tr("&Help"));
252   newMenu->addAction(mussaManualAssistantAction);
253   newMenu->addAction(whatsThisAction);
254   newMenu->addSeparator();
255   newMenu->addAction(aboutAction);
256
257   // add some extra features to the context menu
258   QMenu& popupMenu = browser.getPopupMenu();
259   popupMenu.addAction(viewMussaAlignmentAction);
260   popupMenu.addAction(createSubAnalysisAction);
261 }
262
263 void MussaWindow::setupAssistant()
264 {
265 #if defined(QT_ASSISTANT_FOUND)
266   QStringList manualAssistantArgs;
267   manualAssistantArgs = QStringList();
268   manualAssistantArgs << "-profile" << "./doc/manual/mussagl_manual.adp";
269   manualAssistant = new QAssistantClient("assistant", this);
270   manualAssistant->setArguments(manualAssistantArgs);
271   connect(manualAssistant, SIGNAL(error(QString)),
272           this, SLOT(assistantError(QString)));
273 #endif
274 }
275   
276 void MussaWindow::about()
277 {
278   QString msg("Welcome to Multiple Species Sequence Analysis\n"
279               "(c) 2005-2006 California Institute of Technology\n"
280               "Tristan De Buysscher, Diane Trout\n");
281    msg += "\n\r";
282    msg += "Path: ";
283    msg += QDir::currentPath();
284    msg += "\n";
285    msg += "OpenGL: ";
286    msg += (char *)glGetString(GL_VERSION);
287    msg += "\n";
288    QMessageBox::about(this, tr("About mussa"), msg);
289 }
290
291 void MussaWindow::clear()
292 {
293   aligned_windows.clear();
294   browser.clear();
295 }
296
297 void MussaWindow::createNewAnalysis()
298 {
299   try {
300     // ideally we should open a new window if there's an analysis
301     // but this should work for the moment.
302     if (not isClearingAnalysisSafe()) return;
303
304     if (setup_analysis_dialog.exec()) {
305       Mussa *m = 0;
306       m = setup_analysis_dialog.getMussa();
307       setAnalysis(m);
308     }
309   } catch(mussa_error e) {
310     QString msg(e.what());
311     QMessageBox::warning(this, tr("Create New Analysis"), msg);
312   }
313 }
314
315 void MussaWindow::createSubAnalysis()
316 {
317   list<SequenceLocation> result;
318   SequenceLocationModel& model = subanalysis_window.getModel();
319   browser.copySelectedTracksAsSeqLocation(result);
320   for(list<SequenceLocation>::iterator result_itor = result.begin();
321       result_itor != result.end();
322       ++result_itor)
323   {
324     model.push_back(*result_itor);
325   }
326
327   if (not subanalysis_window.isVisible()) {
328     subanalysis_window.show();
329   }
330 }
331
332 void MussaWindow::saveAnalysis()
333 {
334   // if we've got an analysis
335   if (analysis and not analysis->empty()) {
336     // if it doesn't have a name we need to pick one
337     if (analysis->get_analysis_path().empty()) {
338       saveAnalysisAs();
339     }      
340     // if we've got a name, has it changed any?
341     else if (analysis->is_dirty()) {
342       analysis->save();
343     }
344   }
345 }
346
347 void MussaWindow::saveAnalysisAs()
348 {
349   std::auto_ptr<QFileDialog> dialog(new QFileDialog(this));
350   dialog->setAcceptMode(QFileDialog::AcceptSave);
351   dialog->setFileMode(QFileDialog::AnyFile);
352
353   QStringList fileNames;
354   if (not dialog->exec()) {
355     return;
356   }
357   fileNames = dialog->selectedFiles();
358    
359   if (fileNames.size() != 1) {
360     return;
361   }
362
363   fs::path save_path(fileNames[0].toStdString());
364   // do you want to overwrite?
365   if (fs::exists(save_path) and 
366       QMessageBox::question(
367         this,
368         tr("Overwrite File? -- Mussa"),
369         tr("A file called %1 already exists"
370            "do you want to overwrite it?")
371            .arg(fileNames[0]),
372         tr("&Yes"), tr("&No"),
373         QString(), 0, 1)
374       ) {
375     return;
376   }
377   analysis->save(save_path);
378 }
379
380 bool MussaWindow::isClearingAnalysisSafe()
381 {
382   if (analysis and not analysis->empty() and analysis->is_dirty()) {
383     switch (QMessageBox::question(
384       this,
385       tr("Save Unsaved Changes -- Mussa"),
386       tr("There are unsaved changes,\ndo you want to save?"),
387       tr("&Yes"), tr("&No"), tr("&Cancel"),
388       0, 2)) {
389     case 0:
390       // save
391       saveAnalysis();
392       break;
393     case 1:
394       // don't save
395       break;
396     case 2:
397       // don't replace 
398       return false;
399       break;
400     default:
401       // error
402       throw runtime_error("isClearingAnalysis QMesageBox failure");
403     }
404   } 
405   // if we're here we've been saved and can replace
406   return true;
407 }
408
409 void MussaWindow::editMotifs()
410 {
411   if (motif_editor != 0) {
412     motif_editor->hide();
413     delete motif_editor;
414   }
415   motif_editor = new MotifEditor(analysis);
416   connect(motif_editor, SIGNAL(changedMotifs()), 
417           this, SLOT(updateAnnotations()));
418   motif_editor->show();
419 }
420
421 void MussaWindow::loadMotifList()
422 {
423   QString caption("Load a motif list");
424   QString filter("Motif list(*.txt *.mtl)");
425   QString path = QFileDialog::getOpenFileName(this,
426                                                    caption, 
427                                                    QDir::currentPath(),
428                                                    filter);
429   // user hit cancel?
430   if (path.isNull()) 
431     return;
432   // try to load safely
433   try {
434     fs::path converted_path(path.toStdString(), fs::native);
435     analysis->load_motifs(converted_path);
436   } catch (runtime_error e) {
437     QString msg("Unable to load ");
438     msg += path;
439     msg += "\n";
440     msg += e.what();
441     QMessageBox::warning(this, "Load Motifs", msg);
442   }
443   assert (analysis != 0);
444 }
445
446 void MussaWindow::saveMotifList()
447 {
448   NotImplementedBox();
449 }
450
451 void MussaWindow::loadMupa()
452 {
453   QString caption("Load a mussa parameter file");
454   QString filter("Mussa Parameters (*.mupa)");
455   QString mupa_path = QFileDialog::getOpenFileName(this,
456                                                    caption, 
457                                                    QDir::currentPath(),
458                                                    filter);
459   // user hit cancel?
460   if (mupa_path.isNull()) 
461     return;
462   // try to load safely
463   try {
464     // ideally we should open a new window if there's an analysis
465     // but this should work for the moment.
466     if (not isClearingAnalysisSafe()) return;
467
468     Mussa *m = new Mussa;
469     fs::path converted_path(mupa_path.toStdString(), fs::native);
470     connect(m, SIGNAL(progress(const std::string&, int, int)),
471             this, SLOT(updateProgress(const std::string&, int, int)));
472     m->load_mupa_file(converted_path);
473     m->analyze();
474     setAnalysis(m);
475     setWindowTitle(converted_path.native_file_string().c_str());
476   } catch (mussa_load_error e) {
477     QString msg("Unable to load ");
478     msg += mupa_path;
479     msg += "\n";
480     msg += e.what();
481     QMessageBox::warning(this, "Load Parameter", msg);
482   }
483   assert (analysis != 0);
484 }
485
486 void MussaWindow::loadSavedAnalysis()
487 {
488   QString caption("Load a previously run analysis");
489   QString muway_dir = QFileDialog::getExistingDirectory(this,
490                                                         caption, 
491                                                         QDir::currentPath());
492   // user hit cancel?
493   if (muway_dir.isNull()) 
494     return;
495   // try to safely load
496   try {
497     // ideally we should open a new window if there's an analysis
498     // but this should work for the moment.
499     if (not isClearingAnalysisSafe()) return;
500
501     Mussa *m = new Mussa;
502     fs::path converted_path(muway_dir.toStdString(), fs::native);
503     connect(m, SIGNAL(progress(const std::string&, int, int)),
504             this, SLOT(updateProgress(const std::string&, int, int)));
505     m->load(converted_path);
506     // only switch mussas if we loaded without error
507     setAnalysis(m);
508     setWindowTitle(converted_path.native_file_string().c_str());
509   } catch (mussa_load_error e) {
510     QString msg("Unable to load ");
511     msg += muway_dir;
512     msg += "\n";
513     msg += e.what();
514     QMessageBox::warning(this, "Load Parameter", msg);
515   }
516   assert (analysis != 0);
517 }
518
519 void MussaWindow::newMussaWindow()
520 {
521   Mussa *a = new Mussa();
522   MussaWindow *win = new MussaWindow(a);
523   win->show();
524 }
525
526 void MussaWindow::setSoftThreshold(int threshold)
527 {
528   if (analysis->get_soft_threshold() != threshold) {
529     analysis->set_soft_threshold(threshold);
530     analysis->nway();
531     updateLinks();
532     update();
533   }
534 }
535
536 void MussaWindow::showMussaToolbar()
537 {
538   if (mussaViewTB.isVisible())
539     mussaViewTB.hide();
540   else
541     mussaViewTB.show();
542 }
543
544 void MussaWindow::toggleMotifs()
545 {
546   NotImplementedBox();
547 }
548
549 void MussaWindow::showManual()
550 {
551 #if QT_QTASSISTANT_FOUND
552   manualAssistant->openAssistant();
553 #else
554   try {
555     boost::python::object webopen = get_py()["webbrowser.open"];
556     webopen("http://woldlab.caltech.edu/~king/mussagl_manual/");
557   } catch( boost::python::error_already_set ) {
558     PyErr_Print();
559   }
560 #endif //QT_QTASSISTANT_FOUND
561 }
562
563 void MussaWindow::assistantError(QString message)
564 {
565   //std::cout << "QAssistantError: " << message.toStdString() << "\n";
566   QMessageBox::warning ( this, "Warning: Mussagl Manual", message, 
567                          QMessageBox::Ok, 
568                          QMessageBox::NoButton);
569 }
570
571 void MussaWindow::NotImplementedBox()
572 {
573   QMessageBox::warning(this, QObject::tr("mussa"), QObject::tr("Not implemented yet"));
574 }      
575
576 void MussaWindow::viewMussaAlignment()
577 {
578   const set<int>& selected_paths = browser.selectedPaths();
579   if (selected_paths.size() == 0 ) {
580     QMessageBox::warning(this, 
581                          QObject::tr("mussa"),
582                          QObject::tr("you should probably select some paths "
583                                      "first"));
584   } else {
585     boost::shared_ptr<MussaAlignedWindow> ma_win( 
586       new MussaAlignedWindow(*analysis, selected_paths)
587     );
588
589     aligned_windows.push_back(ma_win);
590     connect(this, SIGNAL(changedAnnotations()), 
591             aligned_windows.back().get(), SLOT(update()));
592     aligned_windows.back()->show();
593   }
594 }
595                         
596 void MussaWindow::updateAnalysis()
597 {
598   threshold.setRange(analysis->get_threshold(),analysis->get_window());
599
600   const Mussa::vector_sequence_type& seqs = analysis->sequences();
601   browser.setSequences(seqs, analysis->colorMapper());
602   updateLinks();
603   browser.zoomOut();
604   zoom.setValue(browser.zoom());
605 }
606
607 void MussaWindow::updateAnnotations()
608 {
609   // motifs were changed in the sequences by 
610   // Mussa::update_sequences_motifs
611   emit changedAnnotations();
612   browser.update();
613 }
614
615 void MussaWindow::updateLinks()
616 {
617   browser.clear_links();
618   bool reversed = false;
619   const NwayPaths& nway = analysis->paths();
620
621   typedef list<ConservedPath> conserved_paths;
622   typedef conserved_paths::const_iterator const_conserved_paths_itor;
623   for(const_conserved_paths_itor path_itor = nway.refined_pathz.begin();
624       path_itor != nway.refined_pathz.end();
625       ++path_itor)
626   {
627     // since we were drawing to the start of a window, and opengl lines
628     // are centered around the two connecting points our lines were slightly
629     // offset. the idea of window_offset is to adjust them to the
630     // right for forward compliment or left for reverse compliment
631     // FIXME: figure out how to unit test these computations
632     //GLfloat window_offset = (path_itor->window_size)/2.0;
633
634     size_t track_len = path_itor->track_indexes.size();
635     vector<int> normalized_path;
636     normalized_path.reserve(track_len);
637     vector<bool> rc_flags(false, track_len);
638     for (size_t track_i=0; track_i != track_len; ++track_i)
639     {
640       int x = path_itor->track_indexes[track_i];
641       // at some point when we modify the pathz data structure to keep
642       // track of the score we can put grab the depth here.
643       //
644       // are we reverse complimented?
645       if ( x>=0) {
646         reversed = false;
647       } else {
648         reversed = true;
649         // make positive 
650         x = -x;
651       }
652       normalized_path.push_back(x);
653       rc_flags.push_back(reversed);
654     }
655     browser.link(normalized_path, rc_flags, path_itor->window_size);
656   }
657   browser.update();
658 }
659
660 void 
661 MussaWindow::updateProgress(const string& description, int current, int max)
662 {  
663   // if we're done  
664   if (current == max) {
665     if (progress_dialog != 0) {
666       progress_dialog->hide();
667       delete progress_dialog;
668       progress_dialog = 0;
669     }
670   } else {
671     // if we're starting, create the dialog
672     if (progress_dialog == 0) {
673       QString desc(description.c_str());
674       QString cancel("Cancel");
675       progress_dialog = new QProgressDialog(desc, cancel, current, max, this);
676       progress_dialog->show();
677     } else {
678       // just update the dialog
679       progress_dialog->setValue(current);
680     }
681   }
682   qApp->processEvents();
683 }