~ubuntu-branches/ubuntu/wily/openms/wily

« back to all changes in this revision

Viewing changes to .pc/doc-path-gets-its-own-env-variable/source/VISUAL/APPLICATIONS/TOPPViewBase.C

  • Committer: Package Import Robot
  • Author(s): Filippo Rusconi
  • Date: 2012-11-12 15:58:12 UTC
  • Revision ID: package-import@ubuntu.com-20121112155812-e6mvctvil4ko9npv
Tags: 1.9.0-1
1.9.0 First Debian package release (Closes: #691129).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// -*- mode: C++; tab-width: 2; -*-
 
2
// vi: set ts=2:
 
3
//
 
4
// --------------------------------------------------------------------------
 
5
// --------------------------------------------------------------------------
 
6
//                   OpenMS Mass Spectrometry Framework
 
7
// --------------------------------------------------------------------------
 
8
//  Copyright (C) 2003-2011 -- Oliver Kohlbacher, Knut Reinert
 
9
//
 
10
//  This library is free software; you can redistribute it and/or
 
11
//  modify it under the terms of the GNU Lesser General Public
 
12
//  License as published by the Free Software Foundation; either
 
13
//  version 2.1 of the License, or (at your option) any later version.
 
14
//
 
15
//  This library is distributed in the hope that it will be useful,
 
16
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
17
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
18
//  Lesser General Public License for more details.
 
19
//
 
20
//  You should have received a copy of the GNU Lesser General Public
 
21
//  License along with this library; if not, write to the Free Software
 
22
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
23
//
 
24
// --------------------------------------------------------------------------
 
25
// $Maintainer: Timo Sachsenberg$
 
26
// $Authors: Timo Sachsenberg, Marc Sturm $
 
27
// --------------------------------------------------------------------------
 
28
 
 
29
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
 
30
 
 
31
#include <OpenMS/ANALYSIS/ID/IDMapper.h>
 
32
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>
 
33
#include <OpenMS/CHEMISTRY/AASequence.h>
 
34
#include <OpenMS/CHEMISTRY/Residue.h>
 
35
#include <OpenMS/CONCEPT/VersionInfo.h>
 
36
#include <OpenMS/FILTERING/SMOOTHING/SavitzkyGolayFilter.h>
 
37
#include <OpenMS/FILTERING/SMOOTHING/GaussFilter.h>
 
38
#include <OpenMS/FILTERING/BASELINE/MorphologicalFilter.h>
 
39
#include <OpenMS/FORMAT/IdXMLFile.h>
 
40
#include <OpenMS/FORMAT/FileHandler.h>
 
41
#include <OpenMS/FORMAT/DB/DBConnection.h>
 
42
#include <OpenMS/FORMAT/TextFile.h>
 
43
#include <OpenMS/FORMAT/DB/DBAdapter.h>
 
44
#include <OpenMS/FORMAT/FileTypes.h>
 
45
#include <OpenMS/FORMAT/FeatureXMLFile.h>
 
46
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
 
47
#include <OpenMS/KERNEL/MSExperiment.h>
 
48
#include <OpenMS/METADATA/Precursor.h>
 
49
#include <OpenMS/SYSTEM/FileWatcher.h>
 
50
#include <OpenMS/SYSTEM/File.h>
 
51
#include <OpenMS/TRANSFORMATIONS/RAW2PEAK/PeakPickerCWT.h>
 
52
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/FeatureFinder.h>
 
53
#include <OpenMS/VISUAL/DIALOGS/DataFilterDialog.h>
 
54
#include <OpenMS/VISUAL/DIALOGS/TOPPViewOpenDialog.h>
 
55
#include <OpenMS/VISUAL/DIALOGS/DBOpenDialog.h>
 
56
#include <OpenMS/VISUAL/DIALOGS/TheoreticalSpectrumGenerationDialog.h>
 
57
#include <OpenMS/VISUAL/DIALOGS/ToolsDialog.h>
 
58
#include <OpenMS/VISUAL/DIALOGS/TOPPViewPrefDialog.h>
 
59
#include <OpenMS/VISUAL/DIALOGS/SpectrumAlignmentDialog.h>
 
60
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
 
61
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DTextItem.h>
 
62
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DDistanceItem.h>
 
63
#include <OpenMS/VISUAL/SpectraViewWidget.h>
 
64
#include <OpenMS/VISUAL/Spectrum1DCanvas.h>
 
65
#include <OpenMS/VISUAL/Spectrum2DCanvas.h>
 
66
#include <OpenMS/VISUAL/Spectrum3DCanvas.h>
 
67
#include <OpenMS/VISUAL/Spectrum1DWidget.h>
 
68
#include <OpenMS/VISUAL/Spectrum2DWidget.h>
 
69
#include <OpenMS/VISUAL/Spectrum3DWidget.h>
 
70
#include <OpenMS/VISUAL/MetaDataBrowser.h>
 
71
#include <OpenMS/VISUAL/ParamEditor.h>
 
72
#include <OpenMS/VISUAL/ColorSelector.h>
 
73
#include <OpenMS/VISUAL/MultiGradientSelector.h>
 
74
#include <OpenMS/VISUAL/EnhancedTabBar.h>
 
75
#include <OpenMS/VISUAL/EnhancedWorkspace.h>
 
76
 
 
77
// OpenMS TOPPAS
 
78
#include <OpenMS/VISUAL/APPLICATIONS/TOPPASBase.h>
 
79
#include <OpenMS/VISUAL/TOPPASScene.h>
 
80
#include <OpenMS/VISUAL/TOPPASMergerVertex.h>
 
81
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
 
82
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
 
83
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
 
84
 
 
85
 
 
86
//Qt
 
87
#include <QtCore/QDate>
 
88
#include <QtCore/QDir>
 
89
#include <QtCore/QTime>
 
90
#include <QtCore/QUrl>
 
91
#include <QtGui/QCheckBox>
 
92
#include <QtGui/QCloseEvent>
 
93
#include <QtGui/QDesktopServices>
 
94
#include <QtGui/QDesktopWidget>
 
95
#include <QtGui/QDockWidget>
 
96
#include <QtGui/QFileDialog>
 
97
#include <QtGui/QHeaderView>
 
98
#include <QtGui/QInputDialog>
 
99
#include <QtGui/QListWidget>
 
100
#include <QtGui/QListWidgetItem>
 
101
#include <QtGui/QMenu>
 
102
#include <QtGui/QMenuBar>
 
103
#include <QtGui/QMessageBox>
 
104
#include <QtGui/QPainter>
 
105
#include <QtGui/QSplashScreen>
 
106
#include <QtGui/QStatusBar>
 
107
#include <QtGui/QTextEdit>
 
108
#include <QtGui/QToolBar>
 
109
#include <QtGui/QToolTip>
 
110
#include <QtGui/QToolButton>
 
111
#include <QtGui/QTreeWidget>
 
112
#include <QtGui/QTreeWidgetItem>
 
113
#include <QtGui/QWhatsThis>
 
114
 
 
115
#include <boost/math/special_functions/fpclassify.hpp>
 
116
 
 
117
#include <algorithm>
 
118
#include <utility>
 
119
 
 
120
using namespace std;
 
121
 
 
122
namespace OpenMS
 
123
{
 
124
  using namespace Internal;
 
125
        using namespace Math;
 
126
 
 
127
qreal TOPPViewBase::toppas_z_value_ = 42.0;
 
128
Int TOPPViewBase::toppas_node_offset_ = 0;
 
129
 
 
130
TOPPViewBase::TOPPViewBase(QWidget* parent):
 
131
        QMainWindow(parent),
 
132
        DefaultParamHandler("TOPPViewBase"),
 
133
        watcher_(0),
 
134
        watcher_msgbox_(false),
 
135
        toppas_clipboard_scene_(0)
 
136
        {
 
137
          setWindowTitle("TOPPView");
 
138
          setWindowIcon(QIcon(":/TOPPView.png"));
 
139
 
 
140
          //prevents errors caused by too small width,height values
 
141
          setMinimumSize(400,400);
 
142
 
 
143
          //enable drag-and-drop
 
144
          setAcceptDrops(true);
 
145
 
 
146
          // get geometry of first screen
 
147
          QRect screen_geometry = QApplication::desktop()->screenGeometry();
 
148
          // center main window
 
149
          setGeometry(
 
150
            (int)(0.1 * screen_geometry.width()),
 
151
            (int)(0.1 * screen_geometry.height()),
 
152
            (int)(0.8 * screen_geometry.width()),
 
153
            (int)(0.8 * screen_geometry.height())
 
154
            );
 
155
 
 
156
          //set & create temporary path -- make sure its a new subdirectory, as TOPPASScene will delete it when its done
 
157
          toppas_tmp_path_ =  (File::getTempDirectory() + String(QDir::separator()) + File::getUniqueName()).toQString();
 
158
          QDir qd;
 
159
          qd.mkpath(toppas_tmp_path_);
 
160
 
 
161
          // create dummy widget (to be able to have a layout), Tab bar and workspace
 
162
          QWidget* dummy = new QWidget(this);
 
163
          setCentralWidget(dummy);
 
164
          QVBoxLayout* box_layout = new QVBoxLayout(dummy);
 
165
 
 
166
          // create empty tab bar and workspace which will hold the main visualization widgets (e.g. spectra widgets...)
 
167
          tab_bar_ = new EnhancedTabBar(dummy);
 
168
          tab_bar_->setWhatsThis("Tab bar<BR><BR>Close tabs through the context menu or by double-clicking them.<BR>The tab bar accepts drag-and-drop from the layer bar.");
 
169
          tab_bar_->addTab("dummy",4710);
 
170
          tab_bar_->setMinimumSize(tab_bar_->sizeHint());
 
171
          tab_bar_->removeId(4710);
 
172
 
 
173
          connect(tab_bar_,SIGNAL(currentIdChanged(int)),this,SLOT(enhancedWorkspaceWindowChanged(int)));
 
174
          connect(tab_bar_,SIGNAL(aboutToCloseId(int)),this,SLOT(closeByTab(int)));
 
175
 
 
176
          //connect signals ans slots for drag-and-drop
 
177
          connect(tab_bar_,SIGNAL(dropOnWidget(const QMimeData*,QWidget*)),this,SLOT(copyLayer(const QMimeData*,QWidget*)));
 
178
          connect(tab_bar_,SIGNAL(dropOnTab(const QMimeData*,QWidget*,int)),this,SLOT(copyLayer(const QMimeData*,QWidget*,int)));
 
179
          box_layout->addWidget(tab_bar_);
 
180
 
 
181
          ws_= new EnhancedWorkspace(dummy);
 
182
          connect(ws_,SIGNAL(windowActivated(QWidget*)),this,SLOT(updateToolBar()));
 
183
          connect(ws_,SIGNAL(windowActivated(QWidget*)),this,SLOT(updateTabBar(QWidget*)));
 
184
          connect(ws_,SIGNAL(windowActivated(QWidget*)),this,SLOT(updateLayerBar()));
 
185
          connect(ws_,SIGNAL(windowActivated(QWidget*)),this,SLOT(updateViewBar()));
 
186
          connect(ws_,SIGNAL(windowActivated(QWidget*)),this,SLOT(updateFilterBar()));
 
187
          connect(ws_,SIGNAL(windowActivated(QWidget*)),this,SLOT(updateMenu()));
 
188
          connect(ws_,SIGNAL(windowActivated(QWidget*)),this,SLOT(updateCurrentPath()));
 
189
          connect(ws_,SIGNAL(dropReceived(const QMimeData*,QWidget*,int)),this,SLOT(copyLayer(const QMimeData*,QWidget*,int)));
 
190
 
 
191
          box_layout->addWidget(ws_);
 
192
 
 
193
          //################## MENUS #################
 
194
          // File menu          
 
195
          QMenu* file = new QMenu("&File",this);
 
196
          menuBar()->addMenu(file);
 
197
          file->addAction("&Open file",this,SLOT(openFileDialog()), Qt::CTRL+Qt::Key_O);
 
198
          file->addAction("Open from &database",this,SLOT(openDatabaseDialog()), Qt::CTRL+Qt::Key_D);
 
199
          file->addAction("Open &example file",this,SLOT(openExampleDialog()));
 
200
          file->addAction("&Close",this,SLOT(closeFile()), Qt::CTRL+Qt::Key_W);
 
201
          file->addSeparator();
 
202
 
 
203
          // File menu: TOPPAS section
 
204
          file->addAction("&New TOPPAS pipeline",this,SLOT(newPipeline()), Qt::CTRL+Qt::Key_N);
 
205
          file->addAction("&Include TOPPAS pipeline",this,SLOT(includePipeline()), Qt::CTRL+Qt::Key_I);
 
206
          file->addAction("&Save TOPPAS pipeline",this,SLOT(savePipeline()), Qt::CTRL+Qt::Key_S);
 
207
          file->addAction("Save TOPPAS pipeline &As",this,SLOT(saveCurrentPipelineAs()), Qt::CTRL+Qt::SHIFT+Qt::Key_S);
 
208
          file->addAction("&Load TOPPAS resource file",this,SLOT(loadPipelineResourceFile()));
 
209
          file->addAction("Save TOPPAS &resource file",this,SLOT(savePipelineResourceFile()));
 
210
          file->addAction("Refresh TOPPAS &parameters",this,SLOT(refreshPipelineParameters()), Qt::CTRL+Qt::SHIFT+Qt::Key_P);
 
211
          file->addSeparator();
 
212
 
 
213
          //Meta data
 
214
          file->addAction("&Show meta data (file)",this,SLOT(metadataFileDialog()));
 
215
          file->addAction("&Show meta data (database)",this,SLOT(metadataDatabaseDialog()));
 
216
          file->addSeparator();
 
217
 
 
218
          //Recent files
 
219
          QMenu* recent_menu = new QMenu("&Recent files", this);
 
220
          recent_actions_.resize(20);
 
221
          for (Size i = 0; i<20; ++i)
 
222
          {
 
223
            recent_actions_[i] = recent_menu->addAction("",this,SLOT(openRecentFile()));
 
224
            recent_actions_[i]->setVisible(false);
 
225
          }
 
226
          file->addMenu(recent_menu);
 
227
 
 
228
          file->addSeparator();
 
229
          file->addAction("&Preferences",this, SLOT(preferencesDialog()));
 
230
          file->addAction("&Quit",qApp,SLOT(quit()));
 
231
 
 
232
          //Tools menu
 
233
          QMenu* tools = new QMenu("&Tools",this);
 
234
          menuBar()->addMenu(tools);
 
235
          tools->addAction("&Go to",this,SLOT(showGoToDialog()), Qt::CTRL+Qt::Key_G);
 
236
          tools->addAction("&Edit meta data",this,SLOT(editMetadata()), Qt::CTRL+Qt::Key_M);
 
237
          tools->addAction("&Statistics",this,SLOT(layerStatistics()));
 
238
          tools->addSeparator();
 
239
 
 
240
          tools->addAction("Apply TOPP tool (whole layer)", this, SLOT(showTOPPDialog()), Qt::CTRL+Qt::Key_T)->setData(false);
 
241
          tools->addAction("Apply TOPP tool (visible layer data)", this, SLOT(showTOPPDialog()), Qt::CTRL+Qt::SHIFT+Qt::Key_T)->setData(true);
 
242
          tools->addAction("Rerun TOPP tool", this, SLOT(rerunTOPPTool()),Qt::Key_F4);
 
243
          tools->addSeparator();
 
244
          tools->addAction("&Annotate with identification", this, SLOT(annotateWithID()), Qt::CTRL+Qt::Key_I);
 
245
          tools->addAction("Align spectra", this, SLOT(showSpectrumAlignmentDialog()));
 
246
          tools->addAction("Generate theoretical spectrum", this, SLOT(showSpectrumGenerationDialog()));
 
247
 
 
248
          // TOPPAS menu
 
249
          // pipeline menu (TOPPAS pipeline)
 
250
          QMenu* toppas_pipeline = new QMenu("TOPPAS &Pipeline", this);
 
251
          toppas_pipeline->addAction("&Run (F5)",this,SLOT(runPipeline()));
 
252
          toppas_pipeline->addAction("&Abort",this,SLOT(abortPipeline()));
 
253
          menuBar()->addMenu(toppas_pipeline);
 
254
 
 
255
          //Layer menu
 
256
          QMenu* layer = new QMenu("&Layer",this);
 
257
          menuBar()->addMenu(layer);
 
258
          layer->addAction("Save all data", this, SLOT(saveLayerAll()), Qt::CTRL+Qt::Key_S);
 
259
          layer->addAction("Save visible data", this, SLOT(saveLayerVisible()), Qt::CTRL+Qt::SHIFT+Qt::Key_S);
 
260
          layer->addSeparator();
 
261
          layer->addAction("Show/hide grid lines", this, SLOT(toggleGridLines()), Qt::CTRL+Qt::Key_R);
 
262
          layer->addAction("Show/hide axis legends", this, SLOT(toggleAxisLegends()), Qt::CTRL+Qt::Key_L);
 
263
          layer->addSeparator();
 
264
          layer->addAction("Preferences", this, SLOT(showPreferences()));
 
265
 
 
266
          //Windows menu
 
267
          QMenu* windows = new QMenu("&Windows", this);
 
268
          menuBar()->addMenu(windows);
 
269
          windows->addAction("&Cascade",this->ws_,SLOT(cascade()));
 
270
          windows->addAction("&Tile automatic",this->ws_,SLOT(tile()));
 
271
          windows->addAction(QIcon(":/tile_horizontal.png"),"Tile &vertical",this,SLOT(tileHorizontal()));
 
272
          windows->addAction(QIcon(":/tile_vertical.png"),"Tile &horizontal",this,SLOT(tileVertical()));
 
273
          windows->addSeparator();
 
274
 
 
275
          //Help menu
 
276
          QMenu* help = new QMenu("&Help", this);
 
277
          menuBar()->addMenu(help);
 
278
          help->addAction(QWhatsThis::createAction(help));
 
279
          help->addSeparator();
 
280
          QAction* action = help->addAction("OpenMS website",this,SLOT(showURL()));
 
281
          action->setData("http://www.OpenMS.de");
 
282
          action = help->addAction("Tutorials and documentation",this,SLOT(showURL()), Qt::Key_F1);
 
283
          action->setData(String(File::getOpenMSDataPath() + "/../../doc/html/index.html").toQString());
 
284
 
 
285
          help->addSeparator();
 
286
          help->addAction("&About",this,SLOT(showAboutDialog()));
 
287
 
 
288
          //create status bar
 
289
          message_label_ = new QLabel(statusBar());
 
290
          statusBar()->addWidget(message_label_,1);
 
291
 
 
292
          rt_label_ = new QLabel("RT: 12345678", statusBar());
 
293
          rt_label_->setMinimumSize(rt_label_->sizeHint());
 
294
          rt_label_->setText("");
 
295
          statusBar()->addPermanentWidget(rt_label_,0);
 
296
          mz_label_ = new QLabel("m/z: 123456780912", statusBar());
 
297
          mz_label_->setMinimumSize(mz_label_->sizeHint());
 
298
          mz_label_->setText("");
 
299
          statusBar()->addPermanentWidget(mz_label_,0);
 
300
 
 
301
          //################## TOOLBARS #################
 
302
          //create toolbars and connect signals
 
303
          QToolButton* b;
 
304
 
 
305
          //--Basic tool bar for all views--
 
306
          tool_bar_ = addToolBar("Basic tool bar");
 
307
 
 
308
          //intensity modes
 
309
          intensity_button_group_ = new QButtonGroup(tool_bar_);
 
310
          intensity_button_group_->setExclusive(true);
 
311
 
 
312
          b = new QToolButton(tool_bar_);
 
313
          b->setIcon(QIcon(":/lin.png"));
 
314
          b->setToolTip("Intensity: Normal");
 
315
          b->setShortcut(Qt::Key_N);
 
316
          b->setCheckable(true);
 
317
          b->setWhatsThis("Intensity: Normal<BR><BR>Intensity is displayed unmodified.<BR>(Hotkey: N)");
 
318
          intensity_button_group_->addButton(b,SpectrumCanvas::IM_NONE);
 
319
          tool_bar_->addWidget(b);
 
320
 
 
321
          b = new QToolButton(tool_bar_);
 
322
          b->setIcon(QIcon(":/percentage.png"));
 
323
          b->setToolTip("Intensity: Percentage");
 
324
          b->setShortcut(Qt::Key_P);
 
325
          b->setCheckable(true);
 
326
          b->setWhatsThis("Intensity: Percentage<BR><BR>Intensity is displayed as a percentage of the layer"
 
327
                          " maximum intensity. If only one layer is displayed this mode behaves like the"
 
328
                          " normal mode. If more than one layer is displayed intensities are aligned."
 
329
                          "<BR>(Hotkey: P)");
 
330
          intensity_button_group_->addButton(b,SpectrumCanvas::IM_PERCENTAGE);
 
331
          tool_bar_->addWidget(b);
 
332
 
 
333
          b = new QToolButton(tool_bar_);
 
334
          b->setIcon(QIcon(":/snap.png"));
 
335
          b->setToolTip("Intensity: Snap to maximum displayed intensity");
 
336
          b->setShortcut(Qt::Key_S);
 
337
          b->setCheckable(true);
 
338
          b->setWhatsThis("Intensity: Snap to maximum displayed intensity<BR><BR> In this mode the"
 
339
                          " color gradient is adapted to the maximum currently displayed intensity."
 
340
                          "<BR>(Hotkey: S)");
 
341
          intensity_button_group_->addButton(b,SpectrumCanvas::IM_SNAP);
 
342
          tool_bar_->addWidget(b);
 
343
 
 
344
          b = new QToolButton(tool_bar_);
 
345
          b->setIcon(QIcon(":/log.png"));
 
346
          b->setToolTip("Intensity: Use log scaling for colors");
 
347
          b->setCheckable(true);
 
348
          b->setWhatsThis("Intensity: Logarithmic scaling of intensities for color calculation");
 
349
          intensity_button_group_->addButton(b,SpectrumCanvas::IM_LOG);
 
350
          tool_bar_->addWidget(b);
 
351
 
 
352
          connect(intensity_button_group_,SIGNAL(buttonClicked(int)),this,SLOT(setIntensityMode(int)));
 
353
          tool_bar_->addSeparator();
 
354
 
 
355
          //common buttons
 
356
          QAction* reset_zoom_button = tool_bar_->addAction(QIcon(":/reset_zoom.png"), "Reset Zoom", this, SLOT(resetZoom()));
 
357
          reset_zoom_button->setWhatsThis("Reset zoom: Zooms out as far as possible and resets the zoom history.<BR>(Hotkey: Backspace)");
 
358
 
 
359
          tool_bar_->show();
 
360
 
 
361
          //--1D toolbar--
 
362
          tool_bar_1d_ = addToolBar("1D tool bar");
 
363
 
 
364
          //draw modes 1D
 
365
          draw_group_1d_ = new QButtonGroup(tool_bar_1d_);
 
366
          draw_group_1d_->setExclusive(true);
 
367
 
 
368
          b = new QToolButton(tool_bar_1d_);
 
369
          b->setIcon(QIcon(":/peaks.png"));
 
370
          b->setToolTip("Peak mode");
 
371
          b->setShortcut(Qt::Key_I);
 
372
          b->setCheckable(true);
 
373
          b->setWhatsThis("1D Draw mode: Peaks<BR><BR>Peaks are diplayed as sticks.");
 
374
          draw_group_1d_->addButton(b,Spectrum1DCanvas::DM_PEAKS);
 
375
          tool_bar_1d_->addWidget(b);
 
376
 
 
377
          b = new QToolButton(tool_bar_1d_);
 
378
          b->setIcon(QIcon(":/lines.png"));
 
379
          b->setToolTip("Raw data mode");
 
380
          b->setShortcut(Qt::Key_R);
 
381
          b->setCheckable(true);
 
382
          b->setWhatsThis("1D Draw mode: Raw data<BR><BR>Peaks are diplayed as a continous line.");
 
383
          draw_group_1d_->addButton(b,Spectrum1DCanvas::DM_CONNECTEDLINES);
 
384
          tool_bar_1d_->addWidget(b);
 
385
 
 
386
          connect(draw_group_1d_,SIGNAL(buttonClicked(int)),this,SLOT(setDrawMode1D(int)));
 
387
          tool_bar_->addSeparator();
 
388
 
 
389
          //--2D peak toolbar--
 
390
          tool_bar_2d_peak_ = addToolBar("2D peak tool bar");
 
391
 
 
392
          dm_precursors_2d_ = tool_bar_2d_peak_->addAction(QIcon(":/precursors.png"),"Show fragment scan precursors");
 
393
          dm_precursors_2d_->setCheckable(true);
 
394
          dm_precursors_2d_->setWhatsThis("2D peak draw mode: Precursors<BR><BR>fragment scan precursor peaks are marked.<BR>(Hotkey: 1)");
 
395
          dm_precursors_2d_->setShortcut(Qt::Key_1);
 
396
 
 
397
          connect(dm_precursors_2d_, SIGNAL(toggled(bool)), this, SLOT(changeLayerFlag(bool)));
 
398
 
 
399
          projections_2d_ = tool_bar_2d_peak_->addAction(QIcon(":/projections.png"), "Show Projections" ,this, SLOT(toggleProjections()));
 
400
          projections_2d_->setWhatsThis("Projections: Shows projections of peak data along RT and MZ axis.<BR>(Hotkey: 2)");
 
401
          projections_2d_->setShortcut(Qt::Key_2);
 
402
 
 
403
          //--2D feature toolbar--
 
404
          tool_bar_2d_feat_ = addToolBar("2D feature tool bar");
 
405
 
 
406
          dm_hull_2d_ = tool_bar_2d_feat_->addAction(QIcon(":/convexhull.png"),"Show feature convex hull");
 
407
          dm_hull_2d_->setCheckable(true);
 
408
          dm_hull_2d_->setWhatsThis("2D feature draw mode: Convex hull<BR><BR>The convex hull of the feature is displayed.<BR>(Hotkey: 5)");
 
409
          dm_hull_2d_->setShortcut(Qt::Key_5);
 
410
          connect(dm_hull_2d_, SIGNAL(toggled(bool)), this, SLOT(changeLayerFlag(bool)));
 
411
 
 
412
          dm_hulls_2d_ = tool_bar_2d_feat_->addAction(QIcon(":/convexhulls.png"),"Show feature convex hulls");
 
413
          dm_hulls_2d_->setCheckable(true);
 
414
          dm_hulls_2d_->setWhatsThis("2D feature draw mode: Convex hulls<BR><BR>The convex hulls of the feature are displayed: One for each mass trace.<BR>(Hotkey: 6)");
 
415
          dm_hulls_2d_->setShortcut(Qt::Key_6);
 
416
          connect(dm_hulls_2d_, SIGNAL(toggled(bool)), this, SLOT(changeLayerFlag(bool)));
 
417
 
 
418
          // feature labels:
 
419
          dm_label_2d_ = new QToolButton(tool_bar_2d_feat_);
 
420
          dm_label_2d_->setPopupMode(QToolButton::MenuButtonPopup);
 
421
          QAction* action2 = new QAction(QIcon(":/labels.png"), "Show feature label", dm_label_2d_);
 
422
          action2->setCheckable(true);
 
423
          action2->setWhatsThis("2D feature draw mode: Labels<BR><BR>Display different kinds of annotation next to features.<BR>(Hotkey: 7)");
 
424
          action2->setShortcut(Qt::Key_7);
 
425
          dm_label_2d_->setDefaultAction(action2);
 
426
          tool_bar_2d_feat_->addWidget(dm_label_2d_);
 
427
          connect(dm_label_2d_, SIGNAL(triggered(QAction*)), this, SLOT(changeLabel(QAction*)));
 
428
          //button menu
 
429
          group_label_2d_ = new QActionGroup(dm_label_2d_);
 
430
          QMenu* menu = new QMenu(dm_label_2d_);
 
431
          for (Size i = 0; i < LayerData::SIZE_OF_LABEL_TYPE; ++i)
 
432
          {
 
433
            QAction* temp = group_label_2d_->addAction(
 
434
                QString(LayerData::NamesOfLabelType[i].c_str()));
 
435
            temp->setCheckable(true);
 
436
            if (i == 0) temp->setChecked(true);
 
437
            menu->addAction(temp);
 
438
          }
 
439
          dm_label_2d_->setMenu(menu);
 
440
 
 
441
          // unassigned peptide identifications:
 
442
          dm_unassigned_2d_ = new QToolButton(tool_bar_2d_feat_);
 
443
          dm_unassigned_2d_->setPopupMode(QToolButton::MenuButtonPopup);
 
444
          QAction* action_unassigned = new QAction(QIcon(":/unassigned.png"), "Show unassigned peptide identifications", dm_unassigned_2d_);
 
445
          action_unassigned->setCheckable(true);
 
446
          action_unassigned->setWhatsThis("2D feature draw mode: Unassigned peptide identifications<BR><BR>Show unassigned peptide identifications by precursor m/z or by peptide mass.<BR>(Hotkey: 8)");
 
447
          action_unassigned->setShortcut(Qt::Key_8);
 
448
          dm_unassigned_2d_->setDefaultAction(action_unassigned);
 
449
          tool_bar_2d_feat_->addWidget(dm_unassigned_2d_);
 
450
          connect(dm_unassigned_2d_, SIGNAL(triggered(QAction*)), this, SLOT(changeUnassigned(QAction*)));
 
451
          //button menu
 
452
          group_unassigned_2d_ = new QActionGroup(dm_unassigned_2d_);
 
453
          menu = new QMenu(dm_unassigned_2d_);
 
454
          StringList options = StringList::create(
 
455
              "Don't show,Show by precursor m/z,Show by peptide mass");
 
456
          for (StringList::iterator opt_it = options.begin(); opt_it != options.end();
 
457
          ++opt_it)
 
458
          {
 
459
            QAction* temp = group_unassigned_2d_->addAction(opt_it->toQString());
 
460
            temp->setCheckable(true);
 
461
            if (opt_it == options.begin()) temp->setChecked(true);
 
462
            menu->addAction(temp);
 
463
          }
 
464
          dm_unassigned_2d_->setMenu(menu);
 
465
 
 
466
          //--2D consensus toolbar--
 
467
          tool_bar_2d_cons_ = addToolBar("2D peak tool bar");
 
468
 
 
469
          dm_elements_2d_ = tool_bar_2d_cons_->addAction(QIcon(":/elements.png"),"Show consensus feature element positions");
 
470
          dm_elements_2d_->setCheckable(true);
 
471
          dm_elements_2d_->setWhatsThis("2D consensus feature draw mode: Elements<BR><BR>The individual elements that make up the  consensus feature are drawn.<BR>(Hotkey: 9)");
 
472
          dm_elements_2d_->setShortcut(Qt::Key_9);
 
473
          connect(dm_elements_2d_, SIGNAL(toggled(bool)), this, SLOT(changeLayerFlag(bool)));
 
474
 
 
475
          //--2D identifications toolbar--
 
476
          tool_bar_2d_ident_ = addToolBar("2D identifications tool bar");
 
477
 
 
478
          dm_ident_2d_ = tool_bar_2d_ident_->addAction(QIcon(":/peptidemz.png"), "Use theoretical peptide mass for m/z positions (default: precursor mass)");
 
479
          dm_ident_2d_->setCheckable(true);
 
480
          dm_ident_2d_->setWhatsThis("2D peptide identification draw mode: m/z source<BR><BR>Toggle between precursor mass (default) and theoretical peptide mass as source for the m/z positions of peptide identifications.<BR>(Hotkey: 5)");
 
481
          dm_ident_2d_->setShortcut(Qt::Key_5);
 
482
          connect(dm_ident_2d_, SIGNAL(toggled(bool)), this, SLOT(changeLayerFlag(bool)));
 
483
 
 
484
          //################## Dock widgets #################
 
485
          // layer dock widget
 
486
          layer_dock_widget_ = new QDockWidget("Layers", this);
 
487
          addDockWidget(Qt::RightDockWidgetArea, layer_dock_widget_);
 
488
          layer_manager_ = new QListWidget(layer_dock_widget_);
 
489
          layer_manager_->setWhatsThis("Layer bar<BR><BR>Here the available layers are shown. Left-click on a layer to select it.<BR>Layers can be shown and hidden using the checkboxes in front of the name.<BR> Renaming and removing a layer is possible through the context menu.<BR>Dragging a layer to the tab bar copies the layer.<BR>Double-clicking a layer open its preferences.<BR>You can use the 'PageUp' and 'PageDown' buttons to change the selected layer.");
 
490
 
 
491
          layer_dock_widget_->setWidget(layer_manager_);
 
492
          layer_manager_->setContextMenuPolicy(Qt::CustomContextMenu);
 
493
          layer_manager_->setDragEnabled(true);
 
494
          connect(layer_manager_,SIGNAL(currentRowChanged(int)),this,SLOT(layerSelectionChange(int)));
 
495
          connect(layer_manager_,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(layerContextMenu(const QPoint&)));
 
496
          connect(layer_manager_,SIGNAL(itemChanged(QListWidgetItem*)),this,SLOT(layerVisibilityChange(QListWidgetItem*)));
 
497
          connect(layer_manager_,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(layerEdit(QListWidgetItem*)));
 
498
 
 
499
          windows->addAction(layer_dock_widget_->toggleViewAction());
 
500
 
 
501
          // Views dock widget
 
502
          views_dockwidget_ = new QDockWidget("Views", this);
 
503
          addDockWidget(Qt::RightDockWidgetArea, views_dockwidget_);
 
504
          views_tabwidget_ = new QTabWidget(views_dockwidget_);
 
505
          views_dockwidget_->setWidget(views_tabwidget_);
 
506
 
 
507
          spectra_view_widget_ = new SpectraViewWidget();
 
508
          connect(spectra_view_widget_, SIGNAL(showSpectrumMetaData(int)), this, SLOT(showSpectrumMetaData(int)));
 
509
          connect(spectra_view_widget_, SIGNAL(showSpectrumAs1D(int)), this, SLOT(showSpectrumAs1D(int)));
 
510
          connect(spectra_view_widget_, SIGNAL(spectrumSelected(int)), this, SLOT(activate1DSpectrum(int)));
 
511
          connect(spectra_view_widget_, SIGNAL(spectrumDoubleClicked(int)), this, SLOT(showSpectrumAs1D(int)));
 
512
          spectraview_behavior_ = new TOPPViewSpectraViewBehavior(this);
 
513
          view_behavior_ = spectraview_behavior_;
 
514
 
 
515
          spectra_identification_view_widget_ = new SpectraIdentificationViewWidget(Param());
 
516
          connect(spectra_identification_view_widget_, SIGNAL(spectrumDeselected(int)), this, SLOT(deactivate1DSpectrum(int)));
 
517
          connect(spectra_identification_view_widget_, SIGNAL(showSpectrumAs1D(int)), this, SLOT(showSpectrumAs1D(int)));
 
518
          connect(spectra_identification_view_widget_, SIGNAL(spectrumSelected(int)), this, SLOT(activate1DSpectrum(int)));
 
519
          identificationview_behavior_ = new TOPPViewIdentificationViewBehavior(this);
 
520
          connect(spectra_identification_view_widget_, SIGNAL(requestVisibleArea1D(DoubleReal, DoubleReal)), identificationview_behavior_, SLOT(setVisibleArea1D(DoubleReal, DoubleReal)));
 
521
 
 
522
          // topp tool dock widget          
 
523
          TOPPASTreeView* tools_tree_view = TOPPASBase::createTOPPToolsTreeWidget();
 
524
          connect (tools_tree_view, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(insertNewVertexInCenter_(QTreeWidgetItem*)));
 
525
 
 
526
          views_tabwidget_->addTab(spectra_view_widget_, "Scan view");
 
527
          views_tabwidget_->addTab(spectra_identification_view_widget_, "Identification view");
 
528
          views_tabwidget_->setTabEnabled(1, false);
 
529
          views_tabwidget_->addTab(tools_tree_view, "TOPPAS view");
 
530
          views_tabwidget_->setTabEnabled(2, false);
 
531
 
 
532
          // switch between different view tabs
 
533
          connect(views_tabwidget_, SIGNAL(currentChanged(int)), this, SLOT(viewChanged(int)));
 
534
 
 
535
          // add hide/show option to dock widget
 
536
          windows->addAction(views_dockwidget_->toggleViewAction());
 
537
 
 
538
          // filter dock widget
 
539
          filter_dock_widget_ = new QDockWidget("Data filters", this);
 
540
          addDockWidget(Qt::RightDockWidgetArea, filter_dock_widget_);
 
541
          QWidget* tmp_widget = new QWidget(); //dummy widget as QDockWidget takes only one widget
 
542
          filter_dock_widget_->setWidget(tmp_widget);
 
543
 
 
544
          QVBoxLayout* vbl = new QVBoxLayout(tmp_widget);
 
545
 
 
546
          filters_ = new QListWidget(tmp_widget);
 
547
          filters_->setSelectionMode(QAbstractItemView::NoSelection);
 
548
          filters_->setWhatsThis("Data filter bar<BR><BR>Here filtering options for the current layer can be set.<BR>Through the context menu you can add, remove and edit filters.<BR>For convenience, editing filters is also possible by double-clicking them.");
 
549
          filters_->setContextMenuPolicy(Qt::CustomContextMenu);
 
550
          connect(filters_,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(filterContextMenu(const QPoint&)));
 
551
          connect(filters_,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(filterEdit(QListWidgetItem*)));
 
552
          vbl->addWidget(filters_);
 
553
 
 
554
          filters_check_box_ = new QCheckBox("Enable/disable all filters", tmp_widget);
 
555
          connect(filters_check_box_,SIGNAL(toggled(bool)),this,SLOT(layerFilterVisibilityChange(bool)));
 
556
          vbl->addWidget(filters_check_box_);
 
557
 
 
558
          windows->addAction(filter_dock_widget_->toggleViewAction());
 
559
 
 
560
          //log window
 
561
          QDockWidget* log_bar = new QDockWidget("Log", this);
 
562
          addDockWidget(Qt::BottomDockWidgetArea, log_bar);
 
563
          log_ = new QTextEdit(log_bar);
 
564
          log_->setReadOnly(true);
 
565
          log_->setContextMenuPolicy(Qt::CustomContextMenu);
 
566
          connect(log_,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(logContextMenu(const QPoint&)));
 
567
          log_bar->setWidget(log_);
 
568
          log_bar->hide();
 
569
          windows->addAction(log_bar->toggleViewAction());
 
570
 
 
571
          //################## DEFAULTS #################
 
572
          initializeDefaultParameters_();
 
573
 
 
574
          // store defaults in param_
 
575
          defaultsToParam_();
 
576
 
 
577
          //load param file
 
578
          loadPreferences();
 
579
 
 
580
          //set current path
 
581
          current_path_ = param_.getValue("preferences:default_path");
 
582
 
 
583
          //update the menu
 
584
          updateMenu();
 
585
 
 
586
          topp_.process = 0;
 
587
 
 
588
          //######################### File System Watcher ###########################################
 
589
          watcher_ = new FileWatcher(this);
 
590
          connect(watcher_,SIGNAL(fileChanged(const String&)),this, SLOT(fileChanged_(const String&)));
 
591
        }
 
592
 
 
593
  void TOPPViewBase::initializeDefaultParameters_()
 
594
  {
 
595
    //general
 
596
    defaults_.setValue("preferences:default_map_view", "2d", "Default visualization mode for maps.");
 
597
    defaults_.setValidStrings("preferences:default_map_view",StringList::create("2d,3d"));
 
598
    defaults_.setValue("preferences:default_path", ".", "Default path for loading and storing files.");
 
599
    defaults_.setValue("preferences:default_path_current", "true", "If the current path is preferred over the default path.");
 
600
    defaults_.setValidStrings("preferences:default_path_current",StringList::create("true,false"));
 
601
    defaults_.setValue("preferences:tmp_file_path", QDir::tempPath(), "Path where temporary files can be created.");
 
602
    defaults_.setValue("preferences:number_of_recent_files", 15, "Number of recent files in the main menu.");
 
603
    defaults_.setMinInt("preferences:number_of_recent_files",5);
 
604
    defaults_.setMaxInt("preferences:number_of_recent_files",20);
 
605
    defaults_.setValue("preferences:legend", "show", "Legend visibility");
 
606
    defaults_.setValidStrings("preferences:legend",StringList::create("show,hide"));
 
607
    defaults_.setValue("preferences:intensity_cutoff", "off","Low intensity cutoff for maps.");
 
608
    defaults_.setValidStrings("preferences:intensity_cutoff",StringList::create("on,off"));
 
609
    defaults_.setValue("preferences:on_file_change","ask","What action to take, when a data file changes. Do nothing, update automatically or ask the user.");
 
610
    defaults_.setValidStrings("preferences:on_file_change",StringList::create("none,ask,update automatically"));
 
611
    defaults_.setValue("preferences:topp_cleanup", "true", "If the temporary files for calling of TOPP tools should be removed after the call.");
 
612
    defaults_.setValidStrings("preferences:topp_cleanup",StringList::create("true,false"));
 
613
    //db
 
614
    defaults_.setValue("preferences:db:host", "localhost", "Database server host name.");
 
615
    defaults_.setValue("preferences:db:login", "NoName", "Database login.");
 
616
    defaults_.setValue("preferences:db:name", "OpenMS", "Database name.");
 
617
    defaults_.setValue("preferences:db:port", 3306, "Database server port.");
 
618
    defaults_.setSectionDescription("preferences:db","Database settings.");
 
619
    // 1d view
 
620
    Spectrum1DCanvas* def1 = new Spectrum1DCanvas(Param(),0);
 
621
    defaults_.insert("preferences:1d:",def1->getDefaults());
 
622
    delete def1;
 
623
    defaults_.setSectionDescription("preferences:1d","Settings for single spectrum view.");
 
624
    // 2d view
 
625
    Spectrum2DCanvas* def2 = new Spectrum2DCanvas(Param(),0);
 
626
    defaults_.insert("preferences:2d:",def2->getDefaults());
 
627
    defaults_.setSectionDescription("preferences:2d","Settings for 2D map view.");
 
628
    delete def2;
 
629
    // 3d view
 
630
    Spectrum3DCanvas* def3 = new Spectrum3DCanvas(Param(),0);
 
631
    defaults_.insert("preferences:3d:",def3->getDefaults());
 
632
    delete def3;
 
633
    defaults_.setSectionDescription("preferences:3d","Settings for 3D map view.");
 
634
    // identification view
 
635
    SpectraIdentificationViewWidget* def4 = new SpectraIdentificationViewWidget(Param(),0);
 
636
    defaults_.insert("preferences:idview:",def4->getDefaults());
 
637
    delete def4;
 
638
    defaults_.setSectionDescription("preferences:idview","Settings for identification view.");
 
639
    defaults_.setValue("preferences:version","none","OpenMS version, used to check if the TOPPView.ini is up-to-date");
 
640
    subsections_.push_back("preferences:RecentFiles");
 
641
  }
 
642
 
 
643
  void TOPPViewBase::closeEvent(QCloseEvent* event)
 
644
  {
 
645
    ws_->closeAllWindows();
 
646
    event->accept();
 
647
  }
 
648
 
 
649
  void TOPPViewBase::showURL()
 
650
  {
 
651
      QAction* action = qobject_cast<QAction*>(sender());
 
652
      if (!QDesktopServices::openUrl(QUrl(action->data().toString())))
 
653
      {
 
654
          QMessageBox::warning(this, tr("Error"),
 
655
                               tr("Unable to open\n") +
 
656
                               action->data().toString() +
 
657
                               tr("\n\nPossible reason: security settings or misconfigured Operating System"));
 
658
      }
 
659
  }
 
660
 
 
661
  void TOPPViewBase::addDataDB(UInt db_id, bool show_options, String caption, UInt window_id)
 
662
  {
 
663
    //set wait cursor
 
664
    setCursor(Qt::WaitCursor);
 
665
 
 
666
    //Open DB connection
 
667
    DBConnection con;
 
668
    connectToDB_(con);
 
669
    if (!con.isConnected())
 
670
    {
 
671
      setCursor(Qt::ArrowCursor);
 
672
      return;
 
673
    }
 
674
 
 
675
    //load the data
 
676
    DBAdapter db(con);
 
677
 
 
678
    // create managed pointer to experiment data
 
679
    ExperimentType* exp = new ExperimentType();
 
680
    ExperimentSharedPtrType exp_sptr(exp);
 
681
 
 
682
    FeatureMapType* dummy_map = new FeatureMapType();
 
683
    FeatureMapSharedPtrType dummy_map_sptr(dummy_map);
 
684
 
 
685
    ConsensusMapType* dummy_map2 = new ConsensusMapType();
 
686
    ConsensusMapSharedPtrType dummy_map2_sptr(dummy_map2);
 
687
 
 
688
    vector<PeptideIdentification> dummy_peptides;
 
689
    try
 
690
    {
 
691
      db.loadExperiment(db_id, *exp);
 
692
    }
 
693
    catch (Exception::BaseException& e)
 
694
    {
 
695
      QMessageBox::critical(this,"Error",(String("Error while reading data: ")+e.what()).c_str());
 
696
      setCursor(Qt::ArrowCursor);
 
697
      return;
 
698
    }
 
699
    exp_sptr->sortSpectra(true);
 
700
    exp_sptr->updateRanges(1);
 
701
 
 
702
    //determine if the data is 1D or 2D
 
703
    QSqlQuery result = con.executeQuery(String("SELECT count(id) from DATA_Spectrum where fid_MSExperiment='")+db_id+"' and MSLevel='1'");
 
704
    LayerData::DataType data_type = ((result.value(0).toInt()>1) ?
 
705
                                     LayerData::DT_PEAK :
 
706
                                     LayerData::DT_CHROMATOGRAM);
 
707
 
 
708
    //add data
 
709
    if (caption=="") caption = String("DB entry ")+db_id;
 
710
    addData(dummy_map_sptr, dummy_map2_sptr, dummy_peptides, exp_sptr, data_type, false, show_options, true, "", caption, window_id);
 
711
 
 
712
    //Reset cursor
 
713
    setCursor(Qt::ArrowCursor);
 
714
  }
 
715
 
 
716
  // static
 
717
  bool TOPPViewBase::containsMS1Scans(const ExperimentType& exp)
 
718
  {
 
719
    //test if no scans with MS-level 1 exist => prevent deadlock
 
720
    bool ms1_present = false;
 
721
    for (Size i = 0; i < exp.size(); ++i)
 
722
    {
 
723
        if (exp[i].getMSLevel() == 1)
 
724
        {
 
725
            ms1_present = true;
 
726
            break;
 
727
        }
 
728
    }
 
729
    return ms1_present;
 
730
  }
 
731
 
 
732
  // static
 
733
  float TOPPViewBase::estimateNoiseFromRandomMS1Scans(const ExperimentType& exp, UInt n_scans)
 
734
  {
 
735
    if (!TOPPViewBase::containsMS1Scans(exp))
 
736
    {
 
737
      return 0.0;
 
738
    }
 
739
 
 
740
    float noise = 0.0;
 
741
    UInt count = 0;
 
742
    srand(time(0));
 
743
    while (count < n_scans)
 
744
    {
 
745
      UInt scan = (UInt)( (double)rand() / ((double)(RAND_MAX)+1.0f) * (double)(exp.size()-1) );
 
746
 
 
747
      if (scan < exp.size() && exp[scan].getMSLevel()==1 && exp[scan].size()!=0)
 
748
      {
 
749
        vector<float> tmp;
 
750
        tmp.reserve(exp[scan].size());
 
751
        for(SpectrumType::ConstIterator it = exp[scan].begin()
 
752
          ; it != exp[scan].end()
 
753
              ; ++it)
 
754
        {
 
755
          tmp.push_back(it->getIntensity());
 
756
        }
 
757
        std::sort(tmp.begin(),tmp.end());
 
758
        noise += tmp[(UInt)ceil((float)(tmp.size()-1)/1.25f)];
 
759
        ++count;
 
760
      }
 
761
    }
 
762
    return noise / (DoubleReal)n_scans;
 
763
  }
 
764
 
 
765
  // static
 
766
  UInt TOPPViewBase::countMS1Zeros(const ExperimentType& exp)
 
767
  {
 
768
    if (!TOPPViewBase::containsMS1Scans(exp))
 
769
    {
 
770
      return 0;
 
771
    }
 
772
 
 
773
    UInt zeros = 0;
 
774
    for (Size i = 0; i != exp.size(); ++i)
 
775
    {
 
776
      if (exp[i].getMSLevel() != 1) // skip non MS1-level scans
 
777
      {
 
778
        continue;
 
779
      }
 
780
      for(Size j = 0; j != exp[i].size(); ++j)
 
781
      {
 
782
        DoubleReal intensity = exp[i][j].getIntensity();
 
783
        if (intensity == 0.0)
 
784
        {
 
785
          zeros++;
 
786
        }
 
787
      }
 
788
    }
 
789
    return zeros;
 
790
  }
 
791
 
 
792
  // static
 
793
  bool TOPPViewBase::hasPeptideIdentifications(const ExperimentType& map)
 
794
  {
 
795
    for(Size i = 0; i!= map.size(); ++i)
 
796
    {
 
797
      if ( !map[i].getPeptideIdentifications().empty())
 
798
      {
 
799
        return true;
 
800
      }
 
801
    }
 
802
    return false;
 
803
  }
 
804
 
 
805
  void TOPPViewBase::preferencesDialog()
 
806
  {
 
807
                Internal::TOPPViewPrefDialog dlg(this);
 
808
 
 
809
    // --------------------------------------------------------------------
 
810
    // Get pointers to the widget in the preferences dialog
 
811
 
 
812
    // default tab
 
813
                QLineEdit* default_path = dlg.findChild<QLineEdit*>("default_path");
 
814
                QCheckBox* default_path_current = dlg.findChild<QCheckBox*>("default_path_current");
 
815
                QLineEdit* temp_path = dlg.findChild<QLineEdit*>("temp_path");
 
816
                QSpinBox* recent_files = dlg.findChild<QSpinBox*>("recent_files");
 
817
                QComboBox* map_default = dlg.findChild<QComboBox*>("map_default");
 
818
                QComboBox* map_cutoff = dlg.findChild<QComboBox*>("map_cutoff");
 
819
                QComboBox* on_file_change = dlg.findChild<QComboBox*>("on_file_change");
 
820
 
 
821
    // db tab
 
822
                QLineEdit* db_host = dlg.findChild<QLineEdit*>("db_host");
 
823
                QSpinBox* db_port = dlg.findChild<QSpinBox*>("db_port");
 
824
                QLineEdit* db_name = dlg.findChild<QLineEdit*>("db_name");
 
825
                QLineEdit* db_login = dlg.findChild<QLineEdit*>("db_login");
 
826
 
 
827
    // 1D view tab
 
828
                ColorSelector* color_1D = dlg.findChild<ColorSelector*>("color_1D");
 
829
                ColorSelector* selected_1D = dlg.findChild<ColorSelector*>("selected_1D");
 
830
                ColorSelector* icon_1D = dlg.findChild<ColorSelector*>("icon_1D");
 
831
 
 
832
    // 2D view tab
 
833
                MultiGradientSelector* peak_2D = dlg.findChild<MultiGradientSelector*>("peak_2D");
 
834
                QComboBox* mapping_2D = dlg.findChild<QComboBox*>("mapping_2D");
 
835
                QComboBox* feature_icon_2D = dlg.findChild<QComboBox*>("feature_icon_2D");
 
836
                QSpinBox* feature_icon_size_2D = dlg.findChild<QSpinBox*>("feature_icon_size_2D");
 
837
 
 
838
    // 3D view tab
 
839
                MultiGradientSelector* peak_3D = dlg.findChild<MultiGradientSelector*>("peak_3D");
 
840
                QComboBox* shade_3D = dlg.findChild<QComboBox*>("shade_3D");
 
841
                QSpinBox* line_width_3D  = dlg.findChild<QSpinBox*>("line_width_3D");
 
842
 
 
843
    // identification view tab
 
844
    QListWidget* id_view_ions = dlg.findChild<QListWidget*>("ions_list_widget");
 
845
    QDoubleSpinBox* a_intensity = dlg.findChild<QDoubleSpinBox*>("a_intensity");
 
846
    QDoubleSpinBox* b_intensity = dlg.findChild<QDoubleSpinBox*>("b_intensity");
 
847
    QDoubleSpinBox* c_intensity = dlg.findChild<QDoubleSpinBox*>("c_intensity");
 
848
    QDoubleSpinBox* x_intensity = dlg.findChild<QDoubleSpinBox*>("x_intensity");
 
849
    QDoubleSpinBox* y_intensity = dlg.findChild<QDoubleSpinBox*>("y_intensity");
 
850
    QDoubleSpinBox* z_intensity = dlg.findChild<QDoubleSpinBox*>("z_intensity");
 
851
 
 
852
    QDoubleSpinBox* tolerance = dlg.findChild<QDoubleSpinBox*>("tolerance");
 
853
    QCheckBox* is_relative_tolerance = dlg.findChild<QCheckBox*>("unit_is_ppm");
 
854
 
 
855
    QDoubleSpinBox* relative_loss_intensity = dlg.findChild<QDoubleSpinBox*>("relative_loss_intensity");
 
856
    QSpinBox* max_isotopes = dlg.findChild<QSpinBox*>("max_isotopes");
 
857
    QSpinBox* charge = dlg.findChild<QSpinBox*>("charge");
 
858
 
 
859
    QList<QListWidgetItem*> a_ions = id_view_ions->findItems("A-ions", Qt::MatchFixedString);
 
860
    QList<QListWidgetItem*> b_ions = id_view_ions->findItems("B-ions", Qt::MatchFixedString);
 
861
    QList<QListWidgetItem*> c_ions = id_view_ions->findItems("C-ions", Qt::MatchFixedString);
 
862
    QList<QListWidgetItem*> x_ions = id_view_ions->findItems("X-ions", Qt::MatchFixedString);
 
863
    QList<QListWidgetItem*> y_ions = id_view_ions->findItems("Y-ions", Qt::MatchFixedString);
 
864
    QList<QListWidgetItem*> z_ions = id_view_ions->findItems("Z-ions", Qt::MatchFixedString);
 
865
    QList<QListWidgetItem*> pc_ions = id_view_ions->findItems("Precursor", Qt::MatchFixedString);
 
866
    QList<QListWidgetItem*> nl_ions = id_view_ions->findItems("Neutral losses", Qt::MatchFixedString);
 
867
    QList<QListWidgetItem*> ic_ions = id_view_ions->findItems("Isotope clusters", Qt::MatchFixedString);
 
868
    QList<QListWidgetItem*> ai_ions = id_view_ions->findItems("Abundant immonium-ions", Qt::MatchFixedString);
 
869
 
 
870
    // --------------------------------------------------------------------
 
871
    // Set dialog entries from current parameter object (default values)
 
872
 
 
873
    // default
 
874
                default_path->setText(param_.getValue("preferences:default_path").toQString());
 
875
                if ((String)param_.getValue("preferences:default_path_current")=="true")
 
876
                {
 
877
                        default_path_current->setChecked(true);
 
878
                }
 
879
                else
 
880
                {
 
881
                        default_path_current->setChecked(false);
 
882
                }
 
883
                temp_path->setText(param_.getValue("preferences:tmp_file_path").toQString());
 
884
                recent_files->setValue((Int)param_.getValue("preferences:number_of_recent_files"));
 
885
                map_default->setCurrentIndex(map_default->findText(param_.getValue("preferences:default_map_view").toQString()));
 
886
                map_cutoff->setCurrentIndex(map_cutoff->findText(param_.getValue("preferences:intensity_cutoff").toQString()));
 
887
                on_file_change->setCurrentIndex(on_file_change->findText(param_.getValue("preferences:on_file_change").toQString()));
 
888
 
 
889
    // db
 
890
                db_host->setText(param_.getValue("preferences:db:host").toQString());
 
891
                db_port->setValue((Int)param_.getValue("preferences:db:port"));
 
892
                db_name->setText(param_.getValue("preferences:db:name").toQString());
 
893
                db_login->setText(param_.getValue("preferences:db:login").toQString());
 
894
 
 
895
    // 1D view
 
896
                color_1D->setColor(QColor(param_.getValue("preferences:1d:peak_color").toQString()));
 
897
                selected_1D->setColor(QColor(param_.getValue("preferences:1d:highlighted_peak_color").toQString()));
 
898
                icon_1D->setColor(QColor(param_.getValue("preferences:1d:icon_color").toQString()));
 
899
 
 
900
    // 2D view
 
901
                peak_2D->gradient().fromString(param_.getValue("preferences:2d:dot:gradient"));
 
902
                mapping_2D->setCurrentIndex(mapping_2D->findText(param_.getValue("preferences:2d:mapping_of_mz_to").toQString()));
 
903
                feature_icon_2D->setCurrentIndex(feature_icon_2D->findText(param_.getValue("preferences:2d:dot:feature_icon").toQString()));
 
904
                feature_icon_size_2D->setValue((Int)param_.getValue("preferences:2d:dot:feature_icon_size"));
 
905
 
 
906
    // 3D view
 
907
                peak_3D->gradient().fromString(param_.getValue("preferences:3d:dot:gradient"));
 
908
                shade_3D->setCurrentIndex((Int)param_.getValue("preferences:3d:dot:shade_mode"));
 
909
                line_width_3D->setValue((Int)param_.getValue("preferences:3d:dot:line_width"));
 
910
 
 
911
    // id view
 
912
    a_intensity->setValue((DoubleReal)param_.getValue("preferences:idview:a_intensity"));
 
913
    b_intensity->setValue((DoubleReal)param_.getValue("preferences:idview:b_intensity"));
 
914
    c_intensity->setValue((DoubleReal)param_.getValue("preferences:idview:c_intensity"));
 
915
    x_intensity->setValue((DoubleReal)param_.getValue("preferences:idview:x_intensity"));
 
916
    y_intensity->setValue((DoubleReal)param_.getValue("preferences:idview:y_intensity"));
 
917
    z_intensity->setValue((DoubleReal)param_.getValue("preferences:idview:z_intensity"));
 
918
    tolerance->setValue((DoubleReal)param_.getValue("preferences:idview:tolerance"));
 
919
 
 
920
    relative_loss_intensity->setValue((DoubleReal)param_.getValue("preferences:idview:relative_loss_intensity"));
 
921
    max_isotopes->setValue((Int)param_.getValue("preferences:idview:max_isotope"));
 
922
    charge->setValue((Int)param_.getValue("preferences:idview:charge"));
 
923
 
 
924
    if(a_ions.empty())
 
925
    {
 
926
      showLogMessage_(LS_ERROR,"", "String 'A-ions' doesn't exist in identification dialog.");
 
927
    } else
 
928
    {
 
929
      Qt::CheckState state = param_.getValue("preferences:idview:show_a_ions").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
930
      a_ions[0]->setCheckState(state);
 
931
    }
 
932
 
 
933
    if(b_ions.empty())
 
934
    {
 
935
      showLogMessage_(LS_ERROR,"", "String 'B-ions' doesn't exist in identification dialog.");
 
936
    } else
 
937
    {
 
938
      Qt::CheckState state = param_.getValue("preferences:idview:show_b_ions").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
939
      b_ions[0]->setCheckState(state);
 
940
    }
 
941
 
 
942
    if(c_ions.empty())
 
943
    {
 
944
      showLogMessage_(LS_ERROR,"", "String 'C-ions' doesn't exist in identification dialog.");
 
945
    } else
 
946
    {
 
947
      Qt::CheckState state = param_.getValue("preferences:idview:show_c_ions").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
948
      c_ions[0]->setCheckState(state);
 
949
    }
 
950
 
 
951
    if(x_ions.empty())
 
952
    {
 
953
      showLogMessage_(LS_ERROR,"", "String 'X-ions' doesn't exist in identification dialog.");
 
954
    } else
 
955
    {
 
956
      Qt::CheckState state = param_.getValue("preferences:idview:show_x_ions").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
957
      x_ions[0]->setCheckState(state);
 
958
    }
 
959
 
 
960
    if(y_ions.empty())
 
961
    {
 
962
      showLogMessage_(LS_ERROR,"", "String 'Y-ions' doesn't exist in identification dialog.");
 
963
    } else
 
964
    {
 
965
      Qt::CheckState state = param_.getValue("preferences:idview:show_y_ions").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
966
      y_ions[0]->setCheckState(state);
 
967
    }
 
968
 
 
969
    if(z_ions.empty())
 
970
    {
 
971
      showLogMessage_(LS_ERROR,"", "String 'Z-ions' doesn't exist in identification dialog.");
 
972
    } else
 
973
    {
 
974
      Qt::CheckState state = param_.getValue("preferences:idview:show_z_ions").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
975
      z_ions[0]->setCheckState(state);
 
976
    }
 
977
 
 
978
    if(pc_ions.empty())
 
979
    {
 
980
      showLogMessage_(LS_ERROR,"", "String 'Precursor' doesn't exist in identification dialog.");
 
981
    } else
 
982
    {
 
983
      Qt::CheckState state = param_.getValue("preferences:idview:show_precursor").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
984
      pc_ions[0]->setCheckState(state);
 
985
    }
 
986
 
 
987
    if(nl_ions.empty())
 
988
    {
 
989
      showLogMessage_(LS_ERROR,"", "String 'Neutral losses' doesn't exist in identification dialog.");
 
990
    } else
 
991
    {
 
992
      Qt::CheckState state = param_.getValue("preferences:idview:add_losses").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
993
      nl_ions[0]->setCheckState(state);
 
994
    }
 
995
 
 
996
    if(ic_ions.empty())
 
997
    {
 
998
      showLogMessage_(LS_ERROR,"", "String 'Isotope clusters' doesn't exist in identification dialog.");
 
999
    } else
 
1000
    {
 
1001
      Qt::CheckState state = param_.getValue("preferences:idview:add_isotopes").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
1002
      ic_ions[0]->setCheckState(state);
 
1003
    }
 
1004
 
 
1005
    if(ai_ions.empty())
 
1006
    {
 
1007
      showLogMessage_(LS_ERROR,"", "String 'Abundant immonium-ions' doesn't exist in identification dialog.");
 
1008
    } else
 
1009
    {
 
1010
      Qt::CheckState state = param_.getValue("preferences:idview:add_abundant_immonium_ions").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
1011
      ai_ions[0]->setCheckState(state);
 
1012
    }
 
1013
 
 
1014
    if(is_relative_tolerance == 0)
 
1015
    {
 
1016
      showLogMessage_(LS_ERROR,"", "String 'unit is ppm' doesn't exist in identification dialog.");
 
1017
    } else
 
1018
    {
 
1019
      Qt::CheckState state = param_.getValue("preferences:idview:is_relative_tolerance").toBool() == true ? Qt::Checked : Qt::Unchecked;
 
1020
      is_relative_tolerance->setCheckState(state);
 
1021
    }
 
1022
 
 
1023
    // --------------------------------------------------------------------
 
1024
    // Execute dialog and update parameter object with user modified values
 
1025
                if (dlg.exec())
 
1026
                {
 
1027
                        param_.setValue("preferences:default_path", default_path->text());
 
1028
                        if (default_path_current->isChecked())
 
1029
                        {
 
1030
                                param_.setValue("preferences:default_path_current","true");
 
1031
                        }
 
1032
                        else
 
1033
                        {
 
1034
                                param_.setValue("preferences:default_path_current","false");
 
1035
                        }
 
1036
                        param_.setValue("preferences:tmp_file_path", temp_path->text());
 
1037
                        param_.setValue("preferences:number_of_recent_files", recent_files->value());
 
1038
                        param_.setValue("preferences:default_map_view", map_default->currentText());
 
1039
                        param_.setValue("preferences:intensity_cutoff", map_cutoff->currentText());
 
1040
                        param_.setValue("preferences:on_file_change", on_file_change->currentText());
 
1041
 
 
1042
                        param_.setValue("preferences:db:host",db_host->text());
 
1043
                        param_.setValue("preferences:db:port",db_port->value());
 
1044
                        param_.setValue("preferences:db:name",db_name->text());
 
1045
                        param_.setValue("preferences:db:login",db_login->text());
 
1046
                        param_.remove("DBPassword");
 
1047
 
 
1048
                        param_.setValue("preferences:1d:peak_color",color_1D->getColor().name());
 
1049
                        param_.setValue("preferences:1d:highlighted_peak_color",selected_1D->getColor().name());
 
1050
                        param_.setValue("preferences:1d:icon_color",icon_1D->getColor().name());
 
1051
 
 
1052
                        param_.setValue("preferences:2d:dot:gradient",peak_2D->gradient().toString());
 
1053
                        param_.setValue("preferences:2d:mapping_of_mz_to",mapping_2D->currentText());
 
1054
                        param_.setValue("preferences:2d:dot:feature_icon",feature_icon_2D->currentText());
 
1055
                        param_.setValue("preferences:2d:dot:feature_icon_size",feature_icon_size_2D->value());
 
1056
 
 
1057
                        param_.setValue("preferences:3d:dot:gradient",peak_3D->gradient().toString());
 
1058
                        param_.setValue("preferences:3d:dot:shade_mode", shade_3D->currentIndex());
 
1059
                        param_.setValue("preferences:3d:dot:line_width",line_width_3D->value());
 
1060
 
 
1061
      // id view
 
1062
      param_.setValue("preferences:idview:a_intensity", a_intensity->value(), "Default intensity of a-ions");
 
1063
      param_.setValue("preferences:idview:b_intensity", b_intensity->value(), "Default intensity of b-ions");
 
1064
      param_.setValue("preferences:idview:c_intensity", c_intensity->value(), "Default intensity of c-ions");
 
1065
      param_.setValue("preferences:idview:x_intensity", x_intensity->value(), "Default intensity of x-ions");
 
1066
      param_.setValue("preferences:idview:y_intensity", y_intensity->value(), "Default intensity of y-ions");
 
1067
      param_.setValue("preferences:idview:z_intensity", z_intensity->value(), "Default intensity of z-ions");
 
1068
      param_.setValue("preferences:idview:relative_loss_intensity", relative_loss_intensity->value(), "Relativ loss in percent");
 
1069
      param_.setValue("preferences:idview:max_isotope", max_isotopes->value(), "Maximum number of isotopes");
 
1070
      param_.setValue("preferences:idview:charge", charge->value(), "Charge state");
 
1071
      param_.setValue("preferences:idview:tolerance", tolerance->value(), "Alignment tolerance");
 
1072
 
 
1073
      String checked;
 
1074
      a_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1075
      param_.setValue("preferences:idview:show_a_ions", checked, "Show a-ions");
 
1076
 
 
1077
      b_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1078
      param_.setValue("preferences:idview:show_b_ions", checked, "Show b-ions");
 
1079
 
 
1080
      c_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1081
      param_.setValue("preferences:idview:show_c_ions", checked, "Show c-ions");
 
1082
 
 
1083
      x_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1084
      param_.setValue("preferences:idview:show_x_ions", checked, "Show x-ions");
 
1085
 
 
1086
      y_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1087
      param_.setValue("preferences:idview:show_y_ions", checked, "Show y-ions");
 
1088
 
 
1089
      z_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1090
      param_.setValue("preferences:idview:show_z_ions", checked, "Show z-ions");
 
1091
 
 
1092
      pc_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1093
      param_.setValue("preferences:idview:show_precursor", checked, "Show precursor");
 
1094
 
 
1095
      nl_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1096
      param_.setValue("preferences:idview:add_losses", checked, "Show neutral losses");
 
1097
 
 
1098
      ic_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1099
      param_.setValue("preferences:idview:add_isotopes", checked, "Show isotopes");
 
1100
 
 
1101
      ai_ions[0]->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1102
      param_.setValue("preferences:idview:add_abundant_immonium_ions", checked, "Show abundant immonium ions");
 
1103
 
 
1104
      is_relative_tolerance->checkState() == Qt::Checked ? checked = "true" : checked = "false";
 
1105
      param_.setValue("preferences:idview:is_relative_tolerance", checked, "Use ppm instead of Da for the automatic alignment");
 
1106
                        savePreferences();
 
1107
                }
 
1108
  }
 
1109
 
 
1110
  std::set<String> TOPPViewBase::getFilenamesOfOpenFiles_()
 
1111
  {
 
1112
    set<String> filename_set;
 
1113
    // iterate over all windows
 
1114
    QWidgetList wl = ws_->windowList();
 
1115
    for(int i=0; i!=ws_->windowList().count(); ++i)
 
1116
    {
 
1117
      QWidget* w = wl[i];
 
1118
      // iterate over all widgets
 
1119
      const SpectrumWidget* sw = qobject_cast<const SpectrumWidget*>(w);
 
1120
      if (sw!=0)
 
1121
      {
 
1122
        Size lc = sw->canvas()->getLayerCount();
 
1123
        // iterate over all layers
 
1124
        for (Size j=0; j!= lc; ++j)
 
1125
        {
 
1126
          filename_set.insert(sw->canvas()->getLayer(j).filename);
 
1127
        }
 
1128
      }
 
1129
    }
 
1130
    return filename_set;
 
1131
  }
 
1132
 
 
1133
  void TOPPViewBase::addDataFile(const String& filename, bool show_options, bool add_to_recent, String caption, UInt window_id, Size spectrum_id)
 
1134
  {
 
1135
    setCursor(Qt::WaitCursor);
 
1136
 
 
1137
        String abs_filename = File::absolutePath(filename);
 
1138
 
 
1139
    // check if the file exists
 
1140
    if (!File::exists(abs_filename))
 
1141
    {
 
1142
      showLogMessage_(LS_ERROR, "Open file error",String("The file '") + abs_filename + "' does not exist!");
 
1143
        setCursor(Qt::ArrowCursor);
 
1144
      return;
 
1145
    }
 
1146
 
 
1147
    // determine file type
 
1148
        FileHandler fh;
 
1149
                FileTypes::Type file_type = fh.getType(abs_filename);
 
1150
    if (file_type == FileTypes::UNKNOWN)
 
1151
                {
 
1152
      showLogMessage_(LS_ERROR,"Open file error",String("Could not determine file type of '") + abs_filename + "'!");
 
1153
        setCursor(Qt::ArrowCursor);
 
1154
      return;
 
1155
                }
 
1156
 
 
1157
    // abort if file type unsupported
 
1158
    if (file_type == FileTypes::INI)
 
1159
                {
 
1160
      showLogMessage_(LS_ERROR,"Open file error",String("The type '") + fh.typeToName(file_type) + "' is not supported!");
 
1161
                setCursor(Qt::ArrowCursor);
 
1162
      return;
 
1163
                }
 
1164
 
 
1165
                //try to load data and determine if it's 1D or 2D data
 
1166
 
 
1167
    // create shared pointer to main data types
 
1168
    FeatureMapType* feature_map = new FeatureMapType();
 
1169
    FeatureMapSharedPtrType feature_map_sptr(feature_map);
 
1170
 
 
1171
    ExperimentType* peak_map = new ExperimentType();
 
1172
    ExperimentSharedPtrType peak_map_sptr(peak_map);
 
1173
 
 
1174
    ConsensusMapType* consensus_map = new ConsensusMapType();
 
1175
    ConsensusMapSharedPtrType consensus_map_sptr(consensus_map);
 
1176
 
 
1177
                vector<PeptideIdentification> peptides;
 
1178
 
 
1179
                LayerData::DataType data_type;
 
1180
 
 
1181
    try
 
1182
    {
 
1183
      if (file_type == FileTypes::FEATUREXML)
 
1184
            {
 
1185
        FeatureXMLFile().load(abs_filename, *feature_map);
 
1186
                                data_type = LayerData::DT_FEATURE;
 
1187
      }
 
1188
      else if (file_type == FileTypes::CONSENSUSXML)
 
1189
            {
 
1190
        ConsensusXMLFile().load(abs_filename, *consensus_map);
 
1191
                                data_type = LayerData::DT_CONSENSUS;
 
1192
      }
 
1193
                        else if (file_type == FileTypes::IDXML)
 
1194
                        {
 
1195
                                vector<ProteinIdentification> proteins; // not needed later
 
1196
                                IdXMLFile().load(abs_filename, proteins, peptides);
 
1197
                                data_type = LayerData::DT_IDENT;
 
1198
                        }
 
1199
      else
 
1200
      {
 
1201
        fh.loadExperiment(abs_filename, *peak_map, file_type, ProgressLogger::GUI);
 
1202
        data_type = LayerData::DT_CHROMATOGRAM;
 
1203
        if (TOPPViewBase::containsMS1Scans(*peak_map))
 
1204
        {
 
1205
          data_type = LayerData::DT_PEAK;
 
1206
        }
 
1207
      }
 
1208
    }
 
1209
    catch(Exception::BaseException& e)
 
1210
    {
 
1211
      showLogMessage_(LS_ERROR,"Error while loading file", e.what());
 
1212
        setCursor(Qt::ArrowCursor);
 
1213
      return;
 
1214
    }
 
1215
 
 
1216
    // sort for mz and update ranges of newly loaded data
 
1217
    peak_map_sptr->sortSpectra(true);
 
1218
    peak_map_sptr->updateRanges(1);
 
1219
 
 
1220
    // try to add the data
 
1221
    if (caption == "")
 
1222
                {
 
1223
                        caption = File::basename(abs_filename);
 
1224
    }
 
1225
    else
 
1226
    {
 
1227
        abs_filename = "";
 
1228
    }
 
1229
 
 
1230
    addData(feature_map_sptr, consensus_map_sptr, peptides, peak_map_sptr, data_type, false, show_options, true, abs_filename, caption, window_id, spectrum_id);
 
1231
 
 
1232
    // add to recent file
 
1233
    if (add_to_recent)
 
1234
    {
 
1235
      addRecentFile_(filename);
 
1236
    }
 
1237
 
 
1238
    // watch file contents for changes
 
1239
    watcher_->addFile(abs_filename);
 
1240
 
 
1241
    // reset cursor
 
1242
    setCursor(Qt::ArrowCursor);
 
1243
  }
 
1244
 
 
1245
  void TOPPViewBase::addData(FeatureMapSharedPtrType feature_map, ConsensusMapSharedPtrType consensus_map, vector<PeptideIdentification>& peptides, ExperimentSharedPtrType peak_map, LayerData::DataType data_type, bool show_as_1d, bool show_options, bool as_new_window, const String& filename, const String& caption, UInt window_id, Size spectrum_id)
 
1246
  {
 
1247
    // initialize flags with defaults from the parameters
 
1248
        bool maps_as_2d = ((String)param_.getValue("preferences:default_map_view")=="2d");
 
1249
        bool maps_as_1d = false;
 
1250
    bool use_intensity_cutoff = ((String)param_.getValue("preferences:intensity_cutoff")=="on");
 
1251
 
 
1252
    // feature, consensus feature and identifications can be merged
 
1253
                bool mergeable = ((data_type == LayerData::DT_FEATURE) ||
 
1254
                                                                                        (data_type == LayerData::DT_CONSENSUS) ||
 
1255
                                                                                        (data_type == LayerData::DT_IDENT));
 
1256
 
 
1257
    // only one peak spectrum? disable 2D as default
 
1258
    if (peak_map->size() == 1)
 
1259
    {
 
1260
      maps_as_2d = false;
 
1261
    }
 
1262
 
 
1263
    // set the window where (new layer) data could be opened in
 
1264
    // get EnhancedTabBarWidget with given id
 
1265
    EnhancedTabBarWidgetInterface* tab_bar_target = window_(window_id);
 
1266
 
 
1267
    // cast to SpectrumWidget
 
1268
    SpectrumWidget* target_window = dynamic_cast<SpectrumWidget*>(tab_bar_target);
 
1269
 
 
1270
    if (tab_bar_target == 0)
 
1271
                {
 
1272
      target_window = getActiveSpectrumWidget();
 
1273
                }
 
1274
    else
 
1275
                {
 
1276
                        as_new_window = false;
 
1277
                }
 
1278
 
 
1279
    //create dialog no matter if it is shown or not. It is used to determine the flags.
 
1280
    TOPPViewOpenDialog dialog(caption, as_new_window, maps_as_2d, use_intensity_cutoff, this);
 
1281
 
 
1282
    //disable opening in new window when there is no active window or feature/ID data is to be opened, but the current window is a 3D window
 
1283
    if (target_window == 0 || (mergeable && dynamic_cast<Spectrum3DWidget*>(target_window) != 0))
 
1284
                {
 
1285
                        dialog.disableLocation(true);
 
1286
                }
 
1287
 
 
1288
    //disable 1d/2d/3d option for feature/consensus/identification maps
 
1289
                if (mergeable)
 
1290
                {
 
1291
                        dialog.disableDimension(true);
 
1292
                }
 
1293
 
 
1294
    //disable cutoff for feature/consensus/identification maps
 
1295
    if (mergeable)
 
1296
    {
 
1297
      dialog.disableCutoff(false);
 
1298
    }
 
1299
 
 
1300
                //enable merge layers if a feature layer is opened and there are already features layers to merge it to
 
1301
    if (mergeable && target_window != 0) //TODO merge
 
1302
                {
 
1303
      SpectrumCanvas* open_canvas = target_window->canvas();
 
1304
                        Map<Size,String> layers;
 
1305
                        for (Size i=0; i<open_canvas->getLayerCount(); ++i)
 
1306
                        {
 
1307
                                if (data_type == open_canvas->getLayer(i).type)
 
1308
                                {
 
1309
                                        layers[i] = open_canvas->getLayer(i).name;
 
1310
                                }
 
1311
                        }
 
1312
                        dialog.setMergeLayers(layers);
 
1313
                }
 
1314
 
 
1315
                //show options if requested
 
1316
                if (show_options && !dialog.exec())
 
1317
                {
 
1318
                        return;
 
1319
                }
 
1320
                as_new_window = dialog.openAsNewWindow();
 
1321
                maps_as_2d = dialog.viewMapAs2D();
 
1322
                maps_as_1d = dialog.viewMapAs1D();
 
1323
                if (show_as_1d)
 
1324
                {
 
1325
                        maps_as_1d = true;
 
1326
                        maps_as_2d = false;
 
1327
                }
 
1328
 
 
1329
    use_intensity_cutoff = dialog.isCutoffEnabled();
 
1330
        Int merge_layer = dialog.getMergeLayer();
 
1331
 
 
1332
                //determine the window to open the data in
 
1333
                if (as_new_window) //new window
 
1334
    {
 
1335
      if (maps_as_1d) // 2d in 1d window
 
1336
      {
 
1337
        target_window = new Spectrum1DWidget(getSpectrumParameters(1), ws_);
 
1338
      }
 
1339
      else if (maps_as_2d || mergeable) //2d or features/IDs
 
1340
      {
 
1341
        target_window = new Spectrum2DWidget(getSpectrumParameters(2), ws_);
 
1342
      }
 
1343
      else // 3d
 
1344
      {
 
1345
        target_window = new Spectrum3DWidget(getSpectrumParameters(3), ws_);
 
1346
      }
 
1347
    }
 
1348
 
 
1349
    if (merge_layer == -1) //add layer to the window
 
1350
    {
 
1351
            if (data_type == LayerData::DT_FEATURE) //features
 
1352
                        {
 
1353
        if (!target_window->canvas()->addLayer(feature_map, filename))
 
1354
        {
 
1355
          return;
 
1356
        }
 
1357
                        }
 
1358
                        else if (data_type == LayerData::DT_CONSENSUS) //consensus features
 
1359
                        {
 
1360
        if (!target_window->canvas()->addLayer(consensus_map,filename)) return;
 
1361
                        }
 
1362
                        else if (data_type == LayerData::DT_IDENT)
 
1363
                        {
 
1364
        if (!target_window->canvas()->addLayer(peptides, filename)) return;
 
1365
                        }
 
1366
            else //peaks
 
1367
            {
 
1368
        if (!target_window->canvas()->addLayer(peak_map,filename)) return;
 
1369
 
 
1370
              //calculate noise
 
1371
        if (use_intensity_cutoff)
 
1372
              {
 
1373
          DoubleReal cutoff = estimateNoiseFromRandomMS1Scans(*(target_window->canvas()->getCurrentLayer().getPeakData()));
 
1374
                                        //create filter
 
1375
                                        DataFilters::DataFilter filter;
 
1376
                                        filter.field = DataFilters::INTENSITY;
 
1377
                                        filter.op = DataFilters::GREATER_EQUAL;
 
1378
                                        filter.value = cutoff;
 
1379
                                        ///add filter
 
1380
                                        DataFilters filters;
 
1381
                                        filters.add(filter);
 
1382
          target_window->canvas()->setFilters(filters);
 
1383
        } else  // no mower, hide zeros if wanted
 
1384
        {
 
1385
          Int n_zeros = TOPPViewBase::countMS1Zeros(*(target_window->canvas()->getCurrentLayer().getPeakData()));
 
1386
          if (n_zeros > 0)
 
1387
          {
 
1388
            //create filter
 
1389
            DataFilters::DataFilter filter;
 
1390
            filter.field = DataFilters::INTENSITY;
 
1391
            filter.op = DataFilters::GREATER_EQUAL;
 
1392
            filter.value = 0.001;
 
1393
            QMessageBox::question(this, "Note:", "Data contains zero values.\nA filter will be added to hide these values.\nYou can reenable data points with zero intensity by removing the filter.");
 
1394
            ///add filter
 
1395
            DataFilters filters;
 
1396
            filters.add(filter);
 
1397
            target_window->canvas()->setFilters(filters);
 
1398
          }
 
1399
        }
 
1400
 
 
1401
        Spectrum1DWidget* open_1d_window = dynamic_cast<Spectrum1DWidget*>(target_window);
 
1402
              if (open_1d_window)
 
1403
              {
 
1404
                open_1d_window->canvas()->activateSpectrum(spectrum_id);
 
1405
              }
 
1406
                        }
 
1407
 
 
1408
                        //set caption
 
1409
      target_window->canvas()->setLayerName(target_window->canvas()->activeLayerIndex(), caption);
 
1410
                }
 
1411
                else //merge feature/ID data into feature layer
 
1412
                {
 
1413
      Spectrum2DCanvas* canvas = qobject_cast<Spectrum2DCanvas*>(target_window->canvas());
 
1414
                        if (data_type == LayerData::DT_CONSENSUS)
 
1415
                        {
 
1416
        canvas->mergeIntoLayer(merge_layer, consensus_map);
 
1417
                        }
 
1418
                        else if (data_type == LayerData::DT_FEATURE)
 
1419
                        {
 
1420
        canvas->mergeIntoLayer(merge_layer, feature_map);
 
1421
                        }
 
1422
                        else if (data_type == LayerData::DT_IDENT)
 
1423
                        {
 
1424
                                canvas->mergeIntoLayer(merge_layer, peptides);
 
1425
                        }
 
1426
                }
 
1427
 
 
1428
    if (as_new_window)
 
1429
    {
 
1430
      showSpectrumWidgetInWindow(target_window,caption);
 
1431
                }
 
1432
    //updateDataBar();
 
1433
                updateLayerBar();
 
1434
    updateViewBar();
 
1435
                updateFilterBar();
 
1436
        updateMenu();
 
1437
        }
 
1438
 
 
1439
  void TOPPViewBase::addRecentFile_(const String& filename)
 
1440
  {
 
1441
        //find out absolute path
 
1442
    String tmp = File::absolutePath(filename);
 
1443
 
 
1444
                // remove the new file if already in the recent list and prepend it
 
1445
                recent_files_.removeAll(tmp.toQString());
 
1446
                recent_files_.prepend(tmp.toQString());
 
1447
 
 
1448
                //remove those files exceeding the defined number
 
1449
                UInt number_of_recent_files = UInt(param_.getValue("preferences:number_of_recent_files"));
 
1450
                while ((UInt)recent_files_.size() > number_of_recent_files)
 
1451
                {
 
1452
                        recent_files_.removeLast();
 
1453
                }
 
1454
    updateRecentMenu_();
 
1455
  }
 
1456
 
 
1457
  void TOPPViewBase::updateRecentMenu_()
 
1458
  {
 
1459
    // get/correct number of recent files
 
1460
                UInt number_of_recent_files = UInt(param_.getValue("preferences:number_of_recent_files"));
 
1461
                if (number_of_recent_files>20)
 
1462
                {
 
1463
                        number_of_recent_files = 20;
 
1464
                        param_.setValue("preferences:number_of_recent_files",20);
 
1465
                }
 
1466
 
 
1467
                for (Size i = 0; i < 20; ++i)
 
1468
                {
 
1469
                        if (i < (UInt)(recent_files_.size()))
 
1470
                        {
 
1471
                                recent_actions_[i]->setText(recent_files_[(int)i]);
 
1472
                                recent_actions_[i]->setVisible(true);
 
1473
                        }
 
1474
                        else
 
1475
                        {
 
1476
                                recent_actions_[i]->setVisible(false);
 
1477
                        }
 
1478
                }
 
1479
  }
 
1480
 
 
1481
  EnhancedTabBarWidgetInterface* TOPPViewBase::window_(int id) const
 
1482
  {
 
1483
    // return window with window_id == id
 
1484
        QList<QWidget*> windows = ws_->windowList();
 
1485
 
 
1486
    for(int i = 0; i < windows.size(); ++i)
 
1487
    {
 
1488
      EnhancedTabBarWidgetInterface* w = dynamic_cast<EnhancedTabBarWidgetInterface*>(windows.at(i));
 
1489
      if (w->getWindowId() == id)
 
1490
                        {
 
1491
        return w;
 
1492
                        }
 
1493
                }
 
1494
                return 0;
 
1495
  }
 
1496
 
 
1497
  void TOPPViewBase::closeByTab(int id)
 
1498
  {
 
1499
    QWidget* w = dynamic_cast<QWidget*>(window_(id));
 
1500
    if (w)
 
1501
        {
 
1502
      w->close();
 
1503
                updateMenu();
 
1504
        }
 
1505
  }
 
1506
 
 
1507
  void TOPPViewBase::enhancedWorkspaceWindowChanged(int id)
 
1508
  {    
 
1509
    QWidget* w = dynamic_cast<QWidget*>(window_(id));
 
1510
    if (w)
 
1511
        {
 
1512
      w->setFocus();
 
1513
      TOPPASWidget* tw = dynamic_cast<TOPPASWidget*>(w);
 
1514
      SpectrumWidget* sw = dynamic_cast<SpectrumWidget*>(w);
 
1515
      if (tw)  // TOPPASWidget
 
1516
      {
 
1517
        setTOPPASTabEnabled(true);
 
1518
        views_tabwidget_->setCurrentIndex(2);
 
1519
        views_tabwidget_->setTabEnabled(0, false);  // switch scan view off
 
1520
        views_tabwidget_->setTabEnabled(1, false);  // switch identification view off
 
1521
      }
 
1522
      else if (sw)  // SpectrumWidget
 
1523
      {
 
1524
        views_tabwidget_->setTabEnabled(0, true);
 
1525
 
 
1526
        // check if there is a layer before requesting data from it
 
1527
        if(sw->canvas()->getLayerCount() > 0)
 
1528
        {
 
1529
          const ExperimentType& map = *sw->canvas()->getCurrentLayer().getPeakData();
 
1530
          if(hasPeptideIdentifications(map))
 
1531
          {
 
1532
            views_tabwidget_->setTabEnabled(1, true);
 
1533
            if (dynamic_cast<Spectrum2DWidget*>(w))
 
1534
            {
 
1535
              views_tabwidget_->setCurrentIndex(0);  // switch to scan tab for 2D widget
 
1536
            } else if (dynamic_cast<Spectrum1DWidget*>(w))
 
1537
            {
 
1538
              views_tabwidget_->setCurrentIndex(1);  // switch to identification tab for 1D widget
 
1539
            }
 
1540
          }
 
1541
          else
 
1542
          {
 
1543
            views_tabwidget_->setTabEnabled(1, false);
 
1544
            views_tabwidget_->setCurrentIndex(0); // stay on scan view tab
 
1545
          }
 
1546
          setTOPPASTabEnabled(false);
 
1547
        }
 
1548
      }
 
1549
        }
 
1550
  }
 
1551
 
 
1552
  void TOPPViewBase::closeFile()
 
1553
  {
 
1554
    ws_->activeWindow()->close();
 
1555
    updateMenu();
 
1556
  }
 
1557
 
 
1558
  void TOPPViewBase::editMetadata()
 
1559
  {
 
1560
    SpectrumCanvas* canvas = getActiveCanvas();
 
1561
 
 
1562
    // warn if hidden layer => wrong layer selected...
 
1563
        if (!canvas->getCurrentLayer().visible)
 
1564
        {
 
1565
                showLogMessage_(LS_NOTICE,"The current layer is not visible","Have you selected the right layer for this action?");
 
1566
        }
 
1567
 
 
1568
        //show editable meta data dialog
 
1569
        canvas->showMetaData(true);
 
1570
  }
 
1571
 
 
1572
  void TOPPViewBase::layerStatistics()
 
1573
  {
 
1574
    getActiveSpectrumWidget()->showStatistics();
 
1575
        updateFilterBar();
 
1576
  }
 
1577
 
 
1578
  void TOPPViewBase::showStatusMessage(string msg, OpenMS::UInt time)
 
1579
  {
 
1580
    if (time == 0)
 
1581
    {
 
1582
      message_label_->setText(msg.c_str());
 
1583
      statusBar()->update();
 
1584
    }
 
1585
    else
 
1586
    {
 
1587
      statusBar()->showMessage(msg.c_str(), time);
 
1588
    }
 
1589
    QApplication::processEvents();
 
1590
  }
 
1591
 
 
1592
  void TOPPViewBase::showCursorStatusInvert(double mz, double rt)
 
1593
  {
 
1594
    // swap rt vs mz (for vertical projection)
 
1595
    showCursorStatus(rt, mz);
 
1596
  }
 
1597
 
 
1598
  void TOPPViewBase::showCursorStatus(double mz, double rt)
 
1599
  {
 
1600
    message_label_->setText("");
 
1601
    if (mz == -1)
 
1602
    {
 
1603
      mz_label_->setText("m/z: ");
 
1604
    }
 
1605
    else if (boost::math::isinf(mz) || boost::math::isnan(mz))
 
1606
                {
 
1607
      mz_label_->setText("m/z: n/a");
 
1608
                }
 
1609
    else
 
1610
    {
 
1611
      mz_label_->setText((String("m/z: ")+String::number(mz,6).fillLeft(' ',8)).toQString());
 
1612
    }
 
1613
 
 
1614
    if (rt == -1)
 
1615
    {
 
1616
      rt_label_->setText("RT: ");
 
1617
    }
 
1618
    else if (boost::math::isinf(rt) || boost::math::isnan(rt))
 
1619
                {
 
1620
      rt_label_->setText("RT: n/a");
 
1621
                }
 
1622
    else
 
1623
    {
 
1624
      rt_label_->setText((String("RT: ")+String::number(rt,1).fillLeft(' ',8)).toQString());
 
1625
    }
 
1626
    statusBar()->update();
 
1627
  }
 
1628
 
 
1629
  void TOPPViewBase::resetZoom()
 
1630
  {
 
1631
    SpectrumWidget* w = getActiveSpectrumWidget();
 
1632
    if (w != 0)
 
1633
    {
 
1634
      w->canvas()->resetZoom();
 
1635
    }
 
1636
  }
 
1637
 
 
1638
  void TOPPViewBase::setIntensityMode(int index)
 
1639
  {
 
1640
    SpectrumWidget* w = getActiveSpectrumWidget();
 
1641
    if (w)
 
1642
    {
 
1643
      intensity_button_group_->button(index)->setChecked(true);
 
1644
      Spectrum2DWidget* w2d = dynamic_cast<Spectrum2DWidget*>(w);
 
1645
      // 2D widget and intensity mode changed?
 
1646
      if (w2d && w2d->canvas()->getIntensityMode() != index)
 
1647
      {
 
1648
        if (index == OpenMS::SpectrumCanvas::IM_LOG)
 
1649
        {
 
1650
          w2d->canvas()->getCurrentLayer().param.setValue("dot:gradient", MultiGradient::getDefaultGradientLogarithmicIntensityMode().toString());
 
1651
          w2d->canvas()->recalculateCurrentLayerDotGradient();
 
1652
        } else if (index != OpenMS::SpectrumCanvas::IM_LOG)
 
1653
        {
 
1654
          w2d->canvas()->getCurrentLayer().param.setValue("dot:gradient", MultiGradient::getDefaultGradientLinearIntensityMode().toString());
 
1655
          w2d->canvas()->recalculateCurrentLayerDotGradient();
 
1656
        }
 
1657
      }
 
1658
        w->setIntensityMode((OpenMS::SpectrumCanvas::IntensityModes)index);
 
1659
        }
 
1660
  }
 
1661
 
 
1662
  void TOPPViewBase::setDrawMode1D(int index)
 
1663
  {
 
1664
    Spectrum1DWidget* w = getActive1DWidget();
 
1665
    if (w)
 
1666
    {
 
1667
      draw_group_1d_->button(Spectrum1DCanvas::DM_PEAKS)->setChecked(true);
 
1668
        w->canvas()->setDrawMode((OpenMS::Spectrum1DCanvas::DrawModes)index);
 
1669
        }
 
1670
  }
 
1671
 
 
1672
        void TOPPViewBase::changeLabel(QAction* action)
 
1673
        {
 
1674
    bool set = false;
 
1675
 
 
1676
                //label type is selected
 
1677
                for (Size i=0; i<LayerData::SIZE_OF_LABEL_TYPE; ++i)
 
1678
                {
 
1679
      if (action->text().toStdString() == LayerData::NamesOfLabelType[i])
 
1680
                        {
 
1681
        getActive2DWidget()->canvas()->setLabel(LayerData::LabelType(i));
 
1682
                                set = true;
 
1683
                        }
 
1684
                }
 
1685
 
 
1686
                //button is simply pressed
 
1687
                if (!set)
 
1688
                {
 
1689
      if (getActive2DWidget()->canvas()->getCurrentLayer().label == LayerData::L_NONE)
 
1690
                        {
 
1691
        getActive2DWidget()->canvas()->setLabel(LayerData::L_INDEX);
 
1692
                                dm_label_2d_->menu()->actions()[1]->setChecked(true);
 
1693
                        }
 
1694
                        else
 
1695
                        {
 
1696
        getActive2DWidget()->canvas()->setLabel(LayerData::L_NONE);
 
1697
                                dm_label_2d_->menu()->actions()[0]->setChecked(true);
 
1698
                        }
 
1699
                }
 
1700
 
 
1701
                updateToolBar();
 
1702
        }
 
1703
 
 
1704
        void TOPPViewBase::changeUnassigned(QAction* action)
 
1705
        {
 
1706
                bool set = false;
 
1707
 
 
1708
                // mass reference is selected
 
1709
                if (action->text().toStdString() == "Don't show")
 
1710
                {
 
1711
      getActive2DWidget()->canvas()->setLayerFlag(LayerData::F_UNASSIGNED, false);
 
1712
      getActive2DWidget()->canvas()->setLayerFlag(LayerData::I_PEPTIDEMZ, false);
 
1713
                        set = true;
 
1714
                }
 
1715
                else if (action->text().toStdString() == "Show by precursor m/z")
 
1716
                {
 
1717
      getActive2DWidget()->canvas()->setLayerFlag(LayerData::F_UNASSIGNED, true);
 
1718
      getActive2DWidget()->canvas()->setLayerFlag(LayerData::I_PEPTIDEMZ, false);
 
1719
                        set = true;
 
1720
                }
 
1721
                else if (action->text().toStdString() == "Show by peptide mass")
 
1722
                {
 
1723
      getActive2DWidget()->canvas()->setLayerFlag(LayerData::F_UNASSIGNED, true);
 
1724
      getActive2DWidget()->canvas()->setLayerFlag(LayerData::I_PEPTIDEMZ, true);
 
1725
                        set = true;
 
1726
                }
 
1727
 
 
1728
                // button is simply pressed
 
1729
                if (!set)
 
1730
                {
 
1731
      bool previous = getActive2DWidget()->canvas()->getLayerFlag(LayerData::F_UNASSIGNED);
 
1732
      getActive2DWidget()->canvas()->setLayerFlag(LayerData::F_UNASSIGNED,
 
1733
                                                                                                                                                                                                !previous);
 
1734
                        if (previous) // now: don't show
 
1735
                        {
 
1736
                                dm_unassigned_2d_->menu()->actions()[0]->setChecked(true);
 
1737
                        }
 
1738
                        else // now: show by precursor
 
1739
                        {
 
1740
                                dm_unassigned_2d_->menu()->actions()[1]->setChecked(true);
 
1741
                        }
 
1742
      getActive2DWidget()->canvas()->setLayerFlag(LayerData::I_PEPTIDEMZ, false);
 
1743
                }
 
1744
 
 
1745
                updateToolBar();
 
1746
        }
 
1747
 
 
1748
  void TOPPViewBase::changeLayerFlag(bool on)
 
1749
  {
 
1750
                QAction* action = qobject_cast<QAction *>(sender());
 
1751
    if (Spectrum2DWidget* win = getActive2DWidget())
 
1752
    {
 
1753
        //peaks
 
1754
                        if (action == dm_precursors_2d_)
 
1755
                        {
 
1756
                    win->canvas()->setLayerFlag(LayerData::P_PRECURSORS,on);
 
1757
                        }
 
1758
                        //features
 
1759
                        else if (action == dm_hulls_2d_)
 
1760
                        {
 
1761
                    win->canvas()->setLayerFlag(LayerData::F_HULLS,on);
 
1762
                        }
 
1763
                        else if (action == dm_hull_2d_)
 
1764
                        {
 
1765
                    win->canvas()->setLayerFlag(LayerData::F_HULL,on);
 
1766
                        }
 
1767
                        //consensus features
 
1768
                        else if (action == dm_elements_2d_)
 
1769
                        {
 
1770
                                 win->canvas()->setLayerFlag(LayerData::C_ELEMENTS,on);
 
1771
                        }
 
1772
                        // identifications
 
1773
                        else if (action == dm_ident_2d_)
 
1774
                        {
 
1775
                                win->canvas()->setLayerFlag(LayerData::I_PEPTIDEMZ, on);
 
1776
                        }
 
1777
                }
 
1778
  }
 
1779
 
 
1780
  void TOPPViewBase::updateToolBar()
 
1781
  {
 
1782
    SpectrumWidget* w = getActiveSpectrumWidget();
 
1783
 
 
1784
    if (w)
 
1785
    {
 
1786
      //set intensity mode
 
1787
      if(intensity_button_group_->button(w->canvas()->getIntensityMode()))
 
1788
      {
 
1789
        intensity_button_group_->button(w->canvas()->getIntensityMode())->setChecked(true);
 
1790
      } else
 
1791
      {
 
1792
        showLogMessage_(LS_ERROR, __PRETTY_FUNCTION__ ,"Button for intensity mode doesn't exist");
 
1793
      }
 
1794
    }
 
1795
 
 
1796
    // 1D
 
1797
    Spectrum1DWidget* w1 = getActive1DWidget();
 
1798
    if (w1)
 
1799
    {
 
1800
      //draw mode
 
1801
      draw_group_1d_->button(w1->canvas()->getDrawMode())->setChecked(true);
 
1802
 
 
1803
      //show/hide toolbars and buttons
 
1804
      tool_bar_1d_->show();
 
1805
      tool_bar_2d_peak_->hide();
 
1806
      tool_bar_2d_feat_->hide();
 
1807
      tool_bar_2d_cons_->hide();
 
1808
                        tool_bar_2d_ident_->hide();
 
1809
    }
 
1810
 
 
1811
    // 2D
 
1812
    Spectrum2DWidget* w2 = getActive2DWidget();
 
1813
    if (w2)
 
1814
    {
 
1815
      tool_bar_1d_->hide();
 
1816
      // check if there is a layer before requesting data from it
 
1817
      if(w2->canvas()->getLayerCount() > 0)
 
1818
      {
 
1819
        //peak draw modes
 
1820
        if (w2->canvas()->getCurrentLayer().type == LayerData::DT_PEAK)
 
1821
        {
 
1822
          dm_precursors_2d_->setChecked(w2->canvas()->getLayerFlag(LayerData::P_PRECURSORS));
 
1823
          tool_bar_2d_peak_->show();
 
1824
          tool_bar_2d_feat_->hide();
 
1825
          tool_bar_2d_cons_->hide();
 
1826
          tool_bar_2d_ident_->hide();
 
1827
        }
 
1828
        //feature draw modes
 
1829
        else if (w2->canvas()->getCurrentLayer().type == LayerData::DT_FEATURE)
 
1830
        {
 
1831
          dm_hulls_2d_->setChecked(w2->canvas()->getLayerFlag(LayerData::F_HULLS));
 
1832
          dm_hull_2d_->setChecked(w2->canvas()->getLayerFlag(LayerData::F_HULL));
 
1833
          dm_unassigned_2d_->setChecked(w2->canvas()->getLayerFlag(LayerData::F_UNASSIGNED));
 
1834
          dm_label_2d_->setChecked(w2->canvas()->getCurrentLayer().label!=LayerData::L_NONE);
 
1835
          tool_bar_2d_peak_->hide();
 
1836
          tool_bar_2d_feat_->show();
 
1837
          tool_bar_2d_cons_->hide();
 
1838
          tool_bar_2d_ident_->hide();
 
1839
        }
 
1840
        //consensus feature draw modes
 
1841
        else if (w2->canvas()->getCurrentLayer().type == LayerData::DT_CONSENSUS)
 
1842
        {
 
1843
          dm_elements_2d_->setChecked(w2->canvas()->getLayerFlag(LayerData::C_ELEMENTS));
 
1844
          tool_bar_2d_peak_->hide();
 
1845
          tool_bar_2d_feat_->hide();
 
1846
          tool_bar_2d_cons_->show();
 
1847
          tool_bar_2d_ident_->hide();
 
1848
        }
 
1849
        else if (w2->canvas()->getCurrentLayer().type == LayerData::DT_IDENT)
 
1850
        {
 
1851
          dm_ident_2d_->setChecked(w2->canvas()->getLayerFlag(LayerData::I_PEPTIDEMZ));
 
1852
          tool_bar_2d_peak_->hide();
 
1853
          tool_bar_2d_feat_->hide();
 
1854
          tool_bar_2d_cons_->hide();
 
1855
          tool_bar_2d_ident_->show();
 
1856
        }
 
1857
      }
 
1858
    }
 
1859
 
 
1860
    // 3D
 
1861
    Spectrum3DWidget* w3 = getActive3DWidget();
 
1862
    if (w3)
 
1863
    {
 
1864
      //show/hide toolbars and buttons
 
1865
      tool_bar_1d_->hide();
 
1866
      tool_bar_2d_peak_->hide();
 
1867
      tool_bar_2d_feat_->hide();
 
1868
      tool_bar_2d_cons_->hide();
 
1869
                        tool_bar_2d_ident_->hide();
 
1870
    }
 
1871
  }
 
1872
 
 
1873
  void TOPPViewBase::updateLayerBar()
 
1874
  {
 
1875
        //reset
 
1876
                layer_manager_->clear();
 
1877
    SpectrumCanvas* cc = getActiveCanvas();
 
1878
    if (cc == 0) return;
 
1879
 
 
1880
                //determine if this is a 1D view (for text color)
 
1881
                bool is_1d_view = false;
 
1882
                if (dynamic_cast<Spectrum1DCanvas*>(cc)) is_1d_view = true;
 
1883
 
 
1884
                layer_manager_->blockSignals(true);
 
1885
                QListWidgetItem* item = 0;
 
1886
                QString name;
 
1887
    for (Size i = 0; i<cc->getLayerCount(); ++i)
 
1888
    {
 
1889
        const LayerData& layer = cc->getLayer(i);
 
1890
        //add item
 
1891
        item = new QListWidgetItem( layer_manager_ );
 
1892
                        name = layer.name.toQString();
 
1893
                        if (layer.flipped)
 
1894
                        {
 
1895
                                name += " [flipped]";
 
1896
                        }
 
1897
                        item->setText(name);
 
1898
                        if (is_1d_view && cc->getLayerCount()>1)
 
1899
                        {
 
1900
                                QPixmap icon(7,7);
 
1901
                                icon.fill(QColor(layer.param.getValue("peak_color").toQString()));
 
1902
                                item->setIcon(icon);
 
1903
                        }
 
1904
        if (layer.visible)
 
1905
        {
 
1906
                item->setCheckState(Qt::Checked);
 
1907
        }
 
1908
        else
 
1909
        {
 
1910
                item->setCheckState(Qt::Unchecked);
 
1911
        }
 
1912
        if (layer.modified)
 
1913
        {
 
1914
                item->setText(item->text() + '*');
 
1915
        }
 
1916
        //highlight active item
 
1917
        if (i == cc->activeLayerIndex())
 
1918
        {
 
1919
                                layer_manager_->setCurrentItem(item);
 
1920
        }
 
1921
                }
 
1922
                layer_manager_->blockSignals(false);
 
1923
  }
 
1924
 
 
1925
  void TOPPViewBase::updateViewBar()
 
1926
  {
 
1927
    SpectrumCanvas* cc = getActiveCanvas();
 
1928
    int layer_row = layer_manager_->currentRow();
 
1929
 
 
1930
    if (layer_row == -1 || cc == 0)
 
1931
    {
 
1932
      // TODO: we need to clean up the SpectraViewWidget & friends
 
1933
      return;
 
1934
    }
 
1935
 
 
1936
    if (spectra_view_widget_->isVisible())
 
1937
    {
 
1938
      spectra_view_widget_->updateEntries(cc->getCurrentLayer());
 
1939
    }
 
1940
 
 
1941
    if (spectra_identification_view_widget_->isVisible())
 
1942
    {
 
1943
      spectra_identification_view_widget_->attachLayer(&cc->getCurrentLayer());
 
1944
      spectra_identification_view_widget_->updateEntries();
 
1945
    }
 
1946
  }
 
1947
 
 
1948
  void TOPPViewBase::viewChanged(int tab_index)
 
1949
  {
 
1950
    // notify that behavior will be deactivated
 
1951
    view_behavior_->deactivateBehavior();
 
1952
 
 
1953
    // set new behavior
 
1954
    if (views_tabwidget_->tabText(tab_index) == "Scan view")
 
1955
    {
 
1956
      layer_dock_widget_->show();
 
1957
      filter_dock_widget_->show();
 
1958
      view_behavior_ = spectraview_behavior_;
 
1959
    } else if (views_tabwidget_->tabText(tab_index) == "Identification view")
 
1960
    {
 
1961
      layer_dock_widget_->show();
 
1962
      filter_dock_widget_->show();
 
1963
      if (getActive2DWidget())  // currently 2D window is open
 
1964
      {
 
1965
        showSpectrumAs1D(0);
 
1966
      }
 
1967
      view_behavior_ = identificationview_behavior_;
 
1968
    } else if (views_tabwidget_->tabText(tab_index) == "TOPPAS view")
 
1969
    {
 
1970
      layer_dock_widget_->hide();
 
1971
      filter_dock_widget_->hide();
 
1972
      // no complex behavior for TOPPAS view needed
 
1973
    } else
 
1974
    {
 
1975
      cerr << "Error: tab_index " << tab_index << endl;
 
1976
      throw Exception::NotImplemented(__FILE__, __LINE__, __PRETTY_FUNCTION__);
 
1977
    }
 
1978
 
 
1979
    // notify that new behavior has been activated
 
1980
    view_behavior_->activateBehavior();
 
1981
    updateViewBar();
 
1982
  }
 
1983
 
 
1984
  /*
 
1985
  void TOPPViewBase::updateDataBar()
 
1986
  {
 
1987
    const set<String> filenames = getFilenamesOfOpenFiles();
 
1988
    //reset
 
1989
    data_manager_view_->clear();
 
1990
    data_manager_view_->blockSignals(true);
 
1991
    QTreeWidgetItem* item = 0;
 
1992
    for (set<String>::const_iterator it = filenames.begin(); it != filenames.end(); ++it)
 
1993
    {
 
1994
      item = new QTreeWidgetItem(data_manager_view_);
 
1995
      QString name = it->toQString();
 
1996
      QFileInfo fi(name);
 
1997
      item->setText(0, fi.fileName());
 
1998
    }
 
1999
    layer_manager_->blockSignals(false);
 
2000
  }
 
2001
*/
 
2002
        void TOPPViewBase::layerSelectionChange(int i)
 
2003
        {
 
2004
                if (i!=-1)
 
2005
                {
 
2006
      getActiveCanvas()->activateLayer(i);
 
2007
                        updateFilterBar();
 
2008
      updateViewBar();
 
2009
                }
 
2010
        }
 
2011
 
 
2012
        void TOPPViewBase::layerContextMenu(const QPoint & pos)
 
2013
        {
 
2014
                QListWidgetItem* item = layer_manager_->itemAt(pos);
 
2015
                if (item)
 
2016
                {
 
2017
                        QAction* new_action = 0;
 
2018
                        int layer = layer_manager_->row(item);
 
2019
                        QMenu* context_menu = new QMenu(layer_manager_);
 
2020
                        context_menu->addAction("Rename");
 
2021
                        context_menu->addAction("Delete");
 
2022
 
 
2023
      if (getActiveCanvas()->getLayer(layer).flipped)
 
2024
                        {
 
2025
                                new_action = context_menu->addAction("Flip upwards (1D)");
 
2026
                        }
 
2027
                        else
 
2028
                        {
 
2029
                                new_action = context_menu->addAction("Flip downwards (1D)");
 
2030
                        }
 
2031
      if (!getActive1DWidget())
 
2032
                        {
 
2033
                                new_action->setEnabled(false);
 
2034
                        }
 
2035
 
 
2036
                        context_menu->addSeparator();
 
2037
                        context_menu->addAction("Preferences");
 
2038
 
 
2039
                        QAction* selected = context_menu->exec(layer_manager_->mapToGlobal(pos));
 
2040
                        //delete layer
 
2041
                        if (selected!=0 && selected->text()=="Delete")
 
2042
                        {
 
2043
        getActiveCanvas()->removeLayer(layer);
 
2044
                        }
 
2045
                        //rename layer
 
2046
                        else if (selected!=0 && selected->text()=="Rename")
 
2047
                        {
 
2048
                                QString name = QInputDialog::getText(this,"Rename layer","Name:");
 
2049
                                if (name!="")
 
2050
                                {
 
2051
          getActiveCanvas()->setLayerName(layer, name);
 
2052
                                }
 
2053
                        }
 
2054
                        // flip layer up/downwards
 
2055
                        else if (selected != 0 && selected->text() == "Flip downwards (1D)")
 
2056
                        {
 
2057
        getActive1DWidget()->canvas()->flipLayer(layer);
 
2058
        getActive1DWidget()->canvas()->setMirrorModeActive(true);
 
2059
                        }
 
2060
                        else if (selected != 0 && selected->text() == "Flip upwards (1D)")
 
2061
                        {
 
2062
        getActive1DWidget()->canvas()->flipLayer(layer);
 
2063
        bool b = getActive1DWidget()->canvas()->flippedLayersExist();
 
2064
        getActive1DWidget()->canvas()->setMirrorModeActive(b);
 
2065
                        }
 
2066
                        else if (selected != 0 && selected->text() == "Preferences")
 
2067
                        {
 
2068
        getActiveCanvas()->showCurrentLayerPreferences();
 
2069
                        }
 
2070
 
 
2071
                        //Update tab bar and window title
 
2072
      if (getActiveCanvas()->getLayerCount()!=0)
 
2073
                        {
 
2074
        tab_bar_->setTabText(tab_bar_->currentIndex(), getActiveCanvas()->getLayer(0).name.toQString());
 
2075
        getActiveSpectrumWidget()->setWindowTitle(getActiveCanvas()->getLayer(0).name.toQString());
 
2076
                        }
 
2077
                        else
 
2078
                        {
 
2079
                                tab_bar_->setTabText(tab_bar_->currentIndex(),"empty");
 
2080
        getActiveSpectrumWidget()->setWindowTitle("empty");
 
2081
                        }
 
2082
 
 
2083
                        //Update filter bar, spectrum bar and layer bar
 
2084
                        updateLayerBar();
 
2085
      updateViewBar();
 
2086
                        updateFilterBar();
 
2087
                        updateMenu();
 
2088
 
 
2089
                        delete (context_menu);
 
2090
                }
 
2091
        }
 
2092
 
 
2093
        void TOPPViewBase::logContextMenu(const QPoint & pos)
 
2094
        {
 
2095
                QMenu* context_menu = new QMenu(log_);
 
2096
                context_menu->addAction("Clear");
 
2097
 
 
2098
                QAction* selected = context_menu->exec(log_->mapToGlobal(pos));
 
2099
 
 
2100
                //clear text
 
2101
    if (selected != 0 && selected->text()== "Clear")
 
2102
                {
 
2103
                        log_->clear();
 
2104
                }
 
2105
                delete (context_menu);
 
2106
        }
 
2107
 
 
2108
        void TOPPViewBase::filterContextMenu(const QPoint & pos)
 
2109
        {
 
2110
                //do nothing if no window is open
 
2111
    if (getActiveCanvas()==0) return;
 
2112
 
 
2113
    //do nothing if no layer is loaded into the canvas
 
2114
    if (getActiveCanvas()->getLayerCount() == 0) return;
 
2115
 
 
2116
                QMenu* context_menu = new QMenu(filters_);
 
2117
 
 
2118
                //warn if the current layer is not visible
 
2119
    String layer_name = String("Layer: ") + getActiveCanvas()->getCurrentLayer().name;
 
2120
    if (!getActiveCanvas()->getCurrentLayer().visible)
 
2121
                {
 
2122
                        layer_name += " (invisible)";
 
2123
                }
 
2124
                context_menu->addAction(layer_name.toQString())->setEnabled(false);
 
2125
                context_menu->addSeparator();
 
2126
 
 
2127
                //add actions
 
2128
                QListWidgetItem* item = filters_->itemAt(pos);
 
2129
                if (item)
 
2130
                {
 
2131
                        context_menu->addAction("Edit");
 
2132
                        context_menu->addAction("Delete");
 
2133
                }
 
2134
                else
 
2135
                {
 
2136
                        context_menu->addAction("Add filter");
 
2137
                }
 
2138
                //results
 
2139
                QAction* selected = context_menu->exec(filters_->mapToGlobal(pos));
 
2140
                if (selected!=0)
 
2141
                {
 
2142
                        if(selected->text()=="Delete")
 
2143
                        {
 
2144
        DataFilters filters = getActiveCanvas()->getCurrentLayer().filters;
 
2145
                                filters.remove(filters_->row(item));
 
2146
        getActiveCanvas()->setFilters(filters);
 
2147
                                updateFilterBar();
 
2148
                        }
 
2149
                        else if (selected->text()=="Edit")
 
2150
                        {
 
2151
                                filterEdit(item);
 
2152
                        }
 
2153
                        else if (selected->text()=="Add filter")
 
2154
                        {
 
2155
        DataFilters filters = getActiveCanvas()->getCurrentLayer().filters;
 
2156
                                DataFilters::DataFilter filter;
 
2157
                                DataFilterDialog dlg(filter, this);
 
2158
                                if (dlg.exec())
 
2159
                                {
 
2160
                                        filters.add(filter);
 
2161
          getActiveCanvas()->setFilters(filters);
 
2162
                                        updateFilterBar();
 
2163
                                }
 
2164
                        }
 
2165
                }
 
2166
                delete (context_menu);
 
2167
        }
 
2168
 
 
2169
        void TOPPViewBase::filterEdit(QListWidgetItem* item)
 
2170
        {
 
2171
    DataFilters filters = getActiveCanvas()->getCurrentLayer().filters;
 
2172
                DataFilters::DataFilter filter = filters[filters_->row(item)];
 
2173
                DataFilterDialog dlg(filter, this);
 
2174
                if (dlg.exec())
 
2175
                {
 
2176
                        filters.replace(filters_->row(item),filter);
 
2177
      getActiveCanvas()->setFilters(filters);
 
2178
                        updateFilterBar();
 
2179
                }
 
2180
        }
 
2181
 
 
2182
        void TOPPViewBase::layerEdit(QListWidgetItem* /*item*/)
 
2183
        {
 
2184
    getActiveCanvas()->showCurrentLayerPreferences();
 
2185
        }
 
2186
 
 
2187
  void TOPPViewBase::updateFilterBar()
 
2188
  {
 
2189
        //update filters
 
2190
        filters_->clear();
 
2191
 
 
2192
    SpectrumCanvas* canvas = getActiveCanvas();
 
2193
                if (canvas==0) return;
 
2194
                if (canvas->getLayerCount()==0) return;
 
2195
 
 
2196
    const DataFilters& filters = getActiveCanvas()->getCurrentLayer().filters;
 
2197
                for (Size i=0; i<filters.size(); ++i)
 
2198
                {
 
2199
                        QListWidgetItem* item = new QListWidgetItem(filters_);
 
2200
                        item->setText(filters[i].toString().toQString());
 
2201
                }
 
2202
 
 
2203
        //update check box
 
2204
    filters_check_box_->setChecked(getActiveCanvas()->getCurrentLayer().filters.isActive());
 
2205
  }
 
2206
 
 
2207
        void TOPPViewBase::layerFilterVisibilityChange(bool on)
 
2208
        {
 
2209
    if (getActiveCanvas())
 
2210
                {
 
2211
      getActiveCanvas()->changeLayerFilterState(getActiveCanvas()->activeLayerIndex(),on);
 
2212
                }
 
2213
        }
 
2214
 
 
2215
        void TOPPViewBase::layerVisibilityChange(QListWidgetItem* item)
 
2216
        {
 
2217
                int layer;
 
2218
                bool visible;
 
2219
                layer = layer_manager_->row(item);
 
2220
    visible = getActiveCanvas()->getLayer(layer).visible;
 
2221
 
 
2222
                if (item->checkState()==Qt::Unchecked && visible)
 
2223
                {
 
2224
      getActiveCanvas()->changeVisibility(layer, false);
 
2225
                }
 
2226
                else if (item->checkState()==Qt::Checked && !visible)
 
2227
                {
 
2228
      getActiveCanvas()->changeVisibility(layer, true);
 
2229
                }
 
2230
        }
 
2231
 
 
2232
  void TOPPViewBase::updateTabBar(QWidget* w)
 
2233
  {
 
2234
        if (w)
 
2235
        {
 
2236
      EnhancedTabBarWidgetInterface* tbw = dynamic_cast<EnhancedTabBarWidgetInterface*>(w);
 
2237
      Int window_id = tbw->getWindowId();
 
2238
                tab_bar_->setCurrentId(window_id);
 
2239
        }
 
2240
  }
 
2241
 
 
2242
  void TOPPViewBase::tileVertical()
 
2243
  {
 
2244
    // primitive horizontal tiling
 
2245
    QWidgetList windows = ws_->windowList();
 
2246
    if ( !windows.count() ) return;
 
2247
 
 
2248
    if (getActive1DWidget()) getActive1DWidget()->showNormal();
 
2249
    if (getActive2DWidget()) getActive2DWidget()->showNormal();
 
2250
 
 
2251
    int heightForEach = ws_->height() / windows.count();
 
2252
    int y = 0;
 
2253
    for ( int i = 0; i < int(windows.count()); ++i )
 
2254
    {
 
2255
      QWidget *window = windows.at(i);
 
2256
      if ( window->isMaximized() || window->isFullScreen() )
 
2257
      {
 
2258
        // prevent flicker
 
2259
        window->hide();
 
2260
        window->setWindowState(Qt::WindowNoState);
 
2261
        window->show();
 
2262
      }
 
2263
      int preferredHeight = window->minimumHeight()+window->parentWidget()->baseSize().height();
 
2264
      int actHeight = std::max(heightForEach, preferredHeight);
 
2265
 
 
2266
      window->parentWidget()->setGeometry( 0, y, ws_->width(), actHeight );
 
2267
      y += actHeight;
 
2268
    }
 
2269
  }
 
2270
 
 
2271
  void TOPPViewBase::tileHorizontal()
 
2272
  {
 
2273
    // primitive horizontal tiling
 
2274
    QWidgetList windows = ws_->windowList();
 
2275
    if ( !windows.count() ) return;
 
2276
 
 
2277
    if (getActive1DWidget()) getActive1DWidget()->showNormal();
 
2278
    if (getActive2DWidget()) getActive2DWidget()->showNormal();
 
2279
 
 
2280
    int widthForEach = ws_->width() / windows.count();
 
2281
    int y = 0;
 
2282
    for ( int i = 0; i < int(windows.count()); ++i )
 
2283
    {
 
2284
      QWidget *window = windows.at(i);
 
2285
      if ( window->windowState() & Qt::WindowMaximized )
 
2286
      {
 
2287
        // prevent flicker
 
2288
        window->hide();
 
2289
        window->showNormal();
 
2290
      }
 
2291
      int preferredWidth = window->minimumWidth()+window->parentWidget()->baseSize().width();
 
2292
 
 
2293
      int actWidth = std::max(widthForEach, preferredWidth);
 
2294
 
 
2295
      window->parentWidget()->setGeometry( y, 0, actWidth , ws_->height() );
 
2296
      y += actWidth;
 
2297
    }
 
2298
  }
 
2299
 
 
2300
  void TOPPViewBase::layerActivated()
 
2301
  {
 
2302
    updateToolBar();
 
2303
    updateViewBar();
 
2304
    updateCurrentPath();
 
2305
  }
 
2306
 
 
2307
  void TOPPViewBase::layerDeactivated()
 
2308
  {
 
2309
 
 
2310
  }
 
2311
 
 
2312
  void TOPPViewBase::showSpectrumWidgetInWindow(SpectrumWidget* sw, const String& caption)
 
2313
  {
 
2314
        ws_->addWindow(sw);
 
2315
    connect(sw->canvas(),SIGNAL(preferencesChange()),this,SLOT(updateLayerBar()));
 
2316
    connect(sw->canvas(),SIGNAL(layerActivated(QWidget*)),this,SLOT(layerActivated()));
 
2317
    connect(sw->canvas(),SIGNAL(layerModficationChange(Size,bool)),this,SLOT(updateLayerBar()));
 
2318
    connect(sw,SIGNAL(sendStatusMessage(std::string,OpenMS::UInt)),this,SLOT(showStatusMessage(std::string,OpenMS::UInt)));
 
2319
    connect(sw,SIGNAL(sendCursorStatus(double,double)),this,SLOT(showCursorStatus(double,double)));
 
2320
    connect(sw,SIGNAL(dropReceived(const QMimeData*,QWidget*,int)),this,SLOT(copyLayer(const QMimeData*,QWidget*,int)));
 
2321
 
 
2322
    // 1D spectrum specific signals
 
2323
    Spectrum1DWidget* sw1 = qobject_cast<Spectrum1DWidget*>(sw);
 
2324
    if (sw1 != 0)
 
2325
    {
 
2326
      connect(sw1, SIGNAL(showCurrentPeaksAs2D()), this, SLOT(showCurrentPeaksAs2D()));
 
2327
      connect(sw1, SIGNAL(showCurrentPeaksAs3D()), this, SLOT(showCurrentPeaksAs3D()));
 
2328
    }
 
2329
 
 
2330
    // 2D spectrum specific signals
 
2331
        Spectrum2DWidget* sw2 = qobject_cast<Spectrum2DWidget*>(sw);
 
2332
        if (sw2 != 0)
 
2333
        {
 
2334
                connect(sw2->getHorizontalProjection(),SIGNAL(sendCursorStatus(double,double)),this,SLOT(showCursorStatus(double,double)));
 
2335
                connect(sw2->getVerticalProjection(),SIGNAL(sendCursorStatus(double,double)),this,SLOT(showCursorStatusInvert(double,double)));
 
2336
      connect(sw2, SIGNAL(showSpectrumAs1D(int)), this, SLOT(showSpectrumAs1D(int)));
 
2337
      connect(sw2, SIGNAL(showCurrentPeaksAs3D()), this, SLOT(showCurrentPeaksAs3D()));
 
2338
        }
 
2339
 
 
2340
    // 3D spectrum specific signals
 
2341
    Spectrum3DWidget* sw3 = qobject_cast<Spectrum3DWidget*>(sw);
 
2342
    if (sw3 != 0)
 
2343
    {
 
2344
      connect(sw3, SIGNAL(showCurrentPeaksAs2D()), this, SLOT(showCurrentPeaksAs2D()));
 
2345
    }
 
2346
 
 
2347
          sw->setWindowTitle(caption.toQString());
 
2348
 
 
2349
                //add tab with id
 
2350
        static int window_counter = 4711;
 
2351
 
 
2352
    sw->setWindowId(window_counter++);
 
2353
 
 
2354
    tab_bar_->addTab(caption.toQString(), sw->getWindowId());
 
2355
 
 
2356
    //connect slots and sigals for removing the widget from the bar, when it is closed
 
2357
    //- through the menu entry
 
2358
    //- through the tab bar
 
2359
    //- thourgh the MDI close button
 
2360
    connect(sw,SIGNAL(aboutToBeDestroyed(int)),tab_bar_,SLOT(removeId(int)));
 
2361
 
 
2362
    tab_bar_->setCurrentId(sw->getWindowId());
 
2363
 
 
2364
                //show first window maximized (only visible windows are in the list)
 
2365
                if (ws_->windowList().count()==0)
 
2366
                {
 
2367
                        sw->showMaximized();
 
2368
                }
 
2369
                else
 
2370
                {
 
2371
                        sw->show();
 
2372
                }
 
2373
    enhancedWorkspaceWindowChanged(sw->getWindowId());
 
2374
  }
 
2375
 
 
2376
  void TOPPViewBase::showGoToDialog()
 
2377
  {
 
2378
    SpectrumWidget* w = getActiveSpectrumWidget();
 
2379
    if (w)
 
2380
    {
 
2381
      getActiveSpectrumWidget()->showGoToDialog();
 
2382
    }
 
2383
  }
 
2384
 
 
2385
  void TOPPViewBase::activate1DSpectrum(int index)
 
2386
  {
 
2387
    Spectrum1DWidget* w = getActive1DWidget();
 
2388
    if (w)
 
2389
    {
 
2390
      view_behavior_->activate1DSpectrum(index);
 
2391
    }
 
2392
  }
 
2393
 
 
2394
  void TOPPViewBase::deactivate1DSpectrum(int index)
 
2395
  {
 
2396
    Spectrum1DWidget* w = getActive1DWidget();
 
2397
    if (w)
 
2398
    {
 
2399
      view_behavior_->deactivate1DSpectrum(index);
 
2400
    }
 
2401
  }
 
2402
 
 
2403
  EnhancedWorkspace* TOPPViewBase::getWorkspace() const
 
2404
  {
 
2405
    return ws_;
 
2406
  }
 
2407
 
 
2408
  SpectrumWidget* TOPPViewBase::getActiveSpectrumWidget() const
 
2409
  {
 
2410
    if (!ws_->activeWindow())
 
2411
    {
 
2412
      return 0;
 
2413
    }
 
2414
    return qobject_cast<SpectrumWidget*>(ws_->activeWindow());
 
2415
  }
 
2416
 
 
2417
  SpectrumCanvas*  TOPPViewBase::getActiveCanvas() const
 
2418
  {
 
2419
    SpectrumWidget* sw = qobject_cast<SpectrumWidget*>(ws_->activeWindow());
 
2420
    if (sw == 0)
 
2421
    {
 
2422
        return 0;
 
2423
    }
 
2424
    return sw->canvas();
 
2425
  }
 
2426
 
 
2427
 
 
2428
  TOPPASWidget* TOPPViewBase::getActiveTOPPASWidget() const
 
2429
  {
 
2430
    if (!ws_->activeWindow())
 
2431
    {
 
2432
      return 0;
 
2433
    }
 
2434
    return qobject_cast<TOPPASWidget*>(ws_->activeWindow());
 
2435
  }
 
2436
 
 
2437
  Spectrum1DWidget* TOPPViewBase::getActive1DWidget() const
 
2438
  {
 
2439
    Spectrum1DWidget* w = qobject_cast<Spectrum1DWidget*>(getActiveSpectrumWidget());
 
2440
    if (!w)
 
2441
    {
 
2442
      return 0;
 
2443
    }
 
2444
                return w;
 
2445
  }
 
2446
 
 
2447
  Spectrum2DWidget* TOPPViewBase::getActive2DWidget() const
 
2448
  {
 
2449
    Spectrum2DWidget* w = qobject_cast<Spectrum2DWidget*>(getActiveSpectrumWidget());
 
2450
    if (!w)
 
2451
    {
 
2452
      return 0;
 
2453
    }
 
2454
                return w;
 
2455
  }
 
2456
 
 
2457
  Spectrum3DWidget* TOPPViewBase::getActive3DWidget() const
 
2458
  {
 
2459
    Spectrum3DWidget* w = qobject_cast<Spectrum3DWidget*>(getActiveSpectrumWidget());
 
2460
    if (!w)
 
2461
    {
 
2462
      return 0;
 
2463
    }
 
2464
                return w;
 
2465
  }
 
2466
 
 
2467
  void TOPPViewBase::loadPreferences(String filename)
 
2468
  {
 
2469
    // compose default ini file path
 
2470
    String default_ini_file = String(QDir::homePath()) + "/.TOPPView.ini";
 
2471
 
 
2472
    if (filename == "")
 
2473
    {
 
2474
      filename = default_ini_file;
 
2475
    }
 
2476
 
 
2477
    // load preferences, if file exists
 
2478
    if (File::exists(filename))
 
2479
    {
 
2480
        bool error = false;
 
2481
        Param tmp;
 
2482
      try
 
2483
      { // the file might be corrupt
 
2484
          tmp.load(filename);
 
2485
      }
 
2486
      catch (...)
 
2487
      {
 
2488
        error = true;
 
2489
      }
 
2490
 
 
2491
      //apply preferences if they are of the current TOPPView version
 
2492
      if(!error && tmp.exists("preferences:version") &&
 
2493
          tmp.getValue("preferences:version").toString() == VersionInfo::getVersion())
 
2494
        {
 
2495
                try
 
2496
                {
 
2497
                setParameters(tmp);
 
2498
                }
 
2499
                catch (Exception::InvalidParameter& /*e*/)
 
2500
                {
 
2501
                        error = true;
 
2502
                }
 
2503
        }
 
2504
        else
 
2505
        {
 
2506
                                error = true;
 
2507
        }
 
2508
 
 
2509
                        //set parameters to defaults when something is fishy with the parameters file
 
2510
                        if (error)
 
2511
                        {
 
2512
                        //reset parameters (they will be stored again when TOPPView quits)
 
2513
                        setParameters(Param());
 
2514
 
 
2515
                                cerr << "The TOPPView preferences files '" << filename << "' was ignored. It is no longer compatible with this TOPPView version and will be replaced." << endl;
 
2516
                        }
 
2517
    }
 
2518
    else if (filename != default_ini_file)
 
2519
    {
 
2520
        cerr << "Unable to load INI File: '" << filename << "'" << endl;
 
2521
    }
 
2522
    param_.setValue("PreferencesFile" , filename);
 
2523
 
 
2524
    //set the recent files
 
2525
    Param p = param_.copy("preferences:RecentFiles");
 
2526
    if (p.size()!=0)
 
2527
    {
 
2528
      for (Param::ParamIterator it=p.begin() ; it!=p.end() ; ++it)
 
2529
      {
 
2530
        QString filename = it->value.toQString();
 
2531
        if (File::exists(filename)) recent_files_.append(filename);
 
2532
      }
 
2533
    }
 
2534
 
 
2535
    updateRecentMenu_();
 
2536
  }
 
2537
 
 
2538
  void TOPPViewBase::savePreferences()
 
2539
  {
 
2540
    // replace recent files
 
2541
    param_.removeAll("preferences:RecentFiles");
 
2542
 
 
2543
    for (int i = 0; i < recent_files_.size(); ++i)
 
2544
    {
 
2545
      param_.setValue("preferences:RecentFiles:"+String(i),recent_files_[i]);
 
2546
    }
 
2547
 
 
2548
                //set version
 
2549
                param_.setValue("preferences:version",VersionInfo::getVersion());
 
2550
 
 
2551
    //save only the subsection that begins with "preferences:"
 
2552
    try
 
2553
    {
 
2554
      param_.copy("preferences:").store(string(param_.getValue("PreferencesFile")));
 
2555
    }
 
2556
    catch(Exception::UnableToCreateFile& /*e*/)
 
2557
    {
 
2558
      cerr << "Unable to create INI File: '" << string(param_.getValue("PreferencesFile")) << "'" << endl;
 
2559
    }
 
2560
  }
 
2561
 
 
2562
  void TOPPViewBase::openRecentFile()
 
2563
  {
 
2564
                QAction* action = qobject_cast<QAction *>(sender());
 
2565
    if (action)
 
2566
                {
 
2567
      QString filename = action->text();
 
2568
      if (filename.endsWith(".toppas", Qt::CaseInsensitive))
 
2569
      {
 
2570
        addTOPPASFile(filename, true);
 
2571
      }
 
2572
      else
 
2573
      {
 
2574
        addDataFile(filename, true, true);
 
2575
      }
 
2576
    }
 
2577
        }
 
2578
 
 
2579
  QStringList TOPPViewBase::getFileList_(const String& path_overwrite)
 
2580
  {
 
2581
    String filter_all = "readable files (*.mzML *.mzXML *.mzData *.featureXML *.consensusXML *.idXML *.dta *.dta2d fid *.bz2 *.gz *.toppas);;";
 
2582
    String filter_single = "mzML files (*.mzML);;mzXML files (*.mzXML);;mzData files (*.mzData);;feature map (*.featureXML);;consensus feature map (*.consensusXML);;peptide identifications (*.idXML);;XML files (*.xml);;XMass Analysis (fid);;dta files (*.dta);;dta2d files (*.dta2d);;bzipped files (*.bz2);;gzipped files (*.gz);;TOPPAS files (*.toppas);;all files (*)";
 
2583
 
 
2584
                QString open_path = current_path_.toQString();
 
2585
                if (path_overwrite!="")
 
2586
                {
 
2587
      open_path = path_overwrite.toQString();
 
2588
                }
 
2589
    // we use the QT file dialog instead of using QFileDialog::Names(...)
 
2590
                // On Windows and Mac OS X, this static function will use the native file dialog and not a QFileDialog,
 
2591
                // which prevents us from doing GUI testing on it.
 
2592
    QFileDialog dialog(this, "Open file(s)", open_path, (filter_all + filter_single).toQString());
 
2593
                dialog.setFileMode(QFileDialog::ExistingFiles);
 
2594
                QStringList file_names;
 
2595
 
 
2596
    if (dialog.exec())
 
2597
    {
 
2598
      file_names = dialog.selectedFiles();
 
2599
    }
 
2600
 
 
2601
                return file_names;
 
2602
  }
 
2603
 
 
2604
  void TOPPViewBase::openFileDialog()
 
2605
  {
 
2606
                QStringList files = getFileList_();
 
2607
    for(QStringList::iterator it = files.begin(); it!=files.end(); ++it)
 
2608
                {
 
2609
      QString filename = *it;
 
2610
      if (filename.endsWith(".toppas", Qt::CaseInsensitive))
 
2611
      {
 
2612
        addTOPPASFile(filename, true);
 
2613
      }
 
2614
      else
 
2615
      {
 
2616
        addDataFile(filename, true, true);
 
2617
      }
 
2618
                }
 
2619
  }
 
2620
 
 
2621
  void TOPPViewBase::addTOPPASFile(const String& file_name, bool in_new_window)
 
2622
  {
 
2623
    TOPPASScene* scene = 0;
 
2624
    if (in_new_window) // open in new window
 
2625
    {
 
2626
      // create TOPPASWidget, load data and open in new window
 
2627
      TOPPASWidget* tw = new TOPPASWidget(Param(), ws_, toppas_tmp_path_);
 
2628
      showTOPPipelineInWindow_(tw, File::basename(file_name));
 
2629
      scene = tw->getScene();
 
2630
      scene->load(file_name);
 
2631
      addRecentFile_(file_name);
 
2632
    }
 
2633
    else  // merge into existing scene
 
2634
    {
 
2635
      TOPPASWidget* tw = getActiveTOPPASWidget();
 
2636
      if (!tw)
 
2637
      {
 
2638
        return;
 
2639
      }
 
2640
      // create TOPPASWidget, load data into temporary scene and include into existing one
 
2641
      TOPPASScene* tmp_scene = new TOPPASScene(0, File::getTempDirectory().toQString()+QDir::separator(), false);
 
2642
      tmp_scene->load(file_name);
 
2643
      scene = tw->getScene();
 
2644
      scene->include(tmp_scene);
 
2645
      delete tmp_scene;
 
2646
    }
 
2647
 
 
2648
    if (in_new_window)
 
2649
    {
 
2650
      // connect scene signals only if we created a new window (otherwise they already exist)
 
2651
      connect(scene, SIGNAL(saveMe()), this, SLOT(savePipeline()));
 
2652
      connect(scene, SIGNAL(selectionCopied(TOPPASScene*)), this, SLOT(saveToClipboard(TOPPASScene*)));
 
2653
      connect(scene, SIGNAL(requestClipboardContent()), this, SLOT(sendClipboardContent()));
 
2654
      connect(scene, SIGNAL(mainWindowNeedsUpdate()), this, SLOT(updateMenu()));
 
2655
      connect(scene, SIGNAL(openInTOPPView(QStringList)), this, SLOT(openFilesInTOPPView(QStringList)));
 
2656
    }
 
2657
 
 
2658
    //connect vertex signals/slots for log messages
 
2659
    for (TOPPASScene::VertexIterator it = scene->verticesBegin(); it != scene->verticesEnd(); ++it)
 
2660
    {
 
2661
      TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(*it);
 
2662
      if (tv)
 
2663
      {
 
2664
        connect(tv, SIGNAL(toolStarted()), this, SLOT(toolStarted()));
 
2665
        connect(tv, SIGNAL(toolFinished()), this, SLOT(toolFinished()));
 
2666
        connect(tv, SIGNAL(toolCrashed()), this, SLOT(toolCrashed()));
 
2667
        connect(tv, SIGNAL(toolFailed()), this, SLOT(toolFailed()));
 
2668
        connect(tv, SIGNAL(toppOutputReady(const QString&)), this, SLOT(updateTOPPOutputLog(const QString&)));
 
2669
        continue;
 
2670
      }
 
2671
      TOPPASOutputFileListVertex* oflv = qobject_cast<TOPPASOutputFileListVertex*>(*it);
 
2672
      if (oflv)
 
2673
      {
 
2674
        connect (oflv, SIGNAL(outputFileWritten(const String&)), this, SLOT(outputVertexFinished(const String&)));
 
2675
        continue;
 
2676
      }
 
2677
    }
 
2678
  }
 
2679
 
 
2680
  void TOPPViewBase::showTOPPipelineInWindow_(TOPPASWidget* tw, const String& caption)
 
2681
  {
 
2682
    ws_->addWindow(tw);
 
2683
 
 
2684
    connect(tw,SIGNAL(sendStatusMessage(std::string,OpenMS::UInt)),this,SLOT(showStatusMessage(std::string,OpenMS::UInt)));
 
2685
    connect(tw,SIGNAL(sendCursorStatus(double,double)),this,SLOT(showCursorStatus(double,double)));
 
2686
    connect(tw,SIGNAL(toolDroppedOnWidget(double,double)),this,SLOT(insertNewVertex_(double,double)));
 
2687
    connect(tw,SIGNAL(pipelineDroppedOnWidget(const String&, bool)),this,SLOT(addTOPPASFile(const String&, bool)));
 
2688
 
 
2689
    tw->setWindowTitle(caption.toQString());
 
2690
 
 
2691
    //add tab with id
 
2692
    static int window_counter = 1337;
 
2693
    tw->setWindowId(window_counter);
 
2694
    window_counter++;
 
2695
 
 
2696
    //connect slots and signals for removing the widget from the bar, when it is closed
 
2697
    //- through the menu entry
 
2698
    //- through the tab bar
 
2699
    //- through the MDI close button
 
2700
    connect(tw, SIGNAL(aboutToBeDestroyed(int)),tab_bar_,SLOT(removeId(int)));
 
2701
 
 
2702
    //show first window maximized (only visible windows are in the list)
 
2703
    if (ws_->windowList().count()==0)
 
2704
    {
 
2705
      tw->showMaximized();
 
2706
    }
 
2707
    else
 
2708
    {
 
2709
      tw->show();
 
2710
    }
 
2711
    TOPPASScene* ts = tw->getScene();
 
2712
 
 
2713
    connect (ts, SIGNAL(entirePipelineFinished()), this, SLOT(showPipelineFinishedLogMessage()));
 
2714
    connect (ts, SIGNAL(entirePipelineFinished()), this, SLOT(updateMenu()));
 
2715
    connect (ts, SIGNAL(pipelineExecutionFailed()), this, SLOT(updateMenu()));
 
2716
 
 
2717
    ts->setSceneRect((tw->mapToScene(tw->rect())).boundingRect());
 
2718
 
 
2719
    tab_bar_->addTab(caption.toQString(), tw->getWindowId());
 
2720
    tab_bar_->setCurrentId(tw->getWindowId());
 
2721
    enhancedWorkspaceWindowChanged(tw->getWindowId());
 
2722
  }
 
2723
 
 
2724
  void TOPPViewBase::insertNewVertex_(double x, double y, QTreeWidgetItem* item)
 
2725
  {
 
2726
    // get toppas tree view from tab widget 2
 
2727
    TOPPASTreeView* toppas_tree_view = qobject_cast<TOPPASTreeView*>(views_tabwidget_->widget(2));
 
2728
 
 
2729
    if (!getActiveTOPPASWidget() || !getActiveTOPPASWidget()->getScene() || !toppas_tree_view)
 
2730
    {
 
2731
      return;
 
2732
    }
 
2733
 
 
2734
    TOPPASScene* scene = getActiveTOPPASWidget()->getScene();
 
2735
    QTreeWidgetItem* current_tool = item ? item : toppas_tree_view->currentItem();
 
2736
    String tool_name = String(current_tool->text(0));
 
2737
    TOPPASVertex* tv = 0;
 
2738
 
 
2739
    if (tool_name == "<Input files>")
 
2740
    {
 
2741
      tv = new TOPPASInputFileListVertex();
 
2742
    }
 
2743
    else if (tool_name == "<Output files>")
 
2744
    {
 
2745
      tv = new TOPPASOutputFileListVertex();
 
2746
      TOPPASOutputFileListVertex* oflv = qobject_cast<TOPPASOutputFileListVertex*>(tv);
 
2747
      connect (oflv, SIGNAL(outputFileWritten(const String&)), this, SLOT(outputVertexFinished(const String&)));
 
2748
      scene->connectOutputVertexSignals(oflv);
 
2749
    }
 
2750
    else if (tool_name == "<Merger>")
 
2751
    {
 
2752
      tv = new TOPPASMergerVertex(true);
 
2753
    }
 
2754
    else if (tool_name == "<Collector>")
 
2755
    {
 
2756
      tv = new TOPPASMergerVertex(false);
 
2757
    }
 
2758
    else // node is a TOPP tool
 
2759
    {
 
2760
      if (current_tool->childCount() > 0)
 
2761
      {
 
2762
        // category or tool name with types is selected (instead of a concrete type)
 
2763
        return;
 
2764
      }
 
2765
      String tool_type;
 
2766
      if (current_tool->parent() != 0 && current_tool->parent()->parent() != 0)
 
2767
      {
 
2768
        // selected item is a type
 
2769
        tool_type = String(current_tool->text(0));
 
2770
        tool_name = String(current_tool->parent()->text(0));
 
2771
      }
 
2772
      else
 
2773
      {
 
2774
        // normal tool which does not have type selected
 
2775
        tool_name = String(current_tool->text(0));
 
2776
        tool_type = "";
 
2777
      }
 
2778
 
 
2779
      tv = new TOPPASToolVertex(tool_name, tool_type);
 
2780
      TOPPASToolVertex* ttv = qobject_cast<TOPPASToolVertex*>(tv);
 
2781
      connect (ttv, SIGNAL(toolStarted()), this, SLOT(toolStarted()));
 
2782
      connect (ttv, SIGNAL(toolFinished()), this, SLOT(toolFinished()));
 
2783
      connect (ttv, SIGNAL(toolCrashed()), this, SLOT(toolCrashed()));
 
2784
      connect (ttv, SIGNAL(toolFailed()), this, SLOT(toolFailed()));
 
2785
      connect (ttv, SIGNAL(toppOutputReady(const QString&)), this, SLOT(updateTOPPOutputLog(const QString&)));
 
2786
 
 
2787
      scene->connectToolVertexSignals(ttv);
 
2788
    }
 
2789
 
 
2790
    scene->connectVertexSignals(tv);
 
2791
    scene->addVertex(tv);
 
2792
    tv->setPos(x,y);
 
2793
    tv->setZValue(toppas_z_value_);
 
2794
    toppas_z_value_ += 0.000001;
 
2795
    scene->topoSort();
 
2796
    scene->setChanged(true);
 
2797
  }
 
2798
 
 
2799
  void TOPPViewBase::insertNewVertexInCenter_(QTreeWidgetItem* item)
 
2800
  {
 
2801
    TOPPASTreeView* toppas_tree_view = qobject_cast<TOPPASTreeView*>(views_tabwidget_->widget(2));
 
2802
 
 
2803
    if (!getActiveTOPPASWidget() || !getActiveTOPPASWidget()->getScene() || !toppas_tree_view || !toppas_tree_view->currentItem())
 
2804
    {
 
2805
      return;
 
2806
    }
 
2807
 
 
2808
    QPointF insert_pos = getActiveTOPPASWidget()->mapToScene(QPoint((getActiveTOPPASWidget()->width()/2.0)+(qreal)(5*toppas_node_offset_),(getActiveTOPPASWidget()->height()/2.0)+(qreal)(5*toppas_node_offset_)));
 
2809
    insertNewVertex_(insert_pos.x(), insert_pos.y(), item);
 
2810
    toppas_node_offset_ = (toppas_node_offset_+1) % 10;
 
2811
  }
 
2812
 
 
2813
  void TOPPViewBase::openExampleDialog()
 
2814
  {
 
2815
                QStringList files = getFileList_(File::getOpenMSDataPath() + "/examples/");
 
2816
 
 
2817
    for(QStringList::iterator it = files.begin(); it != files.end(); ++it)
 
2818
                {
 
2819
      QString filename = *it;
 
2820
      if (filename.endsWith(".toppas", Qt::CaseInsensitive))
 
2821
      {
 
2822
        addTOPPASFile(filename, true);
 
2823
      }
 
2824
      else
 
2825
      {
 
2826
        addDataFile(filename, true, true);
 
2827
      }
 
2828
                }
 
2829
  }
 
2830
 
 
2831
        void TOPPViewBase::connectToDB_(DBConnection& db)
 
2832
        {
 
2833
                //get the password if unset
 
2834
                if (!param_.exists("DBPassword"))
 
2835
                {
 
2836
                        stringstream ss;
 
2837
                        ss << "Enter password for user '" << (String)param_.getValue("preferences:db:login") << "' at '"<< (String)param_.getValue("preferences:db:host")<<":"<<(String)param_.getValue("preferences:db:port")<<"' : ";
 
2838
                        bool ok;
 
2839
                        QString text = QInputDialog::getText(this, "TOPPView database password", ss.str().c_str(), QLineEdit::Password,QString::null, &ok);
 
2840
                        if ( ok )
 
2841
                        {
 
2842
                                param_.setValue("DBPassword",text);
 
2843
                        }
 
2844
                }
 
2845
 
 
2846
                if (param_.exists("DBPassword"))
 
2847
                {
 
2848
                        try
 
2849
                        {
 
2850
                                db.connect((String)param_.getValue("preferences:db:name"), (String)param_.getValue("preferences:db:login"),(String)param_.getValue("DBPassword"),(String)param_.getValue("preferences:db:host"),(UInt)param_.getValue("preferences:db:port"));
 
2851
                        }
 
2852
                        catch (DBConnection::InvalidQuery& er)
 
2853
                        {
 
2854
                                param_.remove("DBPassword");
 
2855
                                showLogMessage_(LS_ERROR,"Unable to log in to the database server",String("Check the login data in the preferences!\nDatabase error message: ") + er.what());
 
2856
                        }
 
2857
                }
 
2858
        }
 
2859
 
 
2860
  void TOPPViewBase::openDatabaseDialog()
 
2861
  {
 
2862
                DBConnection db;
 
2863
                connectToDB_(db);
 
2864
                if (db.isConnected())
 
2865
                {
 
2866
                        vector<UInt> result;
 
2867
                        DBOpenDialog db_dialog(db,result,this);
 
2868
                        if (db_dialog.exec())
 
2869
                        {
 
2870
                                db.disconnect();
 
2871
                                for (vector<UInt>::iterator it = result.begin();it!=result.end();++it)
 
2872
                                {
 
2873
          addDataDB(*it, true);
 
2874
                                }
 
2875
                        }
 
2876
                }
 
2877
  }
 
2878
 
 
2879
        void TOPPViewBase::rerunTOPPTool()
 
2880
        {
 
2881
                //warn if hidden layer => wrong layer selected...
 
2882
    const LayerData& layer = getActiveCanvas()->getCurrentLayer();
 
2883
                if (!layer.visible)
 
2884
                {
 
2885
                showLogMessage_(LS_NOTICE,"The current layer is not visible","Have you selected the right layer for this action?");
 
2886
                }
 
2887
 
 
2888
                //delete old input and output file
 
2889
                File::remove(topp_.file_name + "_in");
 
2890
                File::remove(topp_.file_name + "_out");
 
2891
 
 
2892
                //run the tool
 
2893
                runTOPPTool_();
 
2894
        }
 
2895
 
 
2896
        void TOPPViewBase::showTOPPDialog()
 
2897
        {
 
2898
                QAction* action = qobject_cast<QAction*>(sender());
 
2899
                showTOPPDialog_(action->data().toBool());
 
2900
        }
 
2901
 
 
2902
        void TOPPViewBase::showTOPPDialog_(bool visible)
 
2903
        {
 
2904
                //warn if hidden layer => wrong layer selected...
 
2905
    const LayerData& layer = getActiveCanvas()->getCurrentLayer();
 
2906
                if (!layer.visible)
 
2907
                {
 
2908
                showLogMessage_(LS_NOTICE,"The current layer is not visible","Have you selected the right layer for this action?");
 
2909
                }
 
2910
 
 
2911
                //create and store unique file name prefix for files
 
2912
                topp_.file_name = param_.getValue("preferences:tmp_file_path").toString() + "/TOPPView_" + File::getUniqueName();
 
2913
                if (!File::writable(topp_.file_name+"_ini"))
 
2914
                {
 
2915
                        showLogMessage_(LS_ERROR,"Cannot create temporary file",String("Cannot write to '")+topp_.file_name+"'_ini!");
 
2916
                        return;
 
2917
                }
 
2918
                ToolsDialog tools_dialog(this,topp_.file_name+"_ini",current_path_,getCurrentLayer()->type);
 
2919
 
 
2920
                if(tools_dialog.exec()==QDialog::Accepted)
 
2921
                {
 
2922
                        //Store tool name, input parameter and output parameter
 
2923
                        topp_.tool = tools_dialog.getTool();
 
2924
                        topp_.in = tools_dialog.getInput();
 
2925
                        topp_.out = tools_dialog.getOutput();
 
2926
                        topp_.visible = visible;
 
2927
                        //run the tool
 
2928
                        runTOPPTool_();
 
2929
                }
 
2930
        }
 
2931
 
 
2932
        void TOPPViewBase::runTOPPTool_()
 
2933
        {
 
2934
    const LayerData& layer = getActiveCanvas()->getCurrentLayer();
 
2935
 
 
2936
                //test if files are writable
 
2937
                if (!File::writable(topp_.file_name+"_in"))
 
2938
                {
 
2939
                        showLogMessage_(LS_ERROR,"Cannot create temporary file",String("Cannot write to '")+topp_.file_name+"_in'!");
 
2940
                        return;
 
2941
                }
 
2942
                if (!File::writable(topp_.file_name+"_out"))
 
2943
                {
 
2944
                        showLogMessage_(LS_ERROR,"Cannot create temporary file",String("Cannot write to '")+topp_.file_name+"'_out!");
 
2945
                        return;
 
2946
                }
 
2947
 
 
2948
                //Store data
 
2949
                topp_.layer_name = layer.name;
 
2950
    topp_.window_id = getActiveSpectrumWidget()->getWindowId();
 
2951
    topp_.spectrum_id = layer.getCurrentSpectrumIndex();
 
2952
                if (layer.type==LayerData::DT_PEAK)
 
2953
                {
 
2954
                        MzMLFile f;
 
2955
                        f.setLogType(ProgressLogger::GUI);
 
2956
                        if (topp_.visible)
 
2957
                        {
 
2958
                                ExperimentType exp;
 
2959
        getActiveCanvas()->getVisiblePeakData(exp);
 
2960
                                f.store(topp_.file_name+"_in",exp);
 
2961
                        }
 
2962
                        else
 
2963
                        {
 
2964
        f.store(topp_.file_name+"_in",*layer.getPeakData());
 
2965
                        }
 
2966
                }
 
2967
                else if (layer.type==LayerData::DT_FEATURE)
 
2968
                {
 
2969
                        if (topp_.visible)
 
2970
                        {
 
2971
                                FeatureMapType map;
 
2972
        getActiveCanvas()->getVisibleFeatureData(map);
 
2973
                                FeatureXMLFile().store(topp_.file_name+"_in",map);
 
2974
                        }
 
2975
                        else
 
2976
                        {
 
2977
        FeatureXMLFile().store(topp_.file_name+"_in",*layer.getFeatureMap());
 
2978
                        }
 
2979
                }
 
2980
                else
 
2981
                {
 
2982
                        if (topp_.visible)
 
2983
                        {
 
2984
                                ConsensusMapType map;
 
2985
        getActiveCanvas()->getVisibleConsensusData(map);
 
2986
                                ConsensusXMLFile().store(topp_.file_name+"_in",map);
 
2987
                        }
 
2988
                        else
 
2989
                        {
 
2990
        ConsensusXMLFile().store(topp_.file_name+"_in",*layer.getConsensusMap());
 
2991
                        }
 
2992
                }
 
2993
 
 
2994
                //compose argument list
 
2995
                QStringList args;
 
2996
                args << "-ini"
 
2997
                                 << (topp_.file_name + "_ini").toQString()
 
2998
                                 << QString("-%1").arg(topp_.in.toQString())
 
2999
                                 << (topp_.file_name + "_in").toQString()
 
3000
                                 << "-no_progress";
 
3001
                if (topp_.out!="")
 
3002
                {
 
3003
                        args << QString("-%1").arg(topp_.out.toQString())
 
3004
                                         << (topp_.file_name+"_out").toQString();
 
3005
                }
 
3006
 
 
3007
                //start log and show it
 
3008
                showLogMessage_(LS_NOTICE,"Starting TOPP tool","");// tool + args.join(" "));
 
3009
 
 
3010
                //start process
 
3011
                topp_.process = new QProcess();
 
3012
                topp_.process->setProcessChannelMode(QProcess::MergedChannels);
 
3013
                connect(topp_.process,SIGNAL(readyReadStandardOutput()),this,SLOT(updateProcessLog()));
 
3014
                topp_.process->start(topp_.tool.toQString(),args);
 
3015
 
 
3016
                //connect the finished slot
 
3017
                connect(topp_.process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finishTOPPToolExecution(int,QProcess::ExitStatus)));
 
3018
 
 
3019
                //start process
 
3020
                topp_.process->waitForStarted();
 
3021
                updateMenu();
 
3022
        }
 
3023
 
 
3024
  void TOPPViewBase::finishTOPPToolExecution(int, QProcess::ExitStatus)
 
3025
  {
 
3026
        //finish with new line
 
3027
        log_->append("");
 
3028
 
 
3029
        String tmp_dir = param_.getValue("preferences:tmp_file_path").toString();
 
3030
 
 
3031
                if (topp_.process->exitStatus()==QProcess::CrashExit)
 
3032
                {
 
3033
                        showLogMessage_(LS_ERROR,"Execution of TOPP tool not successful!",String("The tool crashed during execution. If you want to debug this crash, check the input files in '") + tmp_dir + "' or enable 'debug' mode in the TOPP ini file.");
 
3034
                }
 
3035
                else if(topp_.out!="")
 
3036
                {
 
3037
                        if (!File::readable(topp_.file_name+"_out"))
 
3038
                        {
 
3039
                                showLogMessage_(LS_ERROR,"Cannot read TOPP output",String("Cannot read '")+topp_.file_name+"_out'!");
 
3040
                        }
 
3041
                        else
 
3042
                        {
 
3043
                                addDataFile(topp_.file_name+"_out",true,false, topp_.layer_name + " (" + topp_.tool + ")", topp_.window_id, topp_.spectrum_id);
 
3044
                        }
 
3045
                }
 
3046
 
 
3047
                //clean up
 
3048
                delete topp_.process;
 
3049
                topp_.process = 0;
 
3050
                updateMenu();
 
3051
 
 
3052
                //clean up temporary files
 
3053
                if (param_.getValue("preferences:topp_cleanup")=="true")
 
3054
                {
 
3055
                        File::remove(topp_.file_name+"_ini");
 
3056
                        File::remove(topp_.file_name+"_in");
 
3057
                        File::remove(topp_.file_name+"_out");
 
3058
        }
 
3059
  }
 
3060
 
 
3061
        const LayerData* TOPPViewBase::getCurrentLayer() const
 
3062
        {
 
3063
    SpectrumCanvas* canvas = getActiveCanvas();
 
3064
                if (canvas==0)
 
3065
                {
 
3066
                        return 0;
 
3067
                }
 
3068
                return &(canvas->getCurrentLayer());
 
3069
        }
 
3070
 
 
3071
  void TOPPViewBase::toggleProjections()
 
3072
  {
 
3073
    Spectrum2DWidget* w = getActive2DWidget();
 
3074
    if (w)
 
3075
    {
 
3076
        //update minimum size before
 
3077
        if (!w->projectionsVisible())
 
3078
        {
 
3079
                setMinimumSize(700,700);
 
3080
        }
 
3081
        else
 
3082
        {
 
3083
                setMinimumSize(400,400);
 
3084
        }
 
3085
        w->toggleProjections();
 
3086
    }
 
3087
  }
 
3088
 
 
3089
        void TOPPViewBase::annotateWithID()
 
3090
        {
 
3091
    const LayerData& layer = getActiveCanvas()->getCurrentLayer();
 
3092
                //warn if hidden layer => wrong layer selected...
 
3093
                if (!layer.visible)
 
3094
                {
 
3095
                showLogMessage_(LS_NOTICE,"The current layer is not visible","Have you selected the right layer for this action?");
 
3096
                }
 
3097
 
 
3098
                //load id data
 
3099
    QString name = QFileDialog::getOpenFileName(this,
 
3100
                                                "Select protein identification data",
 
3101
                                                current_path_.toQString(),
 
3102
                                                "idXML files (*.idXML);; all files (*.*)");
 
3103
 
 
3104
                if(name!="")
 
3105
                {
 
3106
                        vector<PeptideIdentification> identifications;
 
3107
                        vector<ProteinIdentification> protein_identifications;
 
3108
  
 
3109
      try
 
3110
      {
 
3111
                        String document_id;
 
3112
                        IdXMLFile().load(name, protein_identifications, identifications, document_id);
 
3113
      }
 
3114
      catch (Exception::BaseException& e)
 
3115
      {
 
3116
        QMessageBox::warning(this, "Error", QString("Loading of idXML file failed! (") + e.what() + ")");
 
3117
                          return;
 
3118
      }
 
3119
 
 
3120
      IDMapper mapper;
 
3121
                        if (layer.type==LayerData::DT_PEAK)
 
3122
                        {
 
3123
        Param p = mapper.getDefaults();
 
3124
        p.setValue("rt_tolerance", 0.1, "RT tolerance (in seconds) for the matching");
 
3125
        p.setValue("mz_tolerance", 1.0, "m/z tolerance (in ppm or Da) for the matching");
 
3126
        p.setValue("mz_measure", "Da", "unit of 'mz_tolerance' (ppm or Da)");
 
3127
        mapper.setParameters(p);
 
3128
        mapper.annotate(*layer.getPeakData(), identifications, protein_identifications);
 
3129
        views_tabwidget_->setTabEnabled(1, true);         // enable identification view
 
3130
                        }
 
3131
                        else if (layer.type==LayerData::DT_FEATURE)
 
3132
                        {
 
3133
        mapper.annotate(*layer.getFeatureMap(), identifications, protein_identifications);
 
3134
                        }
 
3135
                        else
 
3136
                        {
 
3137
        mapper.annotate(*layer.getConsensusMap(), identifications, protein_identifications);
 
3138
                        }
 
3139
                }
 
3140
    updateViewBar();
 
3141
        }
 
3142
 
 
3143
  void TOPPViewBase::showSpectrumGenerationDialog()
 
3144
        {
 
3145
                TheoreticalSpectrumGenerationDialog spec_gen_dialog;
 
3146
                if (spec_gen_dialog.exec())
 
3147
                {
 
3148
                        String seq_string(spec_gen_dialog.line_edit->text());
 
3149
                        if (seq_string == "")
 
3150
                        {
 
3151
                                QMessageBox::warning(this, "Error", "You must enter a peptide sequence!");
 
3152
                                return;
 
3153
                        }
 
3154
      AASequence aa_sequence;
 
3155
      try
 
3156
      {
 
3157
        aa_sequence.setStringSequence(seq_string);
 
3158
      }
 
3159
      catch (Exception::BaseException& e)
 
3160
      {
 
3161
        QMessageBox::warning(this, "Error", QString("Spectrum generation failed! (") + e.what() + ")");
 
3162
                          return;
 
3163
      }
 
3164
                        Int charge = spec_gen_dialog.spin_box->value();
 
3165
 
 
3166
                        if (aa_sequence.isValid())
 
3167
                        {
 
3168
                                RichPeakSpectrum rich_spec;
 
3169
                                TheoreticalSpectrumGenerator generator;
 
3170
                                Param p;
 
3171
 
 
3172
        p.setValue("add_metainfo", "true", "Adds the type of peaks as metainfo to the peaks, like y8+, [M-H2O+2H]++");
 
3173
 
 
3174
                                bool losses = (spec_gen_dialog.list_widget->item(7)->checkState() == Qt::Checked); // "Neutral losses"
 
3175
                                String losses_str = losses ? "true" : "false";
 
3176
                                p.setValue("add_losses", losses_str, "Adds common losses to those ion expect to have them, only water and ammonia loss is considered");
 
3177
 
 
3178
                                bool isotopes = (spec_gen_dialog.list_widget->item(8)->checkState() == Qt::Checked); // "Isotope clusters"
 
3179
                                String iso_str = isotopes ? "true" : "false";
 
3180
                                p.setValue("add_isotopes", iso_str, "If set to 1 isotope peaks of the product ion peaks are added");
 
3181
 
 
3182
        bool abundant_immonium_ions = (spec_gen_dialog.list_widget->item(9)->checkState() == Qt::Checked); // "abundant immonium-ions"
 
3183
        String abundant_immonium_ions_str = abundant_immonium_ions ? "true" : "false";
 
3184
        p.setValue("add_abundant_immonium_ions", abundant_immonium_ions_str, "Add most abundant immonium ions");
 
3185
 
 
3186
        Size max_iso_count = (Size)spec_gen_dialog.max_iso_spinbox->value();
 
3187
        p.setValue("max_isotope", max_iso_count, "Number of isotopic peaks");
 
3188
                                p.setValue("a_intensity", spec_gen_dialog.a_intensity->value(), "Intensity of the a-ions");
 
3189
                                p.setValue("b_intensity", spec_gen_dialog.b_intensity->value(), "Intensity of the b-ions");
 
3190
                                p.setValue("c_intensity", spec_gen_dialog.c_intensity->value(), "Intensity of the c-ions");
 
3191
                                p.setValue("x_intensity", spec_gen_dialog.x_intensity->value(), "Intensity of the x-ions");
 
3192
                                p.setValue("y_intensity", spec_gen_dialog.y_intensity->value(), "Intensity of the y-ions");
 
3193
                                p.setValue("z_intensity", spec_gen_dialog.z_intensity->value(), "Intensity of the z-ions");
 
3194
                                DoubleReal rel_loss_int = (DoubleReal)(spec_gen_dialog.rel_loss_intensity->value()) / 100.0;
 
3195
                                p.setValue("relative_loss_intensity", rel_loss_int, "Intensity of loss ions, in relation to the intact ion intensity");
 
3196
                                generator.setParameters(p);
 
3197
 
 
3198
        try
 
3199
        {
 
3200
                                  if (spec_gen_dialog.list_widget->item(0)->checkState() == Qt::Checked) // "A-ions"
 
3201
                                  {
 
3202
                                          generator.addPeaks(rich_spec, aa_sequence, Residue::AIon, charge);
 
3203
                                  }
 
3204
                                  if (spec_gen_dialog.list_widget->item(1)->checkState() == Qt::Checked) // "B-ions"
 
3205
                                  {
 
3206
                                          generator.addPeaks(rich_spec, aa_sequence, Residue::BIon, charge);
 
3207
                                  }
 
3208
                                  if (spec_gen_dialog.list_widget->item(2)->checkState() == Qt::Checked) // "C-ions"
 
3209
                                  {
 
3210
                                          generator.addPeaks(rich_spec, aa_sequence, Residue::CIon, charge);
 
3211
                                  }
 
3212
                                  if (spec_gen_dialog.list_widget->item(3)->checkState() == Qt::Checked) // "X-ions"
 
3213
                                  {
 
3214
                                          generator.addPeaks(rich_spec, aa_sequence, Residue::XIon, charge);
 
3215
                                  }
 
3216
                                  if (spec_gen_dialog.list_widget->item(4)->checkState() == Qt::Checked) // "Y-ions"
 
3217
                                  {
 
3218
                                          generator.addPeaks(rich_spec, aa_sequence, Residue::YIon, charge);
 
3219
                                  }
 
3220
                                  if (spec_gen_dialog.list_widget->item(5)->checkState() == Qt::Checked) // "Z-ions"
 
3221
                                  {
 
3222
                                          generator.addPeaks(rich_spec, aa_sequence, Residue::ZIon, charge);
 
3223
                                  }
 
3224
                                  if (spec_gen_dialog.list_widget->item(6)->checkState() == Qt::Checked) // "Precursor"
 
3225
                                  {
 
3226
                                          generator.addPrecursorPeaks(rich_spec, aa_sequence, charge);
 
3227
          }
 
3228
          if (spec_gen_dialog.list_widget->item(9)->checkState() == Qt::Checked) // "abundant Immonium-ions"
 
3229
          {
 
3230
            generator.addAbundantImmoniumIons(rich_spec);
 
3231
          }
 
3232
        }
 
3233
        catch (Exception::BaseException& e)
 
3234
        {
 
3235
          QMessageBox::warning(this, "Error", QString("Spectrum generation failed! (") + e.what() + "). Please report this to the developers (specify what input you used)!");
 
3236
                                  return;
 
3237
        }
 
3238
 
 
3239
        // convert rich spectrum to simple spectrum
 
3240
                                PeakSpectrum new_spec;
 
3241
                                for (RichPeakSpectrum::Iterator it = rich_spec.begin(); it != rich_spec.end(); ++it)
 
3242
                                {
 
3243
                                        new_spec.push_back(static_cast<Peak1D>(*it));
 
3244
                                }
 
3245
 
 
3246
                                PeakMap new_exp;
 
3247
                                new_exp.push_back(new_spec);
 
3248
        ExperimentSharedPtrType new_exp_sptr(new PeakMap(new_exp));
 
3249
        FeatureMapSharedPtrType f_dummy(new FeatureMapType());
 
3250
        ConsensusMapSharedPtrType c_dummy(new ConsensusMapType());
 
3251
                                vector<PeptideIdentification> p_dummy;
 
3252
        addData(f_dummy, c_dummy, p_dummy, new_exp_sptr, LayerData::DT_CHROMATOGRAM, false, true, true, "", seq_string + QString(" (theoretical)"));
 
3253
 
 
3254
              // ensure spectrum is drawn as sticks
 
3255
              draw_group_1d_->button(Spectrum1DCanvas::DM_PEAKS)->setChecked(true);
 
3256
                                setDrawMode1D(Spectrum1DCanvas::DM_PEAKS);
 
3257
 
 
3258
                        }
 
3259
                        else
 
3260
                        {
 
3261
                                QMessageBox::warning(this, "Error", "The entered peptide sequence is invalid!");
 
3262
                        }
 
3263
                }
 
3264
        }
 
3265
 
 
3266
        void TOPPViewBase::showSpectrumAlignmentDialog()
 
3267
        {
 
3268
    Spectrum1DWidget* active_1d_window = getActive1DWidget();
 
3269
                if (!active_1d_window || !active_1d_window->canvas()->mirrorModeActive())
 
3270
                {
 
3271
                        return;
 
3272
                }
 
3273
                Spectrum1DCanvas* cc = active_1d_window->canvas();
 
3274
 
 
3275
                SpectrumAlignmentDialog spec_align_dialog(active_1d_window);
 
3276
                if (spec_align_dialog.exec())
 
3277
                {
 
3278
                        Int layer_index_1 = spec_align_dialog.get1stLayerIndex();
 
3279
                        Int layer_index_2 = spec_align_dialog.get2ndLayerIndex();
 
3280
 
 
3281
                        // two layers must be selected:
 
3282
                        if (layer_index_1 < 0 || layer_index_2 < 0)
 
3283
                        {
 
3284
                                QMessageBox::information(this, "Layer selection invalid", "You must select two layers for an alignment.");
 
3285
                                return;
 
3286
                        }
 
3287
 
 
3288
                        Param param;
 
3289
                        DoubleReal tolerance = spec_align_dialog.tolerance_spinbox->value();
 
3290
      param.setValue("tolerance", tolerance, "Defines the absolut (in Da) or relative (in ppm) mass tolerance");
 
3291
                        String unit_is_ppm = spec_align_dialog.ppm->isChecked() ? "true" : "false";
 
3292
      param.setValue("is_relative_tolerance", unit_is_ppm, "If true, the mass tolerance is interpreted as ppm value otherwise in Dalton");
 
3293
 
 
3294
                        active_1d_window->performAlignment((UInt)layer_index_1, (UInt)layer_index_2, param);
 
3295
 
 
3296
                        DoubleReal al_score = cc->getAlignmentScore();
 
3297
                        Size al_size = cc->getAlignmentSize();
 
3298
 
 
3299
                        QMessageBox::information(this, "Alignment performed", QString("Aligned %1 pairs of peaks (Score: %2).").arg(al_size).arg(al_score));
 
3300
                }
 
3301
        }
 
3302
 
 
3303
        void TOPPViewBase::showSpectrumAs1D(int index)
 
3304
        {
 
3305
    Spectrum1DWidget* widget_1d = getActive1DWidget();
 
3306
    Spectrum2DWidget* widget_2d = getActive2DWidget();
 
3307
 
 
3308
    if (widget_1d)
 
3309
    {
 
3310
      if (spectra_view_widget_->isVisible())
 
3311
      {
 
3312
        spectraview_behavior_->showSpectrumAs1D(index);
 
3313
      }
 
3314
 
 
3315
      if (spectra_identification_view_widget_->isVisible())
 
3316
      {
 
3317
        identificationview_behavior_->showSpectrumAs1D(index);
 
3318
      }
 
3319
    } else if (widget_2d)
 
3320
    {
 
3321
      if (spectra_view_widget_->isVisible())
 
3322
      {
 
3323
        spectraview_behavior_->showSpectrumAs1D(index);
 
3324
      }
 
3325
 
 
3326
      if (spectra_identification_view_widget_->isVisible())
 
3327
      {
 
3328
        identificationview_behavior_->showSpectrumAs1D(index);
 
3329
      }
 
3330
    }
 
3331
 
 
3332
        }
 
3333
 
 
3334
  void TOPPViewBase::showCurrentPeaksAs2D()
 
3335
  {
 
3336
    const LayerData& layer = getActiveCanvas()->getCurrentLayer();
 
3337
    ExperimentSharedPtrType exp_sptr = layer.getPeakData();
 
3338
 
 
3339
    //open new 2D widget
 
3340
    Spectrum2DWidget* w = new Spectrum2DWidget(getSpectrumParameters(2), ws_);
 
3341
 
 
3342
    //add data
 
3343
    if (!w->canvas()->addLayer(exp_sptr, layer.filename))
 
3344
    {
 
3345
      return;
 
3346
    }
 
3347
 
 
3348
    String caption = layer.name;
 
3349
    w->canvas()->setLayerName(w->canvas()->activeLayerIndex(), caption);
 
3350
    showSpectrumWidgetInWindow(w, caption);
 
3351
    updateLayerBar();
 
3352
    updateViewBar();
 
3353
    updateFilterBar();
 
3354
    updateMenu();
 
3355
  }
 
3356
 
 
3357
  void TOPPViewBase::showCurrentPeaksAs3D()
 
3358
  {
 
3359
    const LayerData& layer = getActiveCanvas()->getCurrentLayer();
 
3360
 
 
3361
    if (layer.type == LayerData::DT_PEAK)
 
3362
    {
 
3363
      //open new 3D widget
 
3364
      Spectrum3DWidget* w = new Spectrum3DWidget(getSpectrumParameters(3), ws_);
 
3365
 
 
3366
      ExperimentSharedPtrType exp_sptr = getActiveCanvas()->getCurrentLayer().getPeakData();
 
3367
 
 
3368
      if (!w->canvas()->addLayer(exp_sptr, layer.filename))
 
3369
      {
 
3370
        return;
 
3371
      }
 
3372
 
 
3373
     if (getActive1DWidget()) // switch from 1D to 3D
 
3374
     {
 
3375
       //TODO:
 
3376
       //- doesnt make sense for fragment scan
 
3377
       //- build new Area with mz range equal to 1D visible range
 
3378
       //- rt range either overall MS1 data range or some convenient window
 
3379
 
 
3380
     } else if (getActive2DWidget())  // switch from 2D to 3D
 
3381
     {
 
3382
        w->canvas()->setVisibleArea(getActiveCanvas()->getVisibleArea());
 
3383
     }
 
3384
 
 
3385
      // set layer name
 
3386
      String caption = layer.name + " (3D)";
 
3387
      w->canvas()->setLayerName(w->canvas()->activeLayerIndex(), caption);
 
3388
      showSpectrumWidgetInWindow(w, caption);
 
3389
 
 
3390
      // set intensity mode (after spectrum has been added!)
 
3391
      setIntensityMode(SpectrumCanvas::IM_SNAP);
 
3392
 
 
3393
      updateLayerBar();
 
3394
      updateViewBar();
 
3395
      updateFilterBar();
 
3396
      updateMenu();
 
3397
    }
 
3398
    else
 
3399
    {
 
3400
      showLogMessage_(LS_NOTICE,"Wrong layer type","You cannot open feature data in 3D mode.");
 
3401
    }
 
3402
  }
 
3403
 
 
3404
        void TOPPViewBase::showAboutDialog()
 
3405
        {
 
3406
                //dialog and grid layout
 
3407
                QDialog* dlg = new QDialog(this);
 
3408
                QGridLayout* grid = new QGridLayout(dlg);
 
3409
                dlg->setWindowTitle("About TOPPView");
 
3410
 
 
3411
                //image
 
3412
                QLabel* label = new QLabel(dlg);
 
3413
                label->setPixmap(QPixmap(":/TOPP_about.png"));
 
3414
                grid->addWidget(label,0,0);
 
3415
 
 
3416
                //text
 
3417
                QString text = QString("<BR>"
 
3418
                                                                                                         "<FONT size=+3>TOPPView</font><BR>"
 
3419
                                                                                                         "<BR>"
 
3420
                                                                                                         "Version: %1<BR>"
 
3421
                                                                                                         "<BR>"
 
3422
                                                                                                         "OpenMS and TOPP is free software available under the<BR>"
 
3423
                                                                                                         "Lesser GNU Public License (LGPL)<BR>"
 
3424
                                                                                                         "<BR>"
 
3425
                                                                                                         "<BR>"
 
3426
                                                                                                         "<BR>"
 
3427
                                                                                                         "<BR>"
 
3428
                                                                                                         "<BR>"
 
3429
                                                                                                         "Any published work based on TOPP and OpenMS shall cite these papers:<BR>"
 
3430
                                                                                                         "Sturm et al., BMC Bioinformatics (2008), 9, 163<BR>"
 
3431
                                                                                                         "Kohlbacher et al., Bioinformatics (2007), 23:e191-e197<BR>"
 
3432
                                                                                                         ).arg(VersionInfo::getVersion().toQString());
 
3433
                label = new QLabel(text,dlg);
 
3434
                grid->addWidget(label,0,1,Qt::AlignTop | Qt::AlignLeft);
 
3435
 
 
3436
                //close button
 
3437
                QPushButton* button = new QPushButton("Close",dlg);
 
3438
                grid->addWidget(button,1,1,Qt::AlignBottom | Qt::AlignRight);
 
3439
                connect(button,SIGNAL(clicked()),dlg,SLOT(close()));
 
3440
 
 
3441
                //execute
 
3442
                dlg->exec();
 
3443
        }
 
3444
 
 
3445
        void TOPPViewBase::updateProcessLog()
 
3446
        {
 
3447
                //show log if there is output
 
3448
                qobject_cast<QWidget *>(log_->parent())->show();
 
3449
 
 
3450
                //update log_
 
3451
                log_->append(topp_.process->readAllStandardOutput());
 
3452
        }
 
3453
 
 
3454
  Param TOPPViewBase::getSpectrumParameters(UInt dim)
 
3455
        {
 
3456
                Param out = param_.copy(String("preferences:") + dim + "d:",true);
 
3457
                out.setValue("default_path",param_.getValue("preferences:default_path").toString());
 
3458
                return out;
 
3459
        }
 
3460
 
 
3461
  void TOPPViewBase::abortTOPPTool()
 
3462
  {
 
3463
        if (topp_.process)
 
3464
        {
 
3465
                //block signals to avoid error message from finished() signal
 
3466
                topp_.process->blockSignals(true);
 
3467
                //kill and delete the process
 
3468
                topp_.process->terminate();
 
3469
                delete topp_.process;
 
3470
                topp_.process = 0;
 
3471
 
 
3472
                        //finish log with new line
 
3473
                log_->append("");
 
3474
 
 
3475
                updateMenu();
 
3476
        }
 
3477
  }
 
3478
 
 
3479
  void TOPPViewBase::updateMenu()
 
3480
  {
 
3481
        //is there a canvas?
 
3482
        bool canvas_exists = false;
 
3483
    if (getActiveCanvas()!=0)
 
3484
        {
 
3485
                canvas_exists = true;
 
3486
        }
 
3487
        //is there a layer?
 
3488
        bool layer_exists = false;
 
3489
    if (canvas_exists && getActiveCanvas()->getLayerCount()!=0)
 
3490
        {
 
3491
                layer_exists = true;
 
3492
        }
 
3493
                //is there a TOPP tool running
 
3494
                bool topp_running = false;
 
3495
                if (topp_.process!=0)
 
3496
                {
 
3497
                        topp_running = true;
 
3498
                }
 
3499
 
 
3500
    TOPPASWidget* tw = getActiveTOPPASWidget();
 
3501
    TOPPASScene* ts = 0;
 
3502
    if (tw)
 
3503
    {
 
3504
      ts = tw->getScene();
 
3505
    } else // active widget is no TOPPAS widget
 
3506
    {
 
3507
 
 
3508
    }
 
3509
 
 
3510
    bool mirror_mode = getActive1DWidget() && getActive1DWidget()->canvas()->mirrorModeActive();
 
3511
                QList<QAction*> actions = this->findChildren<QAction*>("");
 
3512
                for (int i=0; i<actions.count(); ++i)
 
3513
                {
 
3514
                        QString text = actions[i]->text();
 
3515
                        if (text=="&Close" || text=="Show/hide grid lines" || text=="Show/hide axis legends")
 
3516
                        {
 
3517
                                actions[i]->setEnabled(false);
 
3518
                                if (canvas_exists)
 
3519
                                {
 
3520
                                        actions[i]->setEnabled(true);
 
3521
                                }
 
3522
                        }
 
3523
                        else if (text.left(15)=="Apply TOPP tool")
 
3524
                        {
 
3525
                                actions[i]->setEnabled(false);
 
3526
                                if (canvas_exists && layer_exists && !topp_running)
 
3527
                                {
 
3528
                                        actions[i]->setEnabled(true);
 
3529
                                }
 
3530
                        }
 
3531
                        else if (text=="Abort running TOPP tool")
 
3532
                        {
 
3533
                                actions[i]->setEnabled(false);
 
3534
                                if (topp_running)
 
3535
                                {
 
3536
                                        actions[i]->setEnabled(true);
 
3537
                                }
 
3538
                        }
 
3539
                        else if (text=="Rerun TOPP tool")
 
3540
                        {
 
3541
                                actions[i]->setEnabled(false);
 
3542
                                if (canvas_exists && layer_exists && !topp_running && topp_.tool!="")
 
3543
                                {
 
3544
                                        actions[i]->setEnabled(true);
 
3545
                                }
 
3546
                        }
 
3547
      else if (text=="&Go to" || text=="&Edit meta data" || text=="&Statistics" || text=="&Annotate with identification"  || text=="Save all data"  || text=="Save visible data"  || text=="Preferences")
 
3548
                        {
 
3549
                                actions[i]->setEnabled(false);
 
3550
                                if (canvas_exists && layer_exists)
 
3551
                                {
 
3552
                                        actions[i]->setEnabled(true);
 
3553
                                }
 
3554
                        }
 
3555
                        else if (text=="Align spectra")
 
3556
                        {
 
3557
                                actions[i]->setEnabled(false);
 
3558
                                if (mirror_mode)
 
3559
                                {
 
3560
                                        actions[i]->setEnabled(true);
 
3561
                                }
 
3562
                        }
 
3563
      else if (text=="&Run (F5)")  // pipeline menu
 
3564
      {
 
3565
        bool show = false;
 
3566
        if (ts && !(ts->isPipelineRunning()))
 
3567
        {
 
3568
          show = true;
 
3569
        }
 
3570
        actions[i]->setEnabled(show);
 
3571
      }
 
3572
      else if (text=="&Abort") // pipeline menu
 
3573
      {
 
3574
        bool show = false;
 
3575
        if (ts && ts->isPipelineRunning())
 
3576
        {
 
3577
          show = true;
 
3578
        }
 
3579
        actions[i]->setEnabled(show);
 
3580
      }
 
3581
      else if (text=="&Include TOPPAS pipeline") // pipeline menu
 
3582
      {
 
3583
        bool show = ts;
 
3584
        actions[i]->setEnabled(show);
 
3585
      }
 
3586
      else if (text=="&Load TOPPAS resource file") // pipeline menu
 
3587
      {
 
3588
        bool show = ts;
 
3589
        actions[i]->setEnabled(show);
 
3590
      }
 
3591
      else if (text=="Save TOPPAS &resource file") // pipeline menu
 
3592
      {
 
3593
        bool show = ts;
 
3594
        actions[i]->setEnabled(show);
 
3595
      }
 
3596
      else if (text=="&Save TOPPAS pipeline")
 
3597
      {
 
3598
        bool show = ts && ts->wasChanged();
 
3599
        actions[i]->setEnabled(show);
 
3600
      }
 
3601
      else if (text=="Save TOPPAS pipeline &As")
 
3602
      {
 
3603
        bool show = ts && ts->wasChanged();
 
3604
        actions[i]->setEnabled(show);
 
3605
      }
 
3606
      else if (text=="Refresh TOPPAS &parameters") // pipeline menu
 
3607
      {
 
3608
        bool show = ts && !(ts->isPipelineRunning());
 
3609
        actions[i]->setEnabled(show);
 
3610
      }
 
3611
                        else if (text=="")
 
3612
                        {
 
3613
                                actions[i]->setEnabled(false);
 
3614
                                if (canvas_exists && layer_exists)
 
3615
                                {
 
3616
                                        actions[i]->setEnabled(true);
 
3617
                                }
 
3618
                        }
 
3619
                }
 
3620
  }
 
3621
 
 
3622
  void TOPPViewBase::loadFiles(const StringList& list, QSplashScreen* splash_screen)
 
3623
  {
 
3624
                bool last_was_plus = false;
 
3625
    for (StringList::const_iterator it=list.begin(); it!=list.end(); ++it)
 
3626
    {
 
3627
      if (*it=="+")
 
3628
      {
 
3629
        last_was_plus = true;
 
3630
        continue;
 
3631
        }
 
3632
        else if (*it=="@bw")
 
3633
        {
 
3634
        if ( (getActive2DWidget()!=0 || getActive3DWidget()!=0) && getActiveCanvas()!=0 )
 
3635
                {
 
3636
          Param tmp = getActiveCanvas()->getCurrentLayer().param;
 
3637
                        tmp.setValue("dot:gradient", "Linear|0,#ffffff;100,#000000");
 
3638
          getActiveCanvas()->setCurrentLayerParameters(tmp);
 
3639
                }
 
3640
        }
 
3641
        else if (*it=="@bg")
 
3642
        {
 
3643
        if ( (getActive2DWidget()!=0 || getActive3DWidget()!=0) && getActiveCanvas()!=0 )
 
3644
                {
 
3645
          Param tmp = getActiveCanvas()->getCurrentLayer().param;
 
3646
                        tmp.setValue("dot:gradient", "Linear|0,#dddddd;100,#000000");
 
3647
          getActiveCanvas()->setCurrentLayerParameters(tmp);
 
3648
                }
 
3649
        }
 
3650
        else if (*it=="@b")
 
3651
        {
 
3652
        if ( (getActive2DWidget()!=0 || getActive3DWidget()!=0) && getActiveCanvas()!=0 )
 
3653
                {
 
3654
          Param tmp = getActiveCanvas()->getCurrentLayer().param;
 
3655
                        tmp.setValue("dot:gradient", "Linear|0,#000000;100,#000000");
 
3656
          getActiveCanvas()->setCurrentLayerParameters(tmp);
 
3657
                }
 
3658
        }
 
3659
        else if (*it=="@r")
 
3660
        {
 
3661
        if ( (getActive2DWidget()!=0 || getActive3DWidget()!=0) && getActiveCanvas()!=0 )
 
3662
                {
 
3663
          Param tmp = getActiveCanvas()->getCurrentLayer().param;
 
3664
                        tmp.setValue("dot:gradient", "Linear|0,#ff0000;100,#ff0000");
 
3665
          getActiveCanvas()->setCurrentLayerParameters(tmp);
 
3666
                }
 
3667
        }
 
3668
        else if (*it=="@g")
 
3669
        {
 
3670
        if ( (getActive2DWidget()!=0 || getActive3DWidget()!=0) && getActiveCanvas()!=0 )
 
3671
                {
 
3672
          Param tmp = getActiveCanvas()->getCurrentLayer().param;
 
3673
                        tmp.setValue("dot:gradient", "Linear|0,#00ff00;100,#00ff00");
 
3674
          getActiveCanvas()->setCurrentLayerParameters(tmp);
 
3675
                }
 
3676
        }
 
3677
        else if (*it=="@m")
 
3678
        {
 
3679
        if ( (getActive2DWidget()!=0 || getActive3DWidget()!=0) && getActiveCanvas()!=0 )
 
3680
                {
 
3681
          Param tmp = getActiveCanvas()->getCurrentLayer().param;
 
3682
                        tmp.setValue("dot:gradient", "Linear|0,#ff00ff;100,#ff00ff");
 
3683
          getActiveCanvas()->setCurrentLayerParameters(tmp);
 
3684
                }
 
3685
        }
 
3686
      else if (!last_was_plus || !getActiveSpectrumWidget())
 
3687
        {
 
3688
                splash_screen->showMessage((String("Loading file: ") + *it).toQString());
 
3689
                splash_screen->repaint();
 
3690
                QApplication::processEvents();
 
3691
        addDataFile(*it, false, true);  // add data file but don't show options
 
3692
        }
 
3693
        else
 
3694
        {
 
3695
                splash_screen->showMessage((String("Loading file: ") + *it).toQString());
 
3696
                splash_screen->repaint();
 
3697
                QApplication::processEvents();
 
3698
                last_was_plus = false;
 
3699
        addDataFile(*it, false, true,"",getActiveSpectrumWidget()->getWindowId());
 
3700
        }
 
3701
    }
 
3702
  }
 
3703
 
 
3704
  void TOPPViewBase::showLogMessage_(TOPPViewBase::LogState state, const String& heading, const String& body)
 
3705
  {
 
3706
                //Compose current time string
 
3707
                DateTime d = DateTime::now();
 
3708
 
 
3709
                String state_string;
 
3710
                switch(state)
 
3711
                {
 
3712
                        case LS_NOTICE: state_string = "NOTICE"; break;
 
3713
                        case LS_WARNING: state_string = "WARNING"; break;
 
3714
                        case LS_ERROR: state_string = "ERROR"; break;
 
3715
                }
 
3716
 
 
3717
                //update log
 
3718
                log_->append("==============================================================================");
 
3719
                log_->append((d.getTime() + " " + state_string + ": " + heading).toQString());
 
3720
                log_->append(body.toQString());
 
3721
 
 
3722
        //show log tool window
 
3723
                qobject_cast<QWidget *>(log_->parent())->show();
 
3724
  }
 
3725
 
 
3726
        void TOPPViewBase::saveLayerAll()
 
3727
        {
 
3728
    getActiveCanvas()->saveCurrentLayer(false);
 
3729
        }
 
3730
 
 
3731
        void TOPPViewBase::saveLayerVisible()
 
3732
        {
 
3733
    getActiveCanvas()->saveCurrentLayer(true);
 
3734
        }
 
3735
 
 
3736
        void TOPPViewBase::toggleGridLines()
 
3737
        {
 
3738
    getActiveCanvas()->showGridLines(!getActiveCanvas()->gridLinesShown());
 
3739
        }
 
3740
 
 
3741
        void TOPPViewBase::toggleAxisLegends()
 
3742
        {
 
3743
    getActiveSpectrumWidget()->showLegend(!getActiveSpectrumWidget()->isLegendShown());
 
3744
        }
 
3745
 
 
3746
        void TOPPViewBase::showPreferences()
 
3747
        {
 
3748
    getActiveCanvas()->showCurrentLayerPreferences();
 
3749
        }
 
3750
 
 
3751
        void TOPPViewBase::metadataFileDialog()
 
3752
        {
 
3753
                QStringList files = getFileList_();
 
3754
                FileHandler fh;
 
3755
                fh.getOptions().setMetadataOnly(true);
 
3756
                for (QStringList::iterator it = files.begin(); it!=files.end(); ++it)
 
3757
                {
 
3758
                        ExperimentType exp;
 
3759
                        try
 
3760
                        {
 
3761
                                fh.loadExperiment(*it,exp);
 
3762
                        }
 
3763
                        catch (Exception::BaseException& e)
 
3764
                        {
 
3765
                                QMessageBox::critical(this,"Error",(String("Error while reading data: ")+e.what()).c_str());
 
3766
              return;
 
3767
                        }
 
3768
                        MetaDataBrowser dlg(false, this);
 
3769
                        dlg.add(exp);
 
3770
                        dlg.exec();
 
3771
                }
 
3772
        }
 
3773
 
 
3774
        void TOPPViewBase::metadataDatabaseDialog()
 
3775
        {
 
3776
                DBConnection con;
 
3777
                connectToDB_(con);
 
3778
                if (con.isConnected())
 
3779
                {
 
3780
                        vector<UInt> ids;
 
3781
                        DBOpenDialog db_dialog(con,ids,ws_);
 
3782
                        if (db_dialog.exec())
 
3783
                        {
 
3784
                                DBAdapter db(con);
 
3785
                                db.getOptions().setMetadataOnly(true);
 
3786
                                for (vector<UInt>::iterator it = ids.begin();it!=ids.end();++it)
 
3787
                                {
 
3788
                                        ExperimentType exp;
 
3789
                                        try
 
3790
                                        {
 
3791
                                                db.loadExperiment(*it, exp);
 
3792
                                        }
 
3793
                                        catch (Exception::BaseException& e)
 
3794
                                        {
 
3795
                                                QMessageBox::critical(this,"Error",(String("Error while reading data: ")+e.what()).c_str());
 
3796
                              return;
 
3797
                                        }
 
3798
                                        MetaDataBrowser dlg(false, this);
 
3799
                                        dlg.add(exp);
 
3800
                                        dlg.exec();
 
3801
                                }
 
3802
                        }
 
3803
                }
 
3804
        }
 
3805
 
 
3806
  SpectraIdentificationViewWidget* TOPPViewBase::getSpectraIdentificationViewWidget()
 
3807
  {
 
3808
    return spectra_identification_view_widget_;
 
3809
  }
 
3810
 
 
3811
  void TOPPViewBase::showSpectrumMetaData(int spectrum_index)
 
3812
  {
 
3813
    getActiveCanvas()->showMetaData(true, spectrum_index);
 
3814
  }
 
3815
 
 
3816
  void TOPPViewBase::copyLayer(const QMimeData* data, QWidget* source, int id)
 
3817
        {
 
3818
    QTreeWidget* spectra_view_treewidget = spectra_view_widget_->getTreeWidget();
 
3819
                try
 
3820
                {
 
3821
                        //NOT USED RIGHT NOW, BUT KEEP THIS CODE (it was hard to find out how this is done)
 
3822
                        //decode data to get the row
 
3823
                        //QByteArray encoded_data = data->data(data->formats()[0]);
 
3824
                        //QDataStream stream(&encoded_data, QIODevice::ReadOnly);
 
3825
                        //int row, col;
 
3826
                        //stream >> row >> col;
 
3827
 
 
3828
                //set wait cursor
 
3829
                setCursor(Qt::WaitCursor);
 
3830
 
 
3831
                        //determine where to copy the data
 
3832
                        UInt new_id = 0;
 
3833
      if (id != -1) new_id = id;
 
3834
 
 
3835
                        if (source == layer_manager_)
 
3836
                        {
 
3837
                                //only the selected row can be dragged => the source layer is the selected layer
 
3838
        const LayerData& layer = getActiveCanvas()->getCurrentLayer();
 
3839
 
 
3840
         //attach feature, consensus and peak data
 
3841
        FeatureMapSharedPtrType features = layer.getFeatureMap();
 
3842
        ExperimentSharedPtrType peaks = layer.getPeakData();
 
3843
        ConsensusMapSharedPtrType consensus = layer.getConsensusMap();
 
3844
                                vector<PeptideIdentification> peptides = layer.peptides;
 
3845
 
 
3846
                                //add the data
 
3847
        addData(features, consensus, peptides, peaks, layer.type, false, false, true, layer.filename, layer.name, new_id);
 
3848
                        }
 
3849
      else if (source == spectra_view_treewidget)
 
3850
                        {
 
3851
        const LayerData& layer = getActiveCanvas()->getCurrentLayer();
 
3852
        QTreeWidgetItem* item = spectra_view_treewidget->currentItem();
 
3853
                                if (item != 0)
 
3854
                                {
 
3855
                                        Size index = (Size)(item->text(3).toInt());
 
3856
          const ExperimentType::SpectrumType spectrum = (*layer.getPeakData())[index];
 
3857
                                        ExperimentType new_exp;
 
3858
                                        new_exp.push_back(spectrum);
 
3859
          ExperimentSharedPtrType new_exp_sptr(new ExperimentType(new_exp));
 
3860
          FeatureMapSharedPtrType f_dummy(new FeatureMapType());
 
3861
          ConsensusMapSharedPtrType c_dummy(new ConsensusMapType());
 
3862
                                        vector<PeptideIdentification> p_dummy;
 
3863
          addData(f_dummy, c_dummy, p_dummy, new_exp_sptr, LayerData::DT_CHROMATOGRAM, false, false, true, layer.filename, layer.name, new_id);
 
3864
                                }
 
3865
                        }
 
3866
                        else if (source == 0)
 
3867
                        {
 
3868
                                // drag source is external
 
3869
                                if (data->hasUrls())
 
3870
                                {
 
3871
                                        QList<QUrl> urls = data->urls();
 
3872
                                        for (QList<QUrl>::const_iterator it = urls.begin(); it != urls.end(); ++it)
 
3873
                                        {
 
3874
                                                addDataFile(it->toLocalFile(), false, true, "", new_id);
 
3875
                                        }
 
3876
                                }
 
3877
                        }
 
3878
 
 
3879
                }
 
3880
    catch(Exception::BaseException& e)
 
3881
    {
 
3882
        showLogMessage_(LS_ERROR,"Error while creating layer",e.what());
 
3883
    }
 
3884
 
 
3885
                //reset cursor
 
3886
        setCursor(Qt::ArrowCursor);
 
3887
        }
 
3888
 
 
3889
 
 
3890
        void TOPPViewBase::updateCurrentPath()
 
3891
        {
 
3892
                //do not update if the user disabled this feature.
 
3893
                if (param_.getValue("preferences:default_path_current")!="true") return;
 
3894
 
 
3895
                //reset
 
3896
                current_path_ = param_.getValue("preferences:default_path");
 
3897
 
 
3898
                //update if the current layer has a path associated
 
3899
    if (getActiveCanvas() && getActiveCanvas()->getLayerCount()!=0 && getActiveCanvas()->getCurrentLayer().filename!="")
 
3900
                {
 
3901
      current_path_ = File::path(getActiveCanvas()->getCurrentLayer().filename);
 
3902
                }
 
3903
        }
 
3904
 
 
3905
        void TOPPViewBase::showSpectrumBrowser()
 
3906
        {
 
3907
    views_dockwidget_->show();
 
3908
    updateViewBar();
 
3909
        }
 
3910
 
 
3911
  void TOPPViewBase::fileChanged_(const String& filename)
 
3912
  {
 
3913
    // check if file has been deleted
 
3914
    if (!QFileInfo(filename.toQString()).exists())
 
3915
    {
 
3916
      watcher_->removeFile(filename);
 
3917
      return;
 
3918
    }
 
3919
 
 
3920
    QWidgetList wl = ws_->windowList();
 
3921
 
 
3922
    // iterate over all windows and determine which need an update
 
3923
    std::vector<std::pair<const SpectrumWidget *, Size> > needs_update;
 
3924
    for(int i=0; i!=ws_->windowList().count(); ++i)
 
3925
    {
 
3926
      //std::cout << "Number of windows: " << ws_->windowList().count() << std::endl;
 
3927
      QWidget* w = wl[i];
 
3928
      const SpectrumWidget* sw = qobject_cast<const SpectrumWidget*>(w);
 
3929
      if (sw!=0)
 
3930
      {
 
3931
        Size lc = sw->canvas()->getLayerCount();
 
3932
 
 
3933
        // determine if widget stores one or more layers for the given filename (->needs update)
 
3934
        for (Size j=0; j!= lc; ++j)
 
3935
        {
 
3936
          //std::cout << "Layer filename: " << sw->canvas()->getLayer(j).filename << std::endl;
 
3937
          const LayerData& ld = sw->canvas()->getLayer(j);
 
3938
          if (ld.filename == filename)
 
3939
          {
 
3940
            needs_update.push_back(std::pair<const SpectrumWidget *, Size>(sw,j));
 
3941
          }
 
3942
        }
 
3943
      }
 
3944
    }
 
3945
 
 
3946
    if (needs_update.empty()) // no layer references data of filename
 
3947
    {
 
3948
      watcher_->removeFile(filename);  // remove watcher
 
3949
      return;
 
3950
    } else if ( !needs_update.empty() )  // at least one layer references data of filename
 
3951
    {
 
3952
      //std::cout << "Number of Layers that need update: " << needs_update.size() << std::endl;
 
3953
      pair<const SpectrumWidget *, Size>& slp = needs_update[0];
 
3954
      const SpectrumWidget * sw = slp.first;
 
3955
      Size layer_index = slp.second;
 
3956
 
 
3957
      bool user_wants_update = false;
 
3958
      if ((String)(param_.getValue("preferences:on_file_change"))=="update automatically") //automatically update
 
3959
      {
 
3960
        user_wants_update = true;
 
3961
      }
 
3962
      else if ((String)(param_.getValue("preferences:on_file_change"))=="ask") //ask the user if the layer should be updated
 
3963
      {
 
3964
        if (watcher_msgbox_==true)
 
3965
        { // we already have a dialog for that opened... do not ask again
 
3966
          return;
 
3967
        }
 
3968
        // track that we will show the msgbox and we do not need to show it again if file changes once more and the dialog is still open
 
3969
        watcher_msgbox_=true;
 
3970
        QMessageBox msg_box;
 
3971
        QAbstractButton* ok = msg_box.addButton(QMessageBox::Ok);
 
3972
        msg_box.addButton(QMessageBox::Cancel);
 
3973
        msg_box.setWindowTitle("Layer data changed");
 
3974
        msg_box.setText((String("The data of file '") + filename + "' has changed.<BR>Update layers?").toQString());
 
3975
        msg_box.exec();
 
3976
        watcher_msgbox_=false;
 
3977
        if (msg_box.clickedButton() == ok)
 
3978
        {
 
3979
          user_wants_update = true;
 
3980
        }
 
3981
      }
 
3982
 
 
3983
      if (user_wants_update == false)
 
3984
      {
 
3985
        return;
 
3986
      }
 
3987
      else //if (user_wants_update == true)
 
3988
      {
 
3989
        const LayerData& layer = sw->canvas()->getLayer(layer_index);
 
3990
        // reload data
 
3991
        if (layer.type==LayerData::DT_PEAK) //peak data
 
3992
        {
 
3993
          try
 
3994
          {
 
3995
            FileHandler().loadExperiment(layer.filename,*layer.getPeakData());
 
3996
          }
 
3997
          catch(Exception::BaseException& e)
 
3998
          {
 
3999
            QMessageBox::critical(this,"Error",(String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
 
4000
            layer.getPeakData()->clear(true);
 
4001
          }
 
4002
          layer.getPeakData()->sortSpectra(true);
 
4003
          layer.getPeakData()->updateRanges(1);
 
4004
        }
 
4005
        else if (layer.type==LayerData::DT_FEATURE) //feature data
 
4006
        {
 
4007
          try
 
4008
          {
 
4009
            FileHandler().loadFeatures(layer.filename,*layer.getFeatureMap());
 
4010
          }
 
4011
          catch(Exception::BaseException& e)
 
4012
          {
 
4013
            QMessageBox::critical(this,"Error",(String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
 
4014
            layer.getFeatureMap()->clear(true);
 
4015
          }
 
4016
          layer.getFeatureMap()->updateRanges();
 
4017
        }
 
4018
        else if (layer.type==LayerData::DT_CONSENSUS)  //consensus feature data
 
4019
        {
 
4020
          try
 
4021
          {
 
4022
            ConsensusXMLFile().load(layer.filename,*layer.getConsensusMap());
 
4023
          }
 
4024
          catch(Exception::BaseException& e)
 
4025
          {
 
4026
            QMessageBox::critical(this,"Error",(String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
 
4027
            layer.getConsensusMap()->clear(true);
 
4028
          }
 
4029
          layer.getConsensusMap()->updateRanges();
 
4030
        }
 
4031
        else if (layer.type==LayerData::DT_CHROMATOGRAM) //chromatgram
 
4032
        {
 
4033
          //TODO CHROM
 
4034
          try
 
4035
          {
 
4036
            FileHandler().loadExperiment(layer.filename,*layer.getPeakData());
 
4037
          }
 
4038
          catch(Exception::BaseException& e)
 
4039
          {
 
4040
            QMessageBox::critical(this,"Error",(String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
 
4041
            layer.getPeakData()->clear(true);
 
4042
          }
 
4043
          layer.getPeakData()->sortChromatograms(true);
 
4044
          layer.getPeakData()->updateRanges(1);
 
4045
 
 
4046
        }
 
4047
        /*      else if (layer.type == LayerData::DT_IDENT) // identifications
 
4048
      {
 
4049
        try
 
4050
        {
 
4051
          vector<ProteinIdentification> proteins;
 
4052
          IdXMLFile().load(layer.filename, proteins, layer.peptides);
 
4053
        }
 
4054
        catch(Exception::BaseException& e)
 
4055
        {
 
4056
          QMessageBox::critical(this,"Error",(String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
 
4057
          layer.peptides.clear();
 
4058
        }
 
4059
      }
 
4060
*/
 
4061
      }
 
4062
 
 
4063
      // update all layers that need an update
 
4064
      for (Size i=0; i!= needs_update.size(); ++i)
 
4065
      {
 
4066
        pair<const SpectrumWidget *, Size>& slp = needs_update[i];
 
4067
        const SpectrumWidget * sw = slp.first;
 
4068
        Size layer_index = slp.second;
 
4069
        sw->canvas()->updateLayer(layer_index);
 
4070
      }
 
4071
    }
 
4072
    /*
 
4073
    {
 
4074
      //update the layer if the user choosed to do so
 
4075
      if (update)
 
4076
      {
 
4077
        emit sendStatusMessage(String("Updating layer '") + getLayer(j).name + "' (file changed).",0);
 
4078
        updateLayer_(j);
 
4079
        emit sendStatusMessage(String("Finished updating layer '") + getLayer(j).name + "'.",5000);
 
4080
      }
 
4081
    }
 
4082
    */
 
4083
    updateLayerBar();
 
4084
    updateViewBar();
 
4085
    updateFilterBar();
 
4086
    updateMenu();
 
4087
 
 
4088
    // temporarily remove and read filename from watcher_ as a workaround for bug #233
 
4089
    watcher_->removeFile(filename);
 
4090
    watcher_->addFile(filename);
 
4091
  }
 
4092
 
 
4093
  void TOPPViewBase::setTOPPASTabEnabled(bool enabled)
 
4094
  {
 
4095
    if (views_tabwidget_->isTabEnabled(2) != enabled)
 
4096
    {
 
4097
      views_tabwidget_->setTabEnabled(2, enabled);
 
4098
    }
 
4099
  }
 
4100
 
 
4101
  // ******************************************TOPPAS events**********************************
 
4102
  void TOPPViewBase::newPipeline()
 
4103
  {
 
4104
    TOPPASWidget* tw = new TOPPASWidget(Param(), ws_, toppas_tmp_path_);
 
4105
    TOPPASScene* ts = tw->getScene();
 
4106
    connect (ts, SIGNAL(selectionCopied(TOPPASScene*)), this, SLOT(saveToClipboard(TOPPASScene*)));
 
4107
    connect (ts, SIGNAL(requestClipboardContent()), this, SLOT(sendClipboardContent()));
 
4108
    connect (ts, SIGNAL(saveMe()), this, SLOT(savePipeline()));
 
4109
    connect (ts, SIGNAL(mainWindowNeedsUpdate()), this, SLOT(updateMenu()));
 
4110
    showTOPPipelineInWindow_(tw, "(Untitled)");
 
4111
  }
 
4112
 
 
4113
  void TOPPViewBase::includePipeline()
 
4114
  {
 
4115
    QString file_name = QFileDialog::getOpenFileName(this, tr("Include workflow"), current_path_.toQString(), tr("TOPPAS pipelines (*.toppas)"));
 
4116
    addTOPPASFile(file_name, false);
 
4117
  }
 
4118
 
 
4119
  void TOPPViewBase::savePipeline()
 
4120
  {
 
4121
    TOPPASWidget* w = 0;
 
4122
    QObject* sendr = QObject::sender();
 
4123
    QAction* save_button_clicked = qobject_cast<QAction*>(sendr);
 
4124
 
 
4125
    if (!save_button_clicked)
 
4126
    {
 
4127
      // scene has requested to be saved
 
4128
      TOPPASScene* ts = qobject_cast<TOPPASScene*>(sendr);
 
4129
      if (ts && ts->views().size() > 0)
 
4130
      {
 
4131
        w = qobject_cast<TOPPASWidget*>(ts->views().first());
 
4132
      }
 
4133
    }
 
4134
    else
 
4135
    {
 
4136
      w = getActiveTOPPASWidget();
 
4137
    }
 
4138
 
 
4139
    if (!w)
 
4140
    {
 
4141
      return;
 
4142
    }
 
4143
 
 
4144
    String file_name = w->getScene()->getSaveFileName();
 
4145
    if (file_name != "")
 
4146
    {
 
4147
      if (!file_name.hasSuffix(".toppas"))
 
4148
      {
 
4149
        file_name += ".toppas";
 
4150
      }
 
4151
      w->getScene()->store(file_name);
 
4152
    }
 
4153
    else
 
4154
    {
 
4155
      TOPPASBase::savePipelineAs(w, current_path_.toQString());
 
4156
    }
 
4157
  }
 
4158
 
 
4159
  void TOPPViewBase::saveCurrentPipelineAs()
 
4160
  {
 
4161
    TOPPASWidget* w = getActiveTOPPASWidget();
 
4162
    QString file_name = TOPPASBase::savePipelineAs(w, current_path_.toQString());
 
4163
    if (file_name != "")
 
4164
    {
 
4165
      QString caption = File::basename(file_name).toQString();
 
4166
      tab_bar_->setTabText(tab_bar_->currentIndex(), caption);
 
4167
    }
 
4168
  }
 
4169
 
 
4170
  void TOPPViewBase::loadPipelineResourceFile()
 
4171
  {
 
4172
    TOPPASWidget* w = getActiveTOPPASWidget();
 
4173
    TOPPASBase::loadPipelineResourceFile(w, current_path_.toQString());
 
4174
  }
 
4175
 
 
4176
  void TOPPViewBase::savePipelineResourceFile()
 
4177
  {
 
4178
    TOPPASWidget* w = getActiveTOPPASWidget();
 
4179
    TOPPASBase::savePipelineResourceFile(w, current_path_.toQString());
 
4180
  }
 
4181
 
 
4182
  void TOPPViewBase::refreshPipelineParameters()
 
4183
  {
 
4184
    TOPPASWidget* w = getActiveTOPPASWidget();
 
4185
    QString file_name = TOPPASBase::refreshPipelineParameters(w, current_path_.toQString());
 
4186
    if (file_name != "")
 
4187
    {
 
4188
      QString caption = File::basename(file_name).toQString();
 
4189
      tab_bar_->setTabText(tab_bar_->currentIndex(), caption);
 
4190
    }
 
4191
  }
 
4192
 
 
4193
  void TOPPViewBase::runPipeline()
 
4194
  {
 
4195
    TOPPASWidget* w = getActiveTOPPASWidget();
 
4196
    if (w)
 
4197
    {
 
4198
      w->getScene()->runPipeline();
 
4199
    }
 
4200
  }
 
4201
 
 
4202
  void TOPPViewBase::abortPipeline()
 
4203
  {
 
4204
    TOPPASWidget* w = getActiveTOPPASWidget();
 
4205
    if (w)
 
4206
    {
 
4207
      w->getScene()->abortPipeline();
 
4208
    }
 
4209
    updateMenu();
 
4210
  }
 
4211
 
 
4212
  void TOPPViewBase::showPipelineFinishedLogMessage()
 
4213
  {
 
4214
    showLogMessage_(LS_NOTICE, "Entire pipeline execution finished!", "");
 
4215
  }
 
4216
 
 
4217
  void TOPPViewBase::saveToClipboard(TOPPASScene* scene)
 
4218
  {
 
4219
    if (toppas_clipboard_scene_ != 0)
 
4220
    {
 
4221
      delete toppas_clipboard_scene_;
 
4222
      toppas_clipboard_scene_ = 0;
 
4223
    }
 
4224
    toppas_clipboard_scene_ = scene;
 
4225
  }
 
4226
 
 
4227
  void TOPPViewBase::sendClipboardContent()
 
4228
  {
 
4229
    TOPPASScene* sndr = qobject_cast<TOPPASScene*>(QObject::sender());
 
4230
    if (sndr != 0)
 
4231
    {
 
4232
      sndr->setClipboard(toppas_clipboard_scene_);
 
4233
    }
 
4234
  }
 
4235
 
 
4236
  void TOPPViewBase::toolStarted()
 
4237
  {
 
4238
    TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(QObject::sender());
 
4239
    if (tv)
 
4240
    {
 
4241
      String text = tv->getName();
 
4242
      String type = tv->getType();
 
4243
      if (type != "")
 
4244
      {
 
4245
        text += " ("+type+")";
 
4246
      }
 
4247
      text += " started. Processing ...";
 
4248
 
 
4249
      showLogMessage_(LS_NOTICE, text, "");
 
4250
    }
 
4251
    updateMenu();
 
4252
  }
 
4253
 
 
4254
  void TOPPViewBase::toolFinished()
 
4255
  {
 
4256
    TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(QObject::sender());
 
4257
    if (tv)
 
4258
    {
 
4259
      String text = tv->getName();
 
4260
      String type = tv->getType();
 
4261
      if (type != "")
 
4262
      {
 
4263
        text += " ("+type+")";
 
4264
      }
 
4265
      text += " finished!";
 
4266
 
 
4267
      showLogMessage_(LS_NOTICE, text, "");
 
4268
    }
 
4269
    updateMenu();
 
4270
  }
 
4271
 
 
4272
  void TOPPViewBase::toolCrashed()
 
4273
  {
 
4274
    TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(QObject::sender());
 
4275
    if (tv)
 
4276
    {
 
4277
      String text = tv->getName();
 
4278
      String type = tv->getType();
 
4279
      if (type != "")
 
4280
      {
 
4281
        text += " ("+type+")";
 
4282
      }
 
4283
      text += " crashed!";
 
4284
 
 
4285
      showLogMessage_(LS_ERROR, text, "");
 
4286
    }
 
4287
    updateMenu();
 
4288
  }
 
4289
 
 
4290
  void TOPPViewBase::toolFailed()
 
4291
  {
 
4292
    TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(QObject::sender());
 
4293
    if (tv)
 
4294
    {
 
4295
      String text = tv->getName();
 
4296
      String type = tv->getType();
 
4297
      if (type != "")
 
4298
      {
 
4299
        text += " ("+type+")";
 
4300
      }
 
4301
      text += " failed!";
 
4302
 
 
4303
      showLogMessage_(LS_ERROR, text, "");
 
4304
    }
 
4305
    updateMenu();
 
4306
  }
 
4307
 
 
4308
  void TOPPViewBase::outputVertexFinished(const String& file)
 
4309
  {
 
4310
    String text = "Output file '" + file + "' written.";
 
4311
    showLogMessage_(LS_NOTICE, text, "");
 
4312
  }
 
4313
 
 
4314
  void TOPPViewBase::updateTOPPOutputLog(const QString& out)
 
4315
  {
 
4316
    QString text = out; // shortened version for now (if we reintroduce simultaneous tool execution,
 
4317
                        // we need to rethink this (probably only trigger this slot when tool 100% finished)
 
4318
 
 
4319
    //show log if there is output
 
4320
    qobject_cast<QWidget*>(log_->parent())->show();
 
4321
 
 
4322
    //update log_
 
4323
    log_->append(text);
 
4324
  }
 
4325
 
 
4326
  void TOPPViewBase::openFilesInTOPPView(QStringList files)
 
4327
  {
 
4328
    foreach(QString s, files)
 
4329
    {
 
4330
      addDataFile(s, false, false, s);
 
4331
    }
 
4332
  }
 
4333
 
 
4334
  //
 
4335
 
 
4336
  TOPPViewBase::~TOPPViewBase()
 
4337
  {
 
4338
    savePreferences();
 
4339
    abortTOPPTool();
 
4340
 
 
4341
    // dispose behavior
 
4342
    if(identificationview_behavior_ != 0)
 
4343
    {
 
4344
      delete(identificationview_behavior_);
 
4345
    }
 
4346
 
 
4347
    if(spectraview_behavior_ != 0)
 
4348
    {
 
4349
      delete(spectraview_behavior_);
 
4350
    }
 
4351
  }
 
4352
 
 
4353
} //namespace OpenMS