keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/Plot1DPrefDialog.h | .h | 858 | 40 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
namespace Ui
{
class Plot1DPrefDialogTemplate;
}
namespace OpenMS
{
namespace Internal
{
///Preferences dialog for Plot1DWidget
class OPENMS_GUI_DLLAPI Plot1DPrefDialog :
public QDialog
{
Q_OBJECT
public:
///Constructor
Plot1DPrefDialog(QWidget * parent);
~Plot1DPrefDialog() override;
private:
Ui::Plot1DPrefDialogTemplate* ui_;
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/Plot2DPrefDialog.h | .h | 858 | 40 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
namespace Ui
{
class Plot2DPrefDialogTemplate;
}
namespace OpenMS
{
namespace Internal
{
///Preferences dialog for Plot2DWidget
class OPENMS_GUI_DLLAPI Plot2DPrefDialog :
public QDialog
{
Q_OBJECT
public:
///Constructor
Plot2DPrefDialog(QWidget * parent);
~Plot2DPrefDialog() override;
private:
Ui::Plot2DPrefDialogTemplate* ui_;
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/DataFilterDialog.h | .h | 1,480 | 62 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <OpenMS/PROCESSING/MISC/DataFilters.h>
#include <QDialog>
namespace Ui
{
class DataFilterDialogTemplate;
}
namespace OpenMS
{
/**
@brief Dialog for creating and changing a DataFilter
*/
class OPENMS_GUI_DLLAPI DataFilterDialog :
public QDialog
{
Q_OBJECT
public:
/// constructor
DataFilterDialog(DataFilters::DataFilter & filter, QWidget * parent);
/// destructor
virtual ~DataFilterDialog();
protected slots:
/// Checks if the settings are valid and writes them to filter_ if so
void check_();
/// Is called when field_ changes and enables/disables the meta data functionality as needed
void field_changed_(const QString &);
/// Is called when op_ changes and disables the value field, if operation is "exists", else enables it
void op_changed_(const QString &);
protected:
/// Reference to the filter that is modified
DataFilters::DataFilter & filter_;
private:
/// Not implemented
DataFilterDialog();
Ui::DataFilterDialogTemplate* ui_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/TOPPASIOMappingDialog.h | .h | 1,680 | 70 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtCore/QVector>
#include <QtWidgets/QDialog>
namespace Ui
{
class TOPPASIOMappingDialogTemplate;
}
namespace OpenMS
{
class TOPPASEdge;
/**
@brief Dialog which allows to configure the input/output parameter mapping of an edge.
This dialog allows to select an output parameter of the source vertex and an input
parameter of the target vertex. Only valid selections are allowed, i.e. the type
(file or list of files) and at least one valid file type of either vertex must match.
@ingroup TOPPAS_elements
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI TOPPASIOMappingDialog :
public QDialog
{
Q_OBJECT
public:
/// Constructor
TOPPASIOMappingDialog(TOPPASEdge * parent);
~TOPPASIOMappingDialog() override;
public slots:
/// Called instead of exec() after edge is constructed (in order to avoid showing the dialog if not necessary)
int firstExec();
protected:
/// Fills the table
void fillComboBoxes_();
/// The edge we are configuring
TOPPASEdge * edge_;
protected slots:
/// Called when OK is pressed; checks if the selected parameters are valid
void checkValidity_();
private:
Ui::TOPPASIOMappingDialogTemplate* ui_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/PythonModuleRequirement.h | .h | 2,156 | 69 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QWidget>
namespace Ui
{
class PythonModuleRequirement;
}
namespace OpenMS
{
namespace Internal
{
/// Given a list of python modules which are required, this widget checks them and
/// displays the current status
class OPENMS_GUI_DLLAPI PythonModuleRequirement : public QWidget
{
Q_OBJECT
public:
explicit PythonModuleRequirement(QWidget* parent = nullptr);
~PythonModuleRequirement();
/// change the label of the surrounding box
void setTitle(const QString& title);
/// a list of python modules required for a certain functionality/script
void setRequiredModules(const QStringList& m);
/// some arbitrary description for the user to display statically
void setFreeText(const QString& text);
/// are all modules present?
bool isReady() const { return is_ready_;};
signals:
/// emitted whenever the requirement check was executed...
void valueChanged(QStringList& valid_modules, QStringList& missing_modules);
public slots:
/// re-evaluate the presence of modules, based on a new python version
void validate(const QString& python_exe);
private:
QStringList required_modules_; ///< list of modules which are needed (order might be important -- know your Python...)
QString info_text_; ///< additional text to display for the user
bool is_ready_ = false; ///< all modules are present and the app is good to go
Ui::PythonModuleRequirement* ui_;
};
} // ns Internal
} // ns OpenMS
// this is required to allow Ui_SwathTabWidget (auto UIC'd from .ui) to have a PythonModuleRequirement member
using PythonModuleRequirement = OpenMS::Internal::PythonModuleRequirement;
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/SaveImageDialog.h | .h | 1,734 | 69 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QCheckBox>
namespace OpenMS
{
/**
@brief Dialog for saving an image.
@image html SaveImageDialog.png
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI SaveImageDialog :
public QDialog
{
Q_OBJECT
public:
///Constructor
SaveImageDialog(QWidget * parent = nullptr);
///set size and size ratio
void setSize(int x, int y);
///accessors for the width
int getXSize();
///accessors for the height
int getYSize();
///accessors for the format
QString getFormat();
public slots:
///changes width keeping proportions
void xSizeChanged(const QString & s);
///changes height keeping proportions
void ySizeChanged(const QString & s);
///set size ratio when proportions checkbox is activated
void proportionsActivated(bool state);
///checks if the values for width and height are ok before accepting the dialog
void checkSize();
private:
//format
QComboBox * format_;
//size
QLineEdit * size_x_;
QLineEdit * size_y_;
QCheckBox * size_proportions_;
//ratio size_x_/size_y_
float size_ratio_;
//set the size ratio (width/height)
void setSizeRatio_(float r);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/ToolsDialog.h | .h | 4,801 | 138 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/VISUAL/LayerDataBase.h>
class QLabel;
class QComboBox;
class QPushButton;
class QString;
#include <QtWidgets/QDialog>
namespace OpenMS
{
class ParamEditor;
class TVToolDiscovery;
/**
@brief TOPP tool selection dialog
In the dialog, the user can
- select a TOPP tool
- select the options used for the input and output file
- and set the parameters for the tool
This information can then be used to execute the tool.
The offered tools depend on the data type set in the constructor.
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI ToolsDialog :
public QDialog
{
Q_OBJECT
public:
/**
@brief Constructor
@param[in] parent Qt parent widget
@param[in] params Containing all TOPP tool/util params
@param[in] ini_file The file name of the temporary INI file created by this dialog
@param[in] default_dir The default directory for loading and storing INI files
@param[in] layer_type The type of data (determines the applicable tools)
@param[in] layer_name The name of the selected layer
@param[in] tool_scanner Pointer to the tool scanner for access to the plugins and to rerun the plugins detection
*/
ToolsDialog(QWidget * parent, const Param& params, String ini_file, String default_dir, LayerDataBase::DataType layer_type, const String& layer_name, TVToolDiscovery* tool_scanner);
///Destructor
~ToolsDialog() override;
/// to get the parameter name for output. Empty if no output was selected.
String getOutput();
/// to get the parameter name for input
String getInput();
/// to get the currently selected tool-name
String getTool();
/// get the default extension for the output file
String getExtension();
private:
/// ParamEditor for reading ini-files
ParamEditor * editor_;
/// tools description label
QLabel * tool_desc_;
/// ComboBox for choosing a TOPP-tool
QComboBox * tools_combo_;
/// Button to rerun the automatic plugin detection
QPushButton* reload_plugins_button_;
/// for choosing an input parameter
QComboBox * input_combo_;
/// for choosing an output parameter
QComboBox * output_combo_;
/// Param for loading the ini-file
Param arg_param_;
/// Param for loading configuration information in the ParamEditor
Param vis_param_;
/// ok-button connected with slot ok_()
QPushButton * ok_button_;
/// Location of the temporary INI file this dialog works on
String ini_file_;
/// default-dir of ini-file to open
String default_dir_;
/// name of ini-file
QString filename_;
/// Mapping of file extension to layer type to determine the type of a tool
std::map<String, LayerDataBase::DataType> tool_map_;
/// Param object containing all TOPP tool/util params
Param tool_params_;
/// Param object containing all plugin params
Param plugin_params_;
/// Pointer to the tool scanner for access to the plugins and to rerun the plugins detection
TVToolDiscovery* tool_scanner_;
/// The layer type of the current layer to determine all usable plugins
LayerDataBase::DataType layer_type_;
/// Disables the ok button and input/output comboboxes
void disable_();
/// Enables the ok button and input/output comboboxes
void enable_();
/// Determine all types a tool is compatible with by mapping each file extensions in a tools param
std::vector<LayerDataBase::DataType> getTypesFromParam_(const Param& p) const;
/// Fill input_combo_ and output_combo_ box with the appropriate entries from the specified param object.
void setInputOutputCombo_(const Param& p);
/// Create a list of all TOPP tool/util/plugins that are compatible with the active layer type
QStringList createToolsList_();
protected slots:
/// if ok button pressed show the tool output in a new layer, a new window or standard output as messagebox
void ok_();
/// Slot that handles changing of the tool
void setTool_(int i);
/// Slot that retrieves and displays the defaults
void createINI_();
/// loads an ini-file into the editor
void loadINI_();
/// stores an ini-file from the editor
void storeINI_();
/// rerun the automatic plugin detection
void reloadPlugins_();
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/PythonSelector.h | .h | 1,844 | 65 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QWidget>
namespace Ui
{
class PythonSelector;
}
namespace OpenMS
{
namespace Internal
{
/// A QLineEdit + Browse button to have the user select a local python installation
/// By default, 'python' is used
class OPENMS_GUI_DLLAPI PythonSelector : public QWidget
{
Q_OBJECT
public:
explicit PythonSelector(QWidget* parent = nullptr);
~PythonSelector();
const String& getLastPython() const
{
return last_known_python_exe_;
}
signals:
/// emitted whenever the line-edit has new values for the current python executable
/// @param[in] last_known_python_exe The currently best guess where python can be found
/// @param[in] valid_python Is the python executable given in @p last_known_python_exe callable?
void valueChanged(QString last_known_python_exe, bool valid_python);
private slots:
void showFileDialog_();
void validate_();
private:
String last_known_python_exe_ = "python"; ///< initial guess or last valid user input
bool currently_valid_ = false; ///< unless proven otherwise by 'validate_()'
Ui::PythonSelector* ui_;
};
}
} // ns OpenMS
// this is required to allow Ui_SwathTabWidget (auto UIC'd from .ui) to have a PythonSelector member
using PythonSelector = OpenMS::Internal::PythonSelector;
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/TOPPASOutputFilesDialog.h | .h | 1,436 | 64 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
namespace Ui
{
class TOPPASOutputFilesDialogTemplate;
}
namespace OpenMS
{
class OutputDirectory;
/**
@brief Dialog which allows to specify the directory for the output files
@ingroup TOPPAS_elements
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI TOPPASOutputFilesDialog :
public QDialog
{
Q_OBJECT
public:
/// Constructor
TOPPASOutputFilesDialog(const QString& dir_name, int num_jobs);
~TOPPASOutputFilesDialog() override;
/// Returns the name of the directory
QString getDirectory() const;
/// Returns the maximum number of jobs in the spinbox
int getNumJobs() const;
public slots:
/// Lets the user select the directory via a file dialog
void showFileDialog();
protected slots:
/// Called when OK is pressed; checks if the selected file is valid
void checkValidity_();
private:
Ui::TOPPASOutputFilesDialogTemplate* ui_;
};
}
using OutputDirectory = OpenMS::OutputDirectory;
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/SwathTabWidget.h | .h | 4,362 | 122 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/VISUAL/MISC/ExternalProcessMBox.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/TableView.h>
#include <QTabWidget> // our base class
#include <vector>
#include <utility> // for std::pair
namespace Ui
{
class SwathTabWidget;
}
namespace OpenMS
{
class InputFile;
class OutputDirectory;
class ParamEditor;
namespace Internal
{
class SwathTabWidget;
/// A multi-tabbed widget for the SwathWizard offering setting of parameters, input-file specification and running Swath and more
class OPENMS_GUI_DLLAPI SwathTabWidget : public QTabWidget
{
Q_OBJECT
public:
template <typename> friend class WizardGUILock;
explicit SwathTabWidget(QWidget *parent = nullptr);
~SwathTabWidget();
StringList getMzMLInputFiles() const;
QStringList getPyProphetOutputFileNames() const;
private slots:
void on_run_swath_clicked();
void on_edit_advanced_parameters_clicked();
/// update the current working directory for all file input fields
void broadcastNewCWD_(const QString& new_cwd);
void on_btn_runPyProphet_clicked();
void on_btn_pyresults_clicked();
void on_pushButton_clicked();
private:
/// find the path of a Script, given the location of python(.exe). E.g. pyprophet.exe or feature_alignment.py
/// Returns true on success, with the full path in @p script_name
bool findPythonScript_(const String& path_to_python_exe, String& script_name);
/// collect all parameters throughout the Wizard's controls and update 'swath_param_'
void updateSwathParamFromWidgets_();
/// update Widgets given a param object
void updateWidgetsfromSwathParam_();
/// where to write OSW output and pyProphet output
QString getCurrentOutDir_() const;
/// translate the current list of input mzMLs and the current output directory of OSW to a list of expected OSW output files == pyProphet input files
/// The bool indicates if the file is already present
std::vector<std::pair<String, bool>> getPyProphetInputFiles() const;
/// check if input to pyProphet is already present in the output directory of OSW
void checkPyProphetInput_();
/// fill osw_result_files_ according to the the currently specified input mzMLs
/// append text to the log tab
/// @param[in] text The text to write
/// @param[in] color Color of the text
/// @param[in] new_section Start a new block with a date and time
void writeLog_(const QString& text, const QColor& color = "#000000", bool new_section = false);
/// @brief convenient overload for String
void writeLog_(const String& text, const QColor& color = "#000000", bool new_section = false);
/// Ensure all input widgets are filled with data by the user to run OpenSwathWorkflow
/// If anything is missing: show a Messagebox and return false.
bool checkOSWInputReady_();
Ui::SwathTabWidget *ui;
Param swath_param_; ///< the global Swath parameters which will be passed to OpenSwathWorkflow.exe, once updated with parameters the Wizard holds separately
Param swath_param_wizard_; ///< small selection of important parameters which the user can directly change in the Wizard
StringList osw_result_files_; ///< list of .osw files produced by OSW which are currently available
ExternalProcessMBox ep_; ///< to run external programs and pipe their output into our log
};
}
} // ns OpenMS
// this is required to allow Ui_SwathTabWidget (auto UIC'd from .ui) to have a InputFile member
using InputFile = OpenMS::InputFile;
using OutputDirectory = OpenMS::OutputDirectory;
using ParamEditor = OpenMS::ParamEditor;
using TableView = OpenMS::TableView;
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/HistogramDialog.h | .h | 1,424 | 59 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
#include <OpenMS/MATH/STATISTICS/Histogram.h>
#include <OpenMS/VISUAL/HistogramWidget.h>
namespace OpenMS
{
/**
@brief Dialog that show a HistogramWidget.
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI HistogramDialog :
public QDialog
{
Q_OBJECT
public:
/// Constructor
HistogramDialog(const Math::Histogram<> & distribution, QWidget * parent = nullptr);
/// Destructor
~HistogramDialog() override;
/// Returns the value of the left splitter
float getLeftSplitter();
/// Returns the value of the right splitter
float getRightSplitter();
/// Sets the value of the left splitter
void setLeftSplitter(float position);
/// Sets the value of the right splitter
void setRightSplitter(float position);
/// Sets the axis legend
void setLegend(const String & legend);
/// Sets log mode
void setLogMode(bool log_mode);
protected:
HistogramWidget * mw_;
};
} //namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/TheoreticalSpectrumGenerationDialog.h | .h | 3,664 | 132 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Tom Waschischeck $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
#include <QtWidgets/qspinbox.h>
#include <QtWidgets/qlabel.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <array>
namespace Ui
{
class TheoreticalSpectrumGenerationDialogTemplate;
}
class QListWidgetItem;
namespace OpenMS
{
class TestTSGDialog; // fwd declaring test class
/// state of an ion (and its intensity)
enum class CheckBoxState
{
HIDDEN, ///< check box hidden (invisible)
ENABLED, ///< check box enabled (visible, but not checked)
PRECHECKED ///< check box enabled and checked by default
};
/**
@brief Dialog which allows to enter an AA or NA sequence and generates a theoretical spectrum for it.
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI TheoreticalSpectrumGenerationDialog :
public QDialog
{
Q_OBJECT
public:
/// struct for all information about a check box of an ion
struct CheckBox {
/// Constructor
CheckBox(QDoubleSpinBox** sb, QLabel** l, std::array<CheckBoxState, 3> s, std::pair<String, String> p_t, std::pair<String, String> p_s);
/// pointer to the corresponding ion intensity spin box
QDoubleSpinBox** ptr_to_spin_box;
/// pointer to the label of the spin box
QLabel** ptr_to_spin_label;
/// State of this check box depending on sequence type ("Peptide", "RNA", "Metabolite")
const std::array<CheckBoxState, 3> state;
/// parameter with description of this ion
const std::pair<String, String> param_this;
/// parameter with description of the ion intensity
const std::pair<String, String> param_spin;
};
/// type of the input sequence (corresponds to the value of the combo box 'ui_->seq_type')
enum class SequenceType
{
PEPTIDE,
RNA,
METABOLITE
};
friend class TestTSGDialog; // to test the GUI expressed in the private member ui
/// Constructor
TheoreticalSpectrumGenerationDialog();
/// Destructor
~TheoreticalSpectrumGenerationDialog() override;
/// returns the calculated spectrum
const MSSpectrum& getSpectrum() const;
/// returns the input sequence (is public for TOPPView)
const String getSequence() const;
protected slots:
/// for isotope model changes
void modelChanged_();
/// for sequence type changes (combo box)
void seqTypeSwitch_();
/// change check state of check box on widget click
void listWidgetItemClicked_(QListWidgetItem* item);
/// calculates the spectrum
void calculateSpectrum_();
protected:
private:
/// calculate parameters from UI elements
Param getParam_() const;
/// iterates through 'check_boxes_' and en-/disables
/// check boxes and corresponding spin boxes (and their labels)
void updateIonTypes_();
/// UI
Ui::TheoreticalSpectrumGenerationDialogTemplate* ui_;
/// save current sequence setting
SequenceType seq_type_;
/// array of TSGDialog::CheckBox
///
/// Note: Ordering has to be the same as in the UI!
const std::array<CheckBox, 12> check_boxes_;
/// member to save the calculated spectrum to
MSSpectrum spec_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/Plot3DPrefDialog.h | .h | 862 | 40 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
namespace Ui
{
class Plot3DPrefDialogTemplate;
}
namespace OpenMS
{
namespace Internal
{
///Preferences dialog for Plot3DWidget
class OPENMS_GUI_DLLAPI Plot3DPrefDialog :
public QDialog
{
Q_OBJECT
public:
///Constructor
Plot3DPrefDialog(QWidget * parent);
~Plot3DPrefDialog() override;
private:
Ui::Plot3DPrefDialogTemplate* ui_;
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/TOPPASToolConfigDialog.h | .h | 2,562 | 87 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/String.h>
class QComboBox;
class QPushButton;
class QRadioButton;
class QString;
#include <QtWidgets/QDialog>
namespace OpenMS
{
class ParamEditor;
/**
@brief TOPP tool configuration dialog
In the dialog, the user can set the parameters for the tool
This information can then be used to execute the tool.
@ingroup TOPPAS_elements
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI TOPPASToolConfigDialog :
public QDialog
{
Q_OBJECT
public:
/**
@brief Constructor
@param[in] parent Qt parent widget
@param[in] param The param we are editing
@param[in] default_dir The default directory for loading and storing INI files
@param[in] tool_name The name of the TOPP tool (used to invoke it on the commandline)
@param[in] tool_type The type of the tool ('-type' parameter of TOPP tool on the commandline). Leave empty if no type exists.
@param[in] tool_desc The tool description
@param[in] hidden_entries List of entries that are used already in edges etc and should not be shown
*/
TOPPASToolConfigDialog(QWidget * parent, Param & param, const String& default_dir, const String& tool_name, const String& tool_type, const String& tool_desc, const QVector<String>& hidden_entries);
///Destructor
~TOPPASToolConfigDialog() override;
private:
/// ParamEditor for reading ini-files
ParamEditor * editor_;
/// The param we are editing
Param * param_;
/// Param for loading the ini-file
Param arg_param_;
/// default-dir of ini-file to open
String default_dir_;
/// name of ini-file
QString filename_;
/// The name of the tool
String tool_name_;
/// The type of the tool
String tool_type_;
/// The parameters already explained by in edges
QVector<String> hidden_entries_;
protected slots:
/// Slot for OK button
void ok_();
/// loads an ini-file into the editor_
void loadINI_();
/// stores an ini-file from the editor_
void storeINI_();
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/ListFilterDialog.h | .h | 2,378 | 81 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QDialog>
namespace Ui
{
class ListFilterDialog;
}
namespace OpenMS
{
/**
@brief Dialog for creating and changing a DataFilter
*/
class OPENMS_GUI_DLLAPI ListFilterDialog :
public QDialog
{
Q_OBJECT
public:
/// constructor
ListFilterDialog() = delete;
/**
@brief C'tor with items to show and select from
@param[in] parent Parent widget
@param[in] items A set of strings to show and select from. Can be filtered in the dialog
@param[in] items_prechosen A set of strings which are already chosen (on the right side) when first showing this dialog. This must be a subset of @p items
@throws Exception::InvalidValue if any of @p items_prechosen is not contained in @p items
**/
ListFilterDialog(QWidget* parent, const QStringList& items = QStringList(), const QStringList& items_prechosen = QStringList());
/// destructor
virtual ~ListFilterDialog();
/// when pressing 'X' button in corner of the Window
void closeEvent(QCloseEvent* event) override;
/// A set of strings to show and select from. Can be filtered in the dialog
/// @throws Exception::InvalidValue if any of @p items_prechosen is not contained in @p items
void setItems(const QStringList& items);
/// A set of strings which are already chosen (on the right side). Overwrites the currently chosen set.
/// @throws Exception::InvalidValue if any of @p items_prechosen is not contained in @p items
void setPrechosenItems(const QStringList& items_prechosen);
/// get all items which where selected by the user
QStringList getChosenItems() const;
protected slots:
/// button '>>' clicked
void BtnLRClicked_();
/// button '> ALL >' clicked
void BtnLRAllClicked_();
/// button '<<' clicked
void BtnRLClicked_();
/// button '< ALL <' clicked
void BtnRLAllClicked_();
private:
Ui::ListFilterDialog* ui_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/TOPPASInputFilesDialog.h | .h | 1,440 | 61 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
namespace Ui
{
class TOPPASInputFilesDialogTemplate;
}
namespace OpenMS
{
namespace Internal
{
class InputFileList;
}
/**
@brief Dialog which allows to specify a list of input files
@ingroup TOPPAS_elements
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI TOPPASInputFilesDialog :
public QDialog
{
Q_OBJECT
public:
/// Constructor
TOPPASInputFilesDialog(QWidget* parent)
: TOPPASInputFilesDialog(QStringList(), "", parent) {}
TOPPASInputFilesDialog(const QStringList& list, const QString& cwd, QWidget* parent = 0);
~TOPPASInputFilesDialog() override;
void getFilenames(QStringList& files) const;
const QString& getCWD() const;
private:
Ui::TOPPASInputFilesDialogTemplate* ui_;
Internal::InputFileList* ifl_;
};
}
// this is required to allow Ui_SwathTabWidget (auto UIC'd from .ui) to have a TOPPASInputFilesDialog member
using TOPPASInputFilesDialog = OpenMS::TOPPASInputFilesDialog;
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/LayerStatisticsDialog.h | .h | 1,239 | 54 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QDialog>
#include <memory> // for unique_ptr
namespace Ui
{
class LayerStatisticsDialogTemplate;
}
namespace OpenMS
{
class LayerStatistics;
class PlotWidget;
class PlotCanvas;
/**
@brief Dialog showing statistics about the data of the current layer
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI LayerStatisticsDialog :
public QDialog
{
Q_OBJECT
public:
/// Constructor not implemented
LayerStatisticsDialog() = delete;
/// Custom constructor
LayerStatisticsDialog(PlotWidget* parent, std::unique_ptr<LayerStatistics>&& stats);
/// D'tor
~LayerStatisticsDialog() override;
protected:
/// The statistics of the layer
std::unique_ptr<LayerStatistics> stats_;
private:
Ui::LayerStatisticsDialogTemplate* ui_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/SpectrumAlignmentDialog.h | .h | 1,430 | 63 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <QtWidgets/QDialog>
namespace Ui
{
class SpectrumAlignmentDialogTemplate;
}
namespace OpenMS
{
class Plot1DWidget;
/**
@brief Lets the user select two spectra and set the parameters for the spectrum alignment.
@ingroup Dialogs
*/
class SpectrumAlignmentDialog :
public QDialog
{
Q_OBJECT
public:
/// Constructor
SpectrumAlignmentDialog(Plot1DWidget * parent);
~SpectrumAlignmentDialog() override;
double getTolerance() const;
bool isPPM() const;
/// Returns the index of the selected non-flipped layer
Int get1stLayerIndex();
/// Returns the index of the selected flipped layer
Int get2ndLayerIndex();
protected slots:
protected:
/// Stores the layer indices of the layers in the left list (non-flipped layers)
std::vector<UInt> layer_indices_1_;
/// Stores the layer indices of the layers in the right list (flipped layers)
std::vector<UInt> layer_indices_2_;
private:
Ui::SpectrumAlignmentDialogTemplate* ui_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/Plot1DGoToDialog.h | .h | 1,438 | 65 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <OpenMS/CONCEPT/Types.h>
#include <QtWidgets/QDialog>
namespace Ui
{
class Plot1DGoToDialogTemplate;
}
namespace OpenMS
{
/**
@brief simple goto/set visible area dialog for exact placement of the viewing window
@ingroup Dialogs
*/
class OPENMS_GUI_DLLAPI Plot1DGoToDialog :
public QDialog
{
Q_OBJECT
public:
///Constructor
Plot1DGoToDialog(QWidget * parent = nullptr);
///Destructor
~Plot1DGoToDialog() override;
///Sets the m/z range displayed initially
void setRange(float min, float max);
///Sets the m/z range displayed initially
void setMinMaxOfRange(float min, float max);
bool checked();
/// Fixes the currently stored range (i.e. ensure correct order of min-max; enforce minimum of 1 Da window IFF min==max
void fixRange();
///Returns the lower m/z bound
float getMin() const;
///Returns the upper m/z bound
float getMax() const;
private:
Ui::Plot1DGoToDialogTemplate* ui_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/WizardHelper.h | .h | 3,826 | 110 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Jihyung Kim $
// $Authors: Jihyung Kim, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
namespace OpenMS
{
class InputFile;
class OutputDirectory;
class ParamEditor;
namespace Internal
{
/**
@brief RAII class to switch to certain TabWidget, disable the GUI and go back to the orignal Tab when this class is destroyed
*/
template<class TWidgetClass>
class WizardGUILock
{
public:
WizardGUILock(TWidgetClass* stw):
stw_(stw),
old_(stw->currentWidget()),
glock_(stw)
{
stw->setCurrentWidget(stw->ui->tab_log);
}
~WizardGUILock()
{
stw_->setCurrentWidget(old_);
}
private:
TWidgetClass* stw_;
QWidget* old_;
GUIHelpers::GUILock glock_;
};
/// custom arguments to allow for looping calls
struct Args
{
QStringList loop_arg; ///< list of arguments to insert; one for every loop
size_t insert_pos; ///< where to insert in the target argument list (index is 0-based)
};
typedef std::vector<Args> ArgLoop;
/// Allows running an executable with arguments
/// Multiple execution in a loop is supported by the ArgLoop argument
/// e.g. running 'ls -la .' and 'ls -la ..'
/// uses Command("ls", QStringList() << "-la" << "%1", ArgLoop{ Args {QStringList() << "." << "..", 1 } })
/// All lists in loop[i].loop_arg should have the same size (i.e. same number of loops)
struct Command
{
String exe;
QStringList args;
ArgLoop loop;
Command(const String& e, const QStringList& a, const ArgLoop& l) :
exe(e),
args(a),
loop(l) {}
/// how many loops can we make according to the ArgLoop provided?
/// if ArgLoop is empty, we just do a single invokation
size_t getLoopCount() const
{
if (loop.empty()) return 1;
size_t common_size = loop[0].loop_arg.size();
for (const auto& l : loop)
{
if (l.loop_arg.size() != (int)common_size) throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Internal error. Not all loop arguments support the same number of loops!");
if ((int)l.insert_pos >= args.size()) throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Internal error. Loop argument wants to insert after end of template arguments!");
}
return common_size;
}
/// for a given loop, return the substituted arguments
/// @p loop_number of 0 is always valid, i.e. no loop args, just use the unmodified args provided
QStringList getArgs(const int loop_number) const
{
if (loop_number >= (int)getLoopCount())
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Internal error. The loop number you requested is too high!");
}
if (loop.empty()) return args; // no looping available
QStringList arg_l = args;
for (const auto& largs : loop) // replace all args for the current round
{
arg_l[largs.insert_pos] = args[largs.insert_pos].arg(largs.loop_arg[loop_number]);
}
return arg_l;
}
};
}
} // ns OpenMS
// this is required to allow Ui_[tool_name]TabWidget (auto UIC'd from .ui) to have a InputFile member
using InputFile = OpenMS::InputFile;
using OutputDirectory = OpenMS::OutputDirectory;
using ParamEditor = OpenMS::ParamEditor;
using TableView = OpenMS::TableView;
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/TOPPViewOpenDialog.h | .h | 2,504 | 85 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <OpenMS/CONCEPT/Types.h>
#include <QtWidgets/QDialog>
#include <map>
class QAbstractButton;
namespace Ui
{
class TOPPViewOpenDialogTemplate;
}
namespace OpenMS
{
class Param;
class String;
/**
@brief Dataset opening options for TOPPView
@ingroup TOPPView_elements
*/
class OPENMS_GUI_DLLAPI TOPPViewOpenDialog :
public QDialog
{
Q_OBJECT
public:
/// Constructor
TOPPViewOpenDialog(const String & data_name, bool as_window, bool as_2d, bool cutoff, QWidget * parent = nullptr);
/// Destructor
~TOPPViewOpenDialog() override;
/// Returns true, if 2D mode is to be used for maps
bool viewMapAs2D() const;
/// Returns true, if 1D mode is to be used for maps
bool viewMapAs1D() const;
/// Returns if the low intensity peaks should be hidden
bool isCutoffEnabled() const;
/// Returns if the data is DIA / SWATH-MS data
bool isDataDIA() const;
/// Returns true, if the data should be opened in a new window
bool openAsNewWindow() const;
///Returns the index of the selected merge layer. If the option is not selected -1 is returned.
Int getMergeLayer() const;
/// Disables view dimension section and sets the selected option
void disableDimension(bool as_2d);
/// Disables cutoff section and sets the selected option
void disableCutoff(bool cutoff_on);
/// Disables opening location section and sets the selected option
void disableLocation(bool window);
/**
@brief Sets the possible merge layers (index and name) and activates the option
It is deactivated by default and can be deactivated manually by passing an empty list.
*/
void setMergeLayers(const std::map<Size, String> & layers);
protected slots:
///slot that disables 2D/3D options, when as layer is selected
void updateViewMode_(QAbstractButton * button);
protected:
///Stores if this option is disabled, to avoid activating it in updateViewMode_()
bool map_as_2d_disabled_;
private:
Ui::TOPPViewOpenDialogTemplate* ui_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/include/OpenMS/VISUAL/DIALOGS/TOPPViewPrefDialog.h | .h | 1,420 | 58 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <QtWidgets/QDialog>
namespace Ui
{
class TOPPViewPrefDialogTemplate;
}
namespace OpenMS
{
namespace Internal
{
/**
@brief Preferences dialog for TOPPView
@ingroup TOPPView_elements
*/
class OPENMS_GUI_DLLAPI TOPPViewPrefDialog :
public QDialog
{
Q_OBJECT
public:
TOPPViewPrefDialog(QWidget * parent);
~TOPPViewPrefDialog() override;
/// initialize GUI values with these parameters
void setParam(const Param& param);
/// update the parameters given the current GUI state.
/// Can be used to obtain default parameters and their names.
Param getParam() const;
protected slots:
void browseDefaultPath_();
void browsePluginsPath_();
private:
Ui::TOPPViewPrefDialogTemplate* ui_;
mutable Param param_; ///< is updated in getParam()
Param tsg_param_; ///< params for TheoreticalSpectrumGenerator in the TSG tab
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/FilterList.cpp | .cpp | 2,865 | 107 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/FilterList.h>
#include <ui_FilterList.h>
#include <OpenMS/VISUAL/DIALOGS/DataFilterDialog.h>
#include <QMenu>
using namespace std;
namespace OpenMS::Internal
{
FilterList::FilterList(QWidget *parent) :
QWidget(parent),
ui_(new Ui::FilterList)
{
ui_->setupUi(this);
connect(ui_->filter, &QListWidget::itemDoubleClicked, this, &FilterList::filterEdit_);
connect(ui_->filter, &QListWidget::customContextMenuRequested, this, &FilterList::customContextMenuRequested_);
connect(ui_->check, &QCheckBox::clicked, [&]() // only on user interaction; not when calling setChecked()!
{
filters_.setActive(!filters_.isActive()); // invert internal representation
emit filterChanged(filters_); // make it public
});
}
FilterList::~FilterList()
{
delete ui_;
}
void FilterList::filterEdit_(QListWidgetItem* item)
{
auto row = ui_->filter->row(item);
DataFilters::DataFilter filter = filters_[row];
DataFilterDialog dlg(filter, this);
if (dlg.exec())
{
filters_.replace(row, filter);
set(filters_);
}
}
void FilterList::set(const DataFilters& filters)
{
if (filters == filters_)
{ // avoid unnecessary updates
return;
}
filters_ = filters;
ui_->filter->clear();
for (Size i = 0; i < filters.size(); ++i)
{
QListWidgetItem* item = new QListWidgetItem(ui_->filter);
item->setText(filters[i].toString().toQString());
}
// update check box
ui_->check->setChecked(filters.isActive());
emit filterChanged(filters_);
}
void FilterList::customContextMenuRequested_(const QPoint& pos)
{
QMenu context_menu;
// add actions
QListWidgetItem* item = ui_->filter->itemAt(pos);
if (item)
{
context_menu.addAction("Edit", [&]()
{
filterEdit_(item);
});
context_menu.addAction("Delete", [&]()
{
filters_.remove(ui_->filter->row(item));
set(filters_);
});
}
context_menu.addAction("Add filter", [&]()
{
DataFilters::DataFilter filter;
DataFilterDialog dlg(filter, this);
if (dlg.exec())
{
filters_.add(filter);
set(filters_);
}
});
context_menu.exec(ui_->filter->mapToGlobal(pos));
}
} //namspace OpenMS //namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASInputFileListVertex.cpp | .cpp | 6,059 | 186 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/VISUAL/DIALOGS/TOPPASInputFilesDialog.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
namespace OpenMS
{
TOPPASInputFileListVertex::TOPPASInputFileListVertex(const QStringList& files)
{
setFilenames(files);
}
std::unique_ptr<TOPPASVertex> TOPPASInputFileListVertex::clone() const
{
return std::make_unique<TOPPASInputFileListVertex>(*this);
}
String TOPPASInputFileListVertex::getName() const
{
return "InputVertex";
}
void TOPPASInputFileListVertex::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * /*e*/)
{
showFilesDialog();
}
void TOPPASInputFileListVertex::showFilesDialog()
{
TOPPASInputFilesDialog tifd(getFileNames(), cwd_, nullptr);
if (tifd.exec())
{
QStringList updated_filelist;
tifd.getFilenames(updated_filelist);
if (getFileNames() != updated_filelist)
{ // files were changed
setFilenames(updated_filelist); // to correct filenames (separators etc)
qobject_cast<TOPPASScene *>(scene())->updateEdgeColors();
// update cwd
cwd_ = tifd.getCWD();
emit parameterChanged(true); // aborts the pipeline (if running) and resets downstream nodes
}
}
}
void TOPPASInputFileListVertex::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
TOPPASVertex::paint(painter, option, widget);
// display number of input files
QString text = QString::number(getFileNames().size())
+ " input file"
+ (getFileNames().size() == 1 ? "" : "s");
QRectF text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), (int)(text_boundings.height() / 4.0), text);
// display file type(s)
QStringList text_l = TOPPASVertex::TOPPASFilenames(getFileNames()).getSuffixCounts();
text = text_l.join(" | ");
// might get very long, especially if node was not reached yet, so trim
if (text.length() > 19) text = text.left(15) + " ...";
text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), 35 - (int)(text_boundings.height() / 4.0), text);
}
QRectF TOPPASInputFileListVertex::boundingRect() const
{
return QRectF(-71, -41, 142, 82);
}
bool TOPPASInputFileListVertex::fileNamesValid()
{
QStringList fl = getFileNames();
std::set<std::string> unique_names;
for (const QString& file : fl)
{
if (!File::exists(file))
{
return false;
}
QFileInfo fi(file);
const auto& [it_unique, was_inserted] = unique_names.insert(fi.canonicalFilePath().toStdString());
if (!was_inserted) // duplicate
{
const auto path = *it_unique; // working around 'error: reference to local binding 'it_unique' declared in enclosing function' on Clang (capture of structured binding problem)
OPENMS_LOG_ERROR << "File '" << file.toStdString() << "' (resolved to '" << path << "') appears twice in the input list!" << std::endl;
return false;
}
}
return true;
}
void TOPPASInputFileListVertex::openContainingFolder()
{
std::set<String> directories;
QStringList fl = getFileNames();
for (int i = 0; i < fl.size(); ++i) // collect unique directories
{
QFileInfo fi(fl[i]);
directories.insert(String(QFileInfo(fi.canonicalFilePath()).path()));
}
// open them
for (std::set<String>::const_iterator it = directories.begin(); it != directories.end(); ++it)
{
QString path = QDir::toNativeSeparators(it->toQString());
GUIHelpers::openFolder(path);
}
}
void TOPPASInputFileListVertex::run()
{
round_total_ = (int) output_files_.size(); // for now each file is one round; for the future we might allow to create blocks of files (e.g. for replicate measurements)
round_counter_ = (int) round_total_;
this->finished_ = true; // input node is ready to go (file check was already done)
//std::cerr << "#" << this->getTopoNr() << " set #rounds: " << round_total_ << "\n";
for (ConstEdgeIterator it = outEdgesBegin(); it != outEdgesEnd(); ++it)
{
TOPPASVertex* tv = (*it)->getTargetVertex();
if (tv && !tv->isFinished()) // this tool might have already been called by another path, so do not call it again (as this will throw an error)
{
tv->run();
}
}
}
void TOPPASInputFileListVertex::setKey(const QString& key)
{
key_ = key;
}
const QString& TOPPASInputFileListVertex::getKey()
{
return key_;
}
void TOPPASInputFileListVertex::setFilenames(const QStringList& files)
{
output_files_.clear();
if (files.empty())
{
return;
}
output_files_.resize(files.size()); // for now, assume one file per round (we could later extend that)
for (int f = 0; f < files.size(); ++f)
{
output_files_[f][-1].filenames.push_back(QDir::toNativeSeparators(files[f]));
}
setToolTip(files.join("\n"));
// set current working dir when opening files to the last file
cwd_ = File::path(files.back()).toQString();
}
void TOPPASInputFileListVertex::outEdgeHasChanged()
{
reset();
qobject_cast<TOPPASScene*>(scene())->updateEdgeColors();
TOPPASVertex::outEdgeHasChanged();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TVDIATreeTabController.cpp | .cpp | 9,712 | 278 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TVDIATreeTabController.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/DATASTRUCTURES/OSWData.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/ChromatogramTools.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/LayerDataChrom.h>
#include <OpenMS/VISUAL/Plot1DWidget.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DVerticalLineItem.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
using namespace OpenMS;
using namespace std;
namespace OpenMS
{
typedef LayerDataBase::ExperimentSharedPtrType ExperimentSharedPtrType;
typedef LayerDataBase::ConstExperimentSharedPtrType ConstExperimentSharedPtrType;
typedef LayerDataBase::ODExperimentSharedPtrType ODExperimentSharedPtrType;
typedef LayerDataBase::OSWDataSharedPtrType OSWDataSharedPtrType;
/// represents all the information we need from a chromatogram layer
/// We cannot use a full layer, because the original layer might get destroyed in the process...
struct MiniLayer
{
ExperimentSharedPtrType full_chrom_exp_sptr;
ODExperimentSharedPtrType ondisc_sptr;
OSWDataSharedPtrType annot_sptr;
String filename;
String layername;
explicit MiniLayer(LayerDataChrom& layer)
: full_chrom_exp_sptr(layer.getChromatogramData()),
ondisc_sptr(layer.getOnDiscPeakData()),
annot_sptr(layer.getChromatogramAnnotation()),
filename(layer.filename),
layername(layer.getName())
{
}
};
bool addTransitionAsLayer(Plot1DWidget* w,
const MiniLayer& ml,
const int transition_id,
std::set<UInt32>& transitions_seen)
{
if (transitions_seen.find(transition_id) != transitions_seen.end())
{ // duplicate .. do not show
return true;
}
transitions_seen.insert(transition_id);
// convert from native id to chrom_index
int chrom_index = ml.annot_sptr->fromNativeID(transition_id);
// add data and return if something went wrong
if (!w->canvas()->addChromLayer(ml.full_chrom_exp_sptr, ml.ondisc_sptr, ml.annot_sptr,
chrom_index, ml.filename,
FileHandler::stripExtension(File::basename(ml.filename)),
String("[") + transition_id + "]"))
{
return false;
}
w->canvas()->activateSpectrum(chrom_index, false);
return true;
}
void addFeatures(Plot1DWidget* w, std::vector<OSWPeakGroup>& features)
{
// nothing to do...
if (features.empty())
{
return;
}
// sort features by left RT
std::sort(features.begin(), features.end(), [](const OSWPeakGroup& a, const OSWPeakGroup& b)
{
return a.getRTLeftWidth() < b.getRTLeftWidth();
});
const OSWPeakGroup* best_feature = &features[0];
auto findBestFeature = [&best_feature](const OSWPeakGroup& f)
{
if (best_feature->getQValue() > f.getQValue())
{
best_feature = &f;
}
};
std::for_each(features.begin(), features.end(), findBestFeature);
if (best_feature->getQValue() == -1)
{ // no q-values are annotated. make them all grey.
best_feature = nullptr;
}
GUIHelpers::OverlapDetector od(3); // three y-levels for showing annotation
// show feature boundaries
for (const auto& feature : features)
{
auto width = feature.getRTRightWidth() - feature.getRTLeftWidth();
auto center = feature.getRTLeftWidth() + width / 2;
String ann = String("RT:\n ") + String(feature.getRTExperimental(), false) + "\ndRT:\n " + String(feature.getRTDelta(), false) + "\nQ:\n " + String(feature.getQValue(), false);
QColor col = GUIHelpers::ColorBrewer::Distinct().values[(best_feature == &feature)
? GUIHelpers::ColorBrewer::Distinct::LightGreen
: GUIHelpers::ColorBrewer::Distinct::LightGrey];
Annotation1DVerticalLineItem* item = new Annotation1DVerticalLineItem(center, width, 150, false, col, ann.toQString());
item->setSelected(false);
auto text_size = item->getTextRect(); // this is in px units (Qt widget coordinates)
// translate to axis units (our native 'data'):
auto p_text = w->canvas()->widgetToDataDistance(text_size.width(), 0);
auto chunk = od.placeItem(feature.getRTLeftWidth(), feature.getRTLeftWidth() + p_text.getX());
item->setTextOffset(chunk * text_size.height());
w->canvas()->getCurrentLayer().getCurrentAnnotations().push_back(item);
}
// paint the expected RT once
auto expected_RT = features[0].getRTExperimental() - features[0].getRTDelta();
Annotation1DItem* item = new Annotation1DVerticalLineItem(expected_RT, 3, 200, true, Qt::darkGreen, "");
item->setSelected(false);
w->canvas()->getCurrentLayer().getCurrentAnnotations().push_back(item);
}
TVDIATreeTabController::TVDIATreeTabController(TOPPViewBase* parent) :
TVControllerBase(parent)
{
}
void TVDIATreeTabController::showChromatogramsAsNew1D(const OSWIndexTrace& trace)
{
auto* layer_ptr = dynamic_cast<LayerDataChrom*>(&tv_->getActiveCanvas()->getCurrentLayer());
if (!layer_ptr)
{ // not a chrom layer?
std::cerr << __FILE__ << ": " << __LINE__ << " showChromatograms() invoked on Non-Chrom layer... weird..\n";
return;
}
MiniLayer ml(*layer_ptr);
// create new 1D widget; if we return due to error, the widget will be cleaned up
unique_ptr<Plot1DWidget> w(new Plot1DWidget(tv_->getCanvasParameters(1), DIM::Y, (QWidget*)tv_->getWorkspace()));
if (showChromatogramsInCanvas_(trace, ml, w.get()))
{ // success!
tv_->showPlotWidgetInWindow(w.get());
w.release(); // do NOT delete the widget; tv_ owns it now ...
tv_->updateBarsAndMenus();
}
}
void TVDIATreeTabController::showChromatograms(const OSWIndexTrace& trace)
{
Plot1DWidget* w = tv_->getActive1DWidget();
if (w == nullptr)
{ // currently not a 1d widget... ignore the signal
return;
}
auto* layer_ptr = dynamic_cast<LayerDataChrom*>(&w->canvas()->getCurrentLayer());
if (!layer_ptr)
{ // not a chrom layer?
std::cerr << __FILE__ << ": " << __LINE__ << " showChromatograms() invoked on Non-Chrom layer... weird..\n";
return;
}
MiniLayer ml(*layer_ptr);
// clear all layers
w->canvas()->removeLayers();
// add new layers
if (showChromatogramsInCanvas_(trace, ml, w))
{
tv_->updateBarsAndMenus();
}
}
bool TVDIATreeTabController::showChromatogramsInCanvas_(const OSWIndexTrace& trace, MiniLayer& ml, Plot1DWidget* w)
{
OSWData* data = ml.annot_sptr.get();
if (data == nullptr)
{ // no OSWData available ... strange...
return false;
}
std::set<UInt32> transitions_seen;
std::vector<OSWPeakGroup> features;
switch (trace.lowest)
{
case OSWHierarchy::Level::PROTEIN:
{
const auto& prot = data->getProteins()[trace.idx_prot];
// show only the first peptide for now...
const auto& pep = prot.getPeptidePrecursors()[0];
features = pep.getFeatures();
for (const auto& feat : pep.getFeatures())
{
const auto& trids = feat.getTransitionIDs();
for (UInt trid : trids)
{
if (!addTransitionAsLayer(w, ml, (Size)trid, transitions_seen))
{ // something went wrong. abort
return false;
}
}
}
break;
}
case OSWHierarchy::Level::PEPTIDE:
{
const auto& prot = data->getProteins()[trace.idx_prot];
const auto& pep = prot.getPeptidePrecursors()[trace.idx_pep];
features = pep.getFeatures();
for (const auto& feat : pep.getFeatures())
{
const auto& trids = feat.getTransitionIDs();
for (UInt trid : trids)
{
if (!addTransitionAsLayer(w, ml, (Size)trid, transitions_seen))
{ // something went wrong. abort
return false;
}
}
}
break;
}
case OSWHierarchy::Level::FEATURE:
{
const auto& prot = data->getProteins()[trace.idx_prot];
const auto& pep = prot.getPeptidePrecursors()[trace.idx_pep];
const auto& feat = pep.getFeatures()[trace.idx_feat];
features = { feat };
const auto& trids = feat.getTransitionIDs();
for (UInt trid : trids)
{
if (!addTransitionAsLayer(w, ml, (Size)trid, transitions_seen))
{ // something went wrong. abort
return false;
}
}
break;
}
case OSWHierarchy::Level::TRANSITION:
{
const auto& prot = data->getProteins()[trace.idx_prot];
const auto& pep = prot.getPeptidePrecursors()[trace.idx_pep];
const auto& feat = pep.getFeatures()[trace.idx_feat];
const auto& trid = feat.getTransitionIDs()[trace.idx_trans];
if (!addTransitionAsLayer(w, ml, (Size)trid, transitions_seen))
{ // something went wrong. abort
return false;
}
break;
}
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
// add bars for all identified features
addFeatures(w, features);
return true;
}
} // OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Plot3DOpenGLCanvas.cpp | .cpp | 37,541 | 1,134 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/Plot3DOpenGLCanvas.h>
#include <OpenMS/VISUAL/Plot3DCanvas.h>
#include <OpenMS/VISUAL/AxisTickCalculator.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <QMouseEvent>
using std::cout;
using std::endl;
using std::max;
namespace OpenMS
{
Plot3DOpenGLCanvas::Plot3DOpenGLCanvas(QWidget * parent, Plot3DCanvas & canvas_3d) :
QOpenGLWidget(parent),
canvas_3d_(canvas_3d)
{
canvas_3d.rubber_band_.setParent(this);
x_label_ = (String(Peak2D::shortDimensionName(Peak2D::MZ)) + " [" + String(Peak2D::shortDimensionUnit(Peak2D::MZ)) + "]").toQString();
y_label_ = (String(Peak2D::shortDimensionName(Peak2D::RT)) + " [" + String(Peak2D::shortDimensionUnit(Peak2D::RT)) + "]").toQString();
//Set focus policy and mouse tracking in order to get keyboard events
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
corner_ = 100.0;
near_ = 0.0;
far_ = 600.0;
zoom_ = 1.5;
xrot_ = 220;
yrot_ = 220;
zrot_ = 0;
trans_x_ = 0.0;
trans_y_ = 0.0;
}
Plot3DOpenGLCanvas::~Plot3DOpenGLCanvas() = default;
void Plot3DOpenGLCanvas::calculateGridLines_()
{
switch (canvas_3d_.intensity_mode_)
{
case PlotCanvas::IM_SNAP:
updateIntensityScale();
AxisTickCalculator::calcGridLines(0.0, int_scale_.max_[0], grid_intensity_);
break;
case PlotCanvas::IM_NONE:
AxisTickCalculator::calcGridLines(0.0, canvas_3d_.overall_data_range_.getMaxIntensity(), grid_intensity_);
break;
case PlotCanvas::IM_PERCENTAGE:
AxisTickCalculator::calcGridLines(0.0, 100.0, grid_intensity_);
break;
case PlotCanvas::IM_LOG:
AxisTickCalculator::calcLogGridLines(0.0, log10(1 + max(0.0, canvas_3d_.overall_data_range_.getMaxIntensity())), grid_intensity_);
break;
}
AxisTickCalculator::calcGridLines(canvas_3d_.visible_area_.getAreaUnit().getMinRT(), canvas_3d_.visible_area_.getAreaUnit().getMaxRT(), grid_rt_);
AxisTickCalculator::calcGridLines(canvas_3d_.visible_area_.getAreaUnit().getMinMZ(), canvas_3d_.visible_area_.getAreaUnit().getMaxMZ(), grid_mz_);
}
void Plot3DOpenGLCanvas::transformPoint_(GLdouble out[4], const GLdouble m[16], const GLdouble in[4])
{
#define M(row,col) m[col*4+row]
out[0] = M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3];
out[1] = M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3];
out[2] = M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3];
out[3] = M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3];
#undef M
}
GLint Plot3DOpenGLCanvas::project_(GLdouble objx, GLdouble objy, GLdouble objz, GLdouble * winx, GLdouble * winy)
{
int height= this->height();
int width = this->width();
GLdouble in[4], out[4];
in[0] = objx;
in[1] = objy;
in[2] = objz;
in[3] = 1.0;
GLdouble model[16];
GLdouble proj[16];
glGetDoublev(GL_MODELVIEW_MATRIX, model);
glGetDoublev(GL_PROJECTION_MATRIX, proj);
transformPoint_(out, model, in);
transformPoint_(in, proj, out);
// transform homogeneous coordinates into normalized device coordinates
if (in[3] == 0.0) { return GL_FALSE; }
in[0] /= in[3];
in[1] /= in[3];
in[2] /= in[3];
// viewport transformation (0,0 is in corner of screen not in middle of screen)
*winx = 0 + (1 + in[0]) * width / 2;
*winy = 0 + (1 + in[1]) * height / 2;
return GL_TRUE;
}
void Plot3DOpenGLCanvas::renderText_(double x, double y, double z, const QString & text)
{
// project to screen coordinates
GLdouble textPosX = 0, textPosY = 0;
project_(x, y, z, &textPosX, &textPosY);
const int height = this->height();
textPosY = height - textPosY; // y is inverted
// cout << x << " " << y << " " << z << " : " << textPosX << " " << textPosY << " " << textPosZ << endl;
// render text using the current font and color
painter_->drawText(textPosX, textPosY, text);
}
void Plot3DOpenGLCanvas::qglColor_(const QColor& color)
{
glColor4f(color.redF(), color.greenF(), color.blueF(), color.alphaF());
}
void Plot3DOpenGLCanvas::qglClearColor_(const QColor& clearColor)
{
glClearColor(clearColor.redF(), clearColor.greenF(), clearColor.blueF(), clearColor.alphaF());
}
void Plot3DOpenGLCanvas::resizeGL(int w, int h)
{
width_ = (float)w;
height_ = (float)h;
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-corner_ * zoom_, corner_ * zoom_, -corner_ * zoom_, corner_ * zoom_, near_, far_);
glMatrixMode(GL_MODELVIEW);
}
void Plot3DOpenGLCanvas::initializeGL()
{
initializeOpenGLFunctions();
// The following line triggered a bug where the whole screen would turn
// black during scrolling (specifically it seems that multiple calls to
// this function causes the issue):
// glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
QColor color(String(canvas_3d_.param_.getValue("background_color").toString()).toQString());
qglClearColor_(color);
calculateGridLines_();
//abort if no layers are displayed
if (canvas_3d_.getLayerCount() == 0) { return; }
if (canvas_3d_.action_mode_ == PlotCanvas::AM_ZOOM)
{
if (!canvas_3d_.rubber_band_.isVisible())
{
axes_ = makeAxes_();
if (canvas_3d_.show_grid_)
{
gridlines_ = makeGridLines_();
}
xrot_ = 90 * 16;
yrot_ = 0;
zrot_ = 0;
zoom_ = 1.25;
if (stickdata_ != 0)
{
glDeleteLists(stickdata_, 1);
#ifdef DEBUG_TOPPVIEW
cout << "BEGIN " << OPENMS_PRETTY_FUNCTION << endl;
std::cout << "Deleting sticklist near makeDataAsTopView" << std::endl;
#endif
}
stickdata_ = makeDataAsTopView_();
axes_ticks_ = makeAxesTicks_();
//drawAxesLegend_();
}
}
else if (canvas_3d_.action_mode_ == PlotCanvas::AM_TRANSLATE)
{
if (canvas_3d_.show_grid_) { gridlines_ = makeGridLines_(); }
axes_ = makeAxes_();
ground_ = makeGround_();
x_1_ = 0.0;
y_1_ = 0.0;
x_2_ = 0.0;
y_2_ = 0.0;
if (stickdata_ != 0)
{
glDeleteLists(stickdata_, 1);
#ifdef DEBUG_TOPPVIEW
cout << "BEGIN " << OPENMS_PRETTY_FUNCTION << endl;
std::cout << "Deleting sticklist near makeDataAsTopView" << std::endl;
#endif
}
stickdata_ = makeDataAsStick_();
axes_ticks_ = makeAxesTicks_();
//drawAxesLegend_();
}
}
void Plot3DOpenGLCanvas::resetTranslation()
{
trans_x_ = 0.0;
trans_y_ = 0.0;
}
void Plot3DOpenGLCanvas::storeRotationAndZoom()
{
xrot_tmp_ = xrot_;
yrot_tmp_ = yrot_;
zrot_tmp_ = zrot_;
zoom_tmp_ = zoom_;
}
void Plot3DOpenGLCanvas::restoreRotationAndZoom()
{
xrot_ = xrot_tmp_;
yrot_ = yrot_tmp_;
zrot_ = zrot_tmp_;
zoom_ = zoom_tmp_;
}
void Plot3DOpenGLCanvas::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslated(0.0, 0.0, -3.0 * corner_);
glRotated(xrot_ / 16.0, 1.0, 0.0, 0.0);
glRotated(yrot_ / 16.0, 0.0, 1.0, 0.0);
glRotated(zrot_ / 16.0, 0.0, 0.0, 1.0);
glTranslated(trans_x_, trans_y_, 3.0 * corner_);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if (canvas_3d_.getLayerCount() != 0)
{
glCallList(ground_);
if (canvas_3d_.show_grid_) { glCallList(gridlines_); }
glCallList(axes_);
glCallList(axes_ticks_);
if (canvas_3d_.action_mode_ == PlotCanvas::AM_ZOOM
|| canvas_3d_.action_mode_ == PlotCanvas::AM_TRANSLATE)
{
glCallList(stickdata_);
}
// draw axes legend
if (this->paintEngine()) // check if the paint device is properly initialized to suppress Qt warning
{
painter_ = new QPainter(this);
if (painter_->isActive())
{
drawAxesLegend_();
painter_->end();
}
delete(painter_);
}
}
}
void Plot3DOpenGLCanvas::drawAxesLegend_()
{
QFont font("Typewriter");
font.setPixelSize(10);
QString text;
qglColor_(Qt::black);
// Draw x and y axis legend
if (canvas_3d_.legend_shown_)
{
font.setPixelSize(12);
renderText_(0.0, -corner_ - 20.0, -near_ - 2 * corner_ + 20.0, x_label_);
renderText_(-corner_ - 20.0, -corner_ - 20.0, -near_ - 3 * corner_, y_label_);
font.setPixelSize(10);
}
// RT tick labels
{
if (grid_rt_.size() > 0)
{
for (Size i = 0; i < grid_rt_[0].size(); i++)
{
text = QString::number(grid_rt_[0][i]);
renderText_(-corner_ - 15.0, -corner_ - 5.0, -near_ - 2 * corner_ - scaledRT_(grid_rt_[0][i]), text);
}
}
if (zoom_ < 3.0 && grid_rt_.size() >= 2)
{
for (Size i = 0; i < grid_rt_[1].size(); i++)
{
text = QString::number(grid_rt_[1][i]);
renderText_(-corner_ - 15.0, -corner_ - 5.0, -near_ - 2 * corner_ - scaledRT_(grid_rt_[1][i]), text);
}
}
if (zoom_ < 2.0 && grid_rt_.size() >= 3)
{
for (Size i = 0; i < grid_rt_[2].size(); i++)
{
text = QString::number(grid_rt_[2][i]);
renderText_(-corner_ - 15.0, -corner_ - 5.0, -near_ - 2 * corner_ - scaledRT_(grid_rt_[2][i]), text);
}
}
}
// m/z tick labels
{
if (grid_mz_.size() > 0)
{
for (Size i = 0; i < grid_mz_[0].size(); i++)
{
text = QString::number(grid_mz_[0][i]);
renderText_(-corner_ - text.length() + scaledMZ_(grid_mz_[0][i]), -corner_ - 5.0, -near_ - 2 * corner_ + 15.0, text);
}
}
if (zoom_ < 3.0 && grid_mz_.size() >= 2)
{
for (Size i = 0; i < grid_mz_[1].size(); i++)
{
text = QString::number(grid_mz_[1][i]);
renderText_(-corner_ - text.length() + scaledMZ_(grid_mz_[1][i]), -corner_ - 5.0, -near_ - 2 * corner_ + 15.0, text);
}
}
if (zoom_ < 2.0 && grid_mz_.size() >= 3)
{
for (Size i = 0; i < grid_mz_[2].size(); i++)
{
text = QString::number(grid_mz_[2][i]);
renderText_(-corner_ - text.length() + scaledMZ_(grid_mz_[2][i]), -corner_ - 5.0, -near_ - 2 * corner_ + 15.0, text);
}
}
}
// draw intensity legend if not in zoom mode
if (canvas_3d_.action_mode_ != PlotCanvas::AM_ZOOM)
{
switch (canvas_3d_.intensity_mode_)
{
case PlotCanvas::IM_LOG:
if (canvas_3d_.legend_shown_)
{
font.setPixelSize(12);
text = QString("intensity log");
renderText_(-corner_ - 20.0, corner_ + 10.0, -near_ - 2 * corner_ + 20.0, text);
font.setPixelSize(10);
}
if (zoom_ < 3.0 && grid_intensity_.size() >= 2)
{
for (Size i = 0; i < grid_intensity_[0].size(); i++)
{
double intensity = (double)grid_intensity_[0][i];
text = QString("%1").arg(intensity, 0, 'f', 0);
renderText_(-corner_ - text.length() - width_ / 200.0 - 5.0, -corner_ + scaledIntensity_(pow(10.0, grid_intensity_[0][i]) - 1, canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_, text);
}
}
break;
case PlotCanvas::IM_PERCENTAGE:
if (canvas_3d_.legend_shown_)
{
font.setPixelSize(12);
renderText_(-corner_ - 20.0, corner_ + 10.0, -near_ - 2 * corner_ + 20.0, "intensity %");
font.setPixelSize(10);
}
for (Size i = 0; i < grid_intensity_[0].size(); i++)
{
text = QString::number(grid_intensity_[0][i]);
renderText_(-corner_ - text.length() - width_ / 200.0 - 5.0, -corner_ + (2.0 * grid_intensity_[0][i]), -near_ - 2 * corner_, text);
}
break;
case PlotCanvas::IM_NONE:
case PlotCanvas::IM_SNAP:
int expo = 0;
if (grid_intensity_.size() >= 1)
{
expo = (int)ceil(log10(grid_intensity_[0][0]));
}
if (grid_intensity_.size() >= 2)
{
if (expo >= ceil(log10(grid_intensity_[1][0])))
{
expo = (int)ceil(log10(grid_intensity_[1][0]));
}
}
if (grid_intensity_.size() >= 3)
{
if (expo >= ceil(log10(grid_intensity_[2][0])))
{
expo = (int) ceil(log10(grid_intensity_[2][0]));
}
}
if (canvas_3d_.legend_shown_)
{
font.setPixelSize(12);
text = QString("intensity e+%1").arg((double)expo, 0, 'f', 1);
renderText_(-corner_ - 20.0, corner_ + 10.0, -near_ - 2 * corner_ + 20.0, text);
font.setPixelSize(10);
}
if (zoom_ < 3.0 && grid_intensity_.size() >= 2)
{
for (Size i = 0; i < grid_intensity_[0].size(); i++)
{
double intensity = (double)grid_intensity_[0][i] / pow(10.0, expo);
text = QString("%1").arg(intensity, 0, 'f', 1);
renderText_(-corner_ - text.length() - width_ / 200.0 - 5.0, -corner_ + scaledIntensity_(grid_intensity_[0][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_, text);
}
for (Size i = 0; i < grid_intensity_[1].size(); i++)
{
double intensity = (double)grid_intensity_[1][i] / pow(10.0, expo);
text = QString("%1").arg(intensity, 0, 'f', 1);
renderText_(-corner_ - text.length() - width_ / 200.0 - 5.0, -corner_ + scaledIntensity_(grid_intensity_[1][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_, text);
}
}
if (width_ > 800 && height_ > 600 && zoom_ < 2.0 && grid_intensity_.size() >= 3)
{
for (Size i = 0; i < grid_intensity_[2].size(); i++)
{
double intensity = (double)grid_intensity_[2][i] / pow(10.0, expo);
text = QString("%1").arg(intensity, 0, 'f', 1);
renderText_(-corner_ - text.length() - width_ / 200.0 - 5.0, -corner_ + scaledIntensity_(grid_intensity_[2][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_, text);
}
}
break;
}
}
}
GLuint Plot3DOpenGLCanvas::makeGround_()
{
GLuint list = glGenLists(1);
glNewList(list, GL_COMPILE);
glBegin(GL_QUADS);
QColor color(String(canvas_3d_.param_.getValue("background_color").toString()).toQString());
qglColor_(color);
glVertex3d(-corner_, -corner_ - 2.0, -near_ - 2 * corner_);
glVertex3d(-corner_, -corner_ - 2.0, -far_ + 2 * corner_);
glVertex3d(corner_, -corner_ - 2.0, -far_ + 2 * corner_);
glVertex3d(corner_, -corner_ - 2.0, -near_ - 2 * corner_);
glEnd();
glEndList();
return list;
}
GLuint Plot3DOpenGLCanvas::makeAxes_()
{
GLuint list = glGenLists(1);
glNewList(list, GL_COMPILE);
glLineWidth(3.0);
glShadeModel(GL_FLAT);
glBegin(GL_LINES);
qglColor_(Qt::black);
// x
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_);
glVertex3d(corner_, -corner_, -near_ - 2 * corner_);
// z
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_);
glVertex3d(-corner_, -corner_, -far_ + 2 * corner_);
// y
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_);
glVertex3d(-corner_, corner_, -near_ - 2 * corner_);
glEnd();
glEndList();
return list;
}
GLuint Plot3DOpenGLCanvas::makeDataAsTopView_()
{
GLuint list = glGenLists(1);
glNewList(list, GL_COMPILE);
glPointSize(3.0);
for (Size i = 0; i < canvas_3d_.getLayerCount(); ++i)
{
const LayerDataPeak& layer = dynamic_cast<LayerDataPeak&>(canvas_3d_.getLayer(i));
if (layer.visible)
{
if ((Int)layer.param.getValue("dot:shade_mode"))
{
glShadeModel(GL_SMOOTH);
}
else
{
glShadeModel(GL_FLAT);
}
const auto area = canvas_3d_.visible_area_.getAreaUnit();
const MSExperiment& peak_data = layer.getPeakData()->getMSExperiment();
auto begin_it = peak_data.areaBeginConst(area.getMinRT(), area.getMaxRT(), area.getMinMZ(), area.getMaxMZ());
auto end_it = peak_data.areaEndConst();
// count peaks in area
int count = std::distance(begin_it, end_it);
int max_displayed_peaks = 10000;
int step = 1;
if (count > max_displayed_peaks)
{
step = 1 + count / max_displayed_peaks;
}
for (auto it = begin_it; it != end_it; ++it)
{
if (step > 1)
{
for (int i = 0; i < step - 1; ++i)
{
++it;
}
}
if (it == end_it)
{
glEndList();
return list;
}
PeakIndex pi = it.getPeakIndex();
const MSExperiment& peak_data = layer.getPeakData()->getMSExperiment();
if (layer.filters.passes(peak_data[pi.spectrum], pi.peak))
{
glBegin(GL_POINTS);
double intensity = 0;
switch (canvas_3d_.intensity_mode_)
{
case PlotCanvas::IM_NONE:
qglColor_(layer.gradient.precalculatedColorAt(it->getIntensity()));
break;
case PlotCanvas::IM_PERCENTAGE:
intensity = it->getIntensity() * 100.0 / canvas_3d_.getMaxIntensity(i);
qglColor_(layer.gradient.precalculatedColorAt(intensity));
break;
case PlotCanvas::IM_SNAP:
qglColor_(layer.gradient.precalculatedColorAt(it->getIntensity()));
break;
case PlotCanvas::IM_LOG:
qglColor_(layer.gradient.precalculatedColorAt(log10(1 + max(0.0, (double)(it->getIntensity())))));
break;
}
glVertex3f(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_,
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
glEnd();
}
}
}
}
glEndList();
return list;
}
GLuint Plot3DOpenGLCanvas::makeDataAsStick_()
{
GLuint list = glGenLists(1);
glNewList(list, GL_COMPILE);
for (Size i = 0; i < canvas_3d_.getLayerCount(); i++)
{
LayerDataPeak& layer = dynamic_cast<LayerDataPeak&>(canvas_3d_.getLayer(i));
if (layer.visible)
{
recalculateDotGradient_(layer);
if ((Int)layer.param.getValue("dot:shade_mode"))
{
glShadeModel(GL_SMOOTH);
}
else
{
glShadeModel(GL_FLAT);
}
glLineWidth(layer.param.getValue("dot:line_width"));
const auto area = canvas_3d_.visible_area_.getAreaUnit();
const MSExperiment& peak_data = layer.getPeakData()->getMSExperiment();
auto begin_it = peak_data.areaBeginConst(area.getMinRT(), area.getMaxRT(), area.getMinMZ(), area.getMaxMZ());
auto end_it = peak_data.areaEndConst();
// count peaks in area
int count = std::distance(begin_it, end_it);
int max_displayed_peaks = 100000;
int step = 1;
if (count > max_displayed_peaks)
{
step = 1 + count / max_displayed_peaks;
}
for (auto it = begin_it; it != end_it; ++it)
{
if (step > 1)
{
for (int i = 0; i < step - 1; ++i)
{
++it;
}
}
if (it == end_it)
{
glEndList();
return list;
}
PeakIndex pi = it.getPeakIndex();
const MSExperiment& peak_data = layer.getPeakData()->getMSExperiment();
if (layer.filters.passes(peak_data[pi.spectrum], pi.peak))
{
glBegin(GL_LINES);
double intensity = 0;
switch (canvas_3d_.intensity_mode_)
{
case PlotCanvas::IM_PERCENTAGE:
intensity = it->getIntensity() * 100.0 / canvas_3d_.getMaxIntensity(i);
qglColor_(layer.gradient.precalculatedColorAt(0.0));
glVertex3d(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_,
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
qglColor_(layer.gradient.precalculatedColorAt(intensity));
glVertex3d(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_ + (GLfloat)scaledIntensity_(it->getIntensity(), i),
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
break;
case PlotCanvas::IM_NONE:
qglColor_(layer.gradient.precalculatedColorAt(0.0));
glVertex3d(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_,
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
qglColor_(layer.gradient.precalculatedColorAt(it->getIntensity()));
glVertex3d(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_ + (GLfloat)scaledIntensity_(it->getIntensity(), i),
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
break;
case PlotCanvas::IM_SNAP:
qglColor_(layer.gradient.precalculatedColorAt(0.0));
glVertex3d(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_,
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
qglColor_(layer.gradient.precalculatedColorAt(it->getIntensity()));
glVertex3d(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_ + (GLfloat)scaledIntensity_(it->getIntensity(), i),
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
break;
case PlotCanvas::IM_LOG:
qglColor_(layer.gradient.precalculatedColorAt(0.0));
glVertex3d(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_,
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
qglColor_(layer.gradient.precalculatedColorAt(log10(1 + max(0.0, (double)(it->getIntensity())))));
glVertex3d(-corner_ + (GLfloat)scaledMZ_(it->getMZ()),
-corner_ + (GLfloat)scaledIntensity_(it->getIntensity(), i),
-near_ - 2 * corner_ - (GLfloat)scaledRT_(it.getRT()));
break;
}
glEnd();
}
}
}
}
glEndList();
return list;
}
GLuint Plot3DOpenGLCanvas::makeGridLines_()
{
GLuint list = glGenLists(1);
glNewList(list, GL_COMPILE);
glEnable(GL_LINE_STIPPLE);
glLineStipple(1, 0x0101);
glBegin(GL_LINES);
glColor4ub(0, 0, 0, 80);
// mz
if (grid_mz_.size() >= 1)
{
for (Size i = 0; i < grid_mz_[0].size(); i++)
{
glVertex3d(-corner_ + scaledMZ_(grid_mz_[0][i]), -corner_, -near_ - 2 * corner_);
glVertex3d(-corner_ + scaledMZ_(grid_mz_[0][i]), -corner_, -far_ + 2 * corner_);
}
}
if (grid_mz_.size() >= 2)
{
for (Size i = 0; i < grid_mz_[1].size(); i++)
{
glVertex3d(-corner_ + scaledMZ_(grid_mz_[1][i]), -corner_, -near_ - 2 * corner_);
glVertex3d(-corner_ + scaledMZ_(grid_mz_[1][i]), -corner_, -far_ + 2 * corner_);
}
}
if (grid_mz_.size() >= 3)
{
for (Size i = 0; i < grid_mz_[2].size(); i++)
{
glVertex3d(-corner_ + scaledMZ_(grid_mz_[2][i]), -corner_, -near_ - 2 * corner_);
glVertex3d(-corner_ + scaledMZ_(grid_mz_[2][i]), -corner_, -far_ + 2 * corner_);
}
}
// rt
if (grid_rt_.size() >= 1)
{
for (Size i = 0; i < grid_rt_[0].size(); i++)
{
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[0][i]));
glVertex3d(corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[0][i]));
}
}
if (grid_rt_.size() >= 2)
{
for (Size i = 0; i < grid_rt_[1].size(); i++)
{
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[1][i]));
glVertex3d(corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[1][i]));
}
}
if (grid_rt_.size() >= 3)
{
for (Size i = 0; i < grid_rt_[2].size(); i++)
{
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[2][i]));
glVertex3d(corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[2][i]));
}
}
glEnd();
glDisable(GL_LINE_STIPPLE);
glEndList();
return list;
}
GLuint Plot3DOpenGLCanvas::makeAxesTicks_()
{
GLuint list = glGenLists(1);
glNewList(list, GL_COMPILE);
glShadeModel(GL_FLAT);
glLineWidth(2.0);
glBegin(GL_LINES);
qglColor_(Qt::black);
// mz
if (grid_mz_.size() >= 1)
{
for (Size i = 0; i < grid_mz_[0].size(); i++)
{
glVertex3d(-corner_ + scaledMZ_(grid_mz_[0][i]), -corner_, -near_ - 2 * corner_);
glVertex3d(-corner_ + scaledMZ_(grid_mz_[0][i]), -corner_ + 4.0, -near_ - 2 * corner_);
}
}
if (grid_mz_.size() >= 2)
{
for (Size i = 0; i < grid_mz_[1].size(); i++)
{
glVertex3d(-corner_ + scaledMZ_(grid_mz_[1][i]), -corner_, -near_ - 2 * corner_);
glVertex3d(-corner_ + scaledMZ_(grid_mz_[1][i]), -corner_ + 3.0, -near_ - 2 * corner_);
}
}
if (grid_mz_.size() >= 3)
{
for (Size i = 0; i < grid_mz_[2].size(); i++)
{
glVertex3d(-corner_ + scaledMZ_(grid_mz_[2][i]), -corner_, -near_ - 2 * corner_);
glVertex3d(-corner_ + scaledMZ_(grid_mz_[2][i]), -corner_ + 2.0, -near_ - 2 * corner_);
}
}
// rt
if (grid_rt_.size() >= 1)
{
for (Size i = 0; i < grid_rt_[0].size(); i++)
{
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[0][i]));
glVertex3d(-corner_, -corner_ + 4.0, -near_ - 2 * corner_ - scaledRT_(grid_rt_[0][i]));
}
}
if (grid_rt_.size() >= 2)
{
for (Size i = 0; i < grid_rt_[1].size(); i++)
{
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[1][i]));
glVertex3d(-corner_, -corner_ + 3.0, -near_ - 2 * corner_ - scaledRT_(grid_rt_[1][i]));
}
}
if (grid_rt_.size() >= 3)
{
for (Size i = 0; i < grid_rt_[2].size(); i++)
{
glVertex3d(-corner_, -corner_, -near_ - 2 * corner_ - scaledRT_(grid_rt_[2][i]));
glVertex3d(-corner_, -corner_ + 2.0, -near_ - 2 * corner_ - scaledRT_(grid_rt_[2][i]));
}
}
//Intensity
switch (canvas_3d_.intensity_mode_)
{
case PlotCanvas::IM_PERCENTAGE:
if (grid_intensity_.size() >= 1)
{
for (Size i = 0; i < grid_intensity_[0].size(); i++)
{
glVertex3d(-corner_, -corner_ + (2.0 * grid_intensity_[0][i]), -near_ - 2 * corner_);
glVertex3d(-corner_ + 4.0, -corner_ + (2.0 * grid_intensity_[0][i]), -near_ - 2 * corner_ - 4.0);
}
}
break;
case PlotCanvas::IM_NONE:
case PlotCanvas::IM_SNAP:
if (grid_intensity_.size() >= 1)
{
for (Size i = 0; i < grid_intensity_[0].size(); i++)
{
glVertex3d(-corner_, -corner_ + scaledIntensity_(grid_intensity_[0][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_);
glVertex3d(-corner_ + 4.0, -corner_ + scaledIntensity_(grid_intensity_[0][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_ - 4.0);
}
}
if (grid_intensity_.size() >= 2)
{
for (Size i = 0; i < grid_intensity_[1].size(); i++)
{
glVertex3d(-corner_, -corner_ + scaledIntensity_(grid_intensity_[1][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_);
glVertex3d(-corner_ + 3.0, -corner_ + scaledIntensity_(grid_intensity_[1][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_ - 3.0);
}
}
if (grid_intensity_.size() >= 3)
{
for (Size i = 0; i < grid_intensity_[2].size(); i++)
{
glVertex3d(-corner_, -corner_ + scaledIntensity_(grid_intensity_[2][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_);
glVertex3d(-corner_ + 2.0, -corner_ + scaledIntensity_(grid_intensity_[2][i], canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_ - 2.0);
}
}
break;
case PlotCanvas::IM_LOG:
if (grid_intensity_.size())
{
for (Size i = 0; i < grid_intensity_[0].size(); i++)
{
glVertex3d(-corner_, -corner_ + scaledIntensity_(pow(10.0, grid_intensity_[0][i]) - 1, canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_);
glVertex3d(-corner_ + 4.0, -corner_ + scaledIntensity_(pow(10.0, grid_intensity_[0][i]) - 1, canvas_3d_.layers_.getCurrentLayerIndex()), -near_ - 2 * corner_ - 4.0);
}
}
break;
}
glEnd();
glEndList();
return list;
}
double Plot3DOpenGLCanvas::scaledRT_(double rt)
{
double scaledrt = rt - canvas_3d_.visible_area_.getAreaUnit().getMinRT();
scaledrt = scaledrt * 2.0 * corner_ / canvas_3d_.visible_area_.getAreaUnit().RangeRT::getSpan();
return scaledrt;
}
double Plot3DOpenGLCanvas::scaledInversRT_(double rt)
{
double i_rt = rt * canvas_3d_.visible_area_.getAreaUnit().RangeRT::getSpan();
i_rt = i_rt / 200.0;
i_rt = i_rt + canvas_3d_.visible_area_.getAreaUnit().getMinRT();
// cout<<"rt"<<rt<<" "<<"scaledinver"<<i_rt<<endl;
return i_rt;
}
double Plot3DOpenGLCanvas::scaledMZ_(double mz)
{
double scaledmz = mz - canvas_3d_.visible_area_.getAreaUnit().getMinMZ();
scaledmz = scaledmz * 2.0 * corner_ / canvas_3d_.visible_area_.getAreaUnit().RangeMZ::getSpan() /*dis_mz_*/;
return scaledmz;
}
double Plot3DOpenGLCanvas::scaledInversMZ_(double mz)
{
double i_mz = mz * canvas_3d_.visible_area_.getAreaUnit().RangeMZ::getSpan();
i_mz = i_mz / 200;
i_mz = i_mz + canvas_3d_.visible_area_.getAreaUnit().getMinMZ();
return i_mz;
}
double Plot3DOpenGLCanvas::scaledIntensity_(float intensity, Size layer_index)
{
double scaledintensity = intensity * 2.0 * corner_;
switch (canvas_3d_.intensity_mode_)
{
case PlotCanvas::IM_SNAP:
scaledintensity /= int_scale_.max_[0];
break;
case PlotCanvas::IM_NONE:
scaledintensity /= canvas_3d_.overall_data_range_.getMaxIntensity();
break;
case PlotCanvas::IM_PERCENTAGE:
scaledintensity /= canvas_3d_.getMaxIntensity(layer_index);
break;
case PlotCanvas::IM_LOG:
scaledintensity = log10(1 + max(0.0, (double)intensity)) * 2.0 * corner_ / log10(1 + max(0.0, canvas_3d_.overall_data_range_.getMaxIntensity()));
break;
}
return scaledintensity;
}
void Plot3DOpenGLCanvas::normalizeAngle(int* angle)
{
while (*angle < 0) { *angle += 360 * 16; }
while (*angle > 360 * 16) { *angle -= 360 * 16; }
}
///////////////wheel- and MouseEvents//////////////////
void Plot3DOpenGLCanvas::actionModeChange()
{
//change from translate to zoom
if (canvas_3d_.action_mode_ == PlotCanvas::AM_ZOOM)
{
storeRotationAndZoom();
xrot_ = 220;
yrot_ = 220;
zrot_ = 0;
canvas_3d_.update_buffer_ = true;
canvas_3d_.update_(OPENMS_PRETTY_FUNCTION);
}
//change from zoom to translate
else if (canvas_3d_.action_mode_ == PlotCanvas::AM_TRANSLATE)
{
// if still in selection mode, quit selection mode first:
if (canvas_3d_.rubber_band_.isVisible())
{
computeSelection_();
}
restoreRotationAndZoom();
canvas_3d_.update_buffer_ = true;
canvas_3d_.update_(OPENMS_PRETTY_FUNCTION);
}
update();
}
void Plot3DOpenGLCanvas::focusOutEvent(QFocusEvent * e)
{
canvas_3d_.focusOutEvent(e);
update();
}
void Plot3DOpenGLCanvas::mousePressEvent(QMouseEvent * e)
{
mouse_move_begin_ = e->pos();
mouse_move_end_ = e->pos();
if (canvas_3d_.action_mode_ == PlotCanvas::AM_ZOOM && e->button() == Qt::LeftButton)
{
canvas_3d_.rubber_band_.setGeometry(QRect(e->pos(), QSize()));
canvas_3d_.rubber_band_.show();
canvas_3d_.update_buffer_ = true;
canvas_3d_.update_(OPENMS_PRETTY_FUNCTION);
}
update();
}
void Plot3DOpenGLCanvas::mouseMoveEvent(QMouseEvent * e)
{
if (e->buttons() & Qt::LeftButton)
{
if (canvas_3d_.action_mode_ == PlotCanvas::AM_ZOOM)
{
canvas_3d_.rubber_band_.setGeometry(QRect(mouse_move_begin_, e->pos()).normalized());
canvas_3d_.update_(OPENMS_PRETTY_FUNCTION);
}
else if (canvas_3d_.action_mode_ == PlotCanvas::AM_TRANSLATE)
{
Int x_angle = xrot_ + 8 * (e->position().y() - mouse_move_end_.y());
normalizeAngle(&x_angle);
xrot_ = x_angle;
Int y_angle = yrot_ + 8 * (e->position().x() - mouse_move_end_.x());
normalizeAngle(&y_angle);
yrot_ = y_angle;
//drawAxesLegend_();
mouse_move_end_ = e->pos();
canvas_3d_.update_(OPENMS_PRETTY_FUNCTION);
}
}
update();
}
void Plot3DOpenGLCanvas::mouseReleaseEvent(QMouseEvent * e)
{
if (canvas_3d_.action_mode_ == PlotCanvas::AM_ZOOM && e->button() == Qt::LeftButton)
{
computeSelection_();
}
update();
}
void Plot3DOpenGLCanvas::computeSelection_()
{
QRect rect = canvas_3d_.rubber_band_.geometry();
x_1_ = ((rect.topLeft().x() - width_ / 2) * corner_ * 1.25 * 2) / width_;
y_1_ = -300 + (((rect.topLeft().y() - height_ / 2) * corner_ * 1.25 * 2) / height_);
x_2_ = ((rect.bottomRight().x() - width_ / 2) * corner_ * 1.25 * 2) / width_;
y_2_ = -300 + (((rect.bottomRight().y() - height_ / 2) * corner_ * 1.25 * 2) / height_);
dataToZoomArray_(x_1_, y_1_, x_2_, y_2_);
canvas_3d_.rubber_band_.hide();
canvas_3d_.update_buffer_ = true;
canvas_3d_.update_(OPENMS_PRETTY_FUNCTION);
}
void Plot3DOpenGLCanvas::dataToZoomArray_(double x_1, double y_1, double x_2, double y_2)
{
double scale_x1 = scaledInversRT_(-200 - y_1);
double scale_x2 = scaledInversRT_(-200 - y_2);
double scale_y1 = scaledInversMZ_(x_1 + 100.0);
double scale_y2 = scaledInversMZ_(x_2 + 100.0);
DRange<2> new_area_;
if (scale_x1 > scale_x2)
{
std::swap(scale_x1, scale_x2);
}
new_area_.min_[0] = scale_x1;
new_area_.max_[0] = scale_x2;
if (scale_y1 > scale_y2)
{
std::swap(scale_y1, scale_y2);
}
new_area_.min_[1] = scale_y1;
new_area_.max_[1] = scale_y2;
canvas_3d_.changeVisibleArea_(canvas_3d_.visible_area_.cloneWith(new_area_), true, true);
}
void Plot3DOpenGLCanvas::updateIntensityScale()
{
int_scale_.min_[0] = canvas_3d_.overall_data_range_.getMaxIntensity();
int_scale_.max_[0] = canvas_3d_.overall_data_range_.getMinIntensity();
const auto area = canvas_3d_.visible_area_.getAreaUnit();
for (Size i = 0; i < canvas_3d_.getLayerCount(); i++)
{
const auto& layer = dynamic_cast<const LayerDataPeak&>(canvas_3d_.getLayer(i));
const MSExperiment& peak_data = layer.getPeakData()->getMSExperiment();
auto rt_begin_it = peak_data.RTBegin(area.getMinRT());
auto rt_end_it = peak_data.RTEnd(area.getMaxRT());
for (auto spec_it = rt_begin_it; spec_it != rt_end_it; ++spec_it)
{
auto mz_end = spec_it->MZEnd(area.getMaxMZ());
for (auto it = spec_it->MZBegin(area.getMinMZ()); it != mz_end; ++it)
{
Math::extendRange(int_scale_.min_[0], int_scale_.max_[0], (double)it->getIntensity());
}
}
}
}
void Plot3DOpenGLCanvas::recalculateDotGradient_(LayerDataBase& layer)
{
layer.gradient.fromString(layer.param.getValue("dot:gradient"));
switch (canvas_3d_.intensity_mode_)
{
case PlotCanvas::IM_SNAP:
layer.gradient.activatePrecalculationMode(0.0, int_scale_.max_[0], UInt(canvas_3d_.param_.getValue("dot:interpolation_steps")));
break;
case PlotCanvas::IM_NONE:
layer.gradient.activatePrecalculationMode(0.0, canvas_3d_.overall_data_range_.getMaxIntensity(), UInt(canvas_3d_.param_.getValue("dot:interpolation_steps")));
break;
case PlotCanvas::IM_PERCENTAGE:
layer.gradient.activatePrecalculationMode(0.0, 100.0, UInt(canvas_3d_.param_.getValue("dot:interpolation_steps")));
break;
case PlotCanvas::IM_LOG:
layer.gradient.activatePrecalculationMode(0.0, log10(1 + max(0.0, canvas_3d_.overall_data_range_.getMaxIntensity())), UInt(canvas_3d_.param_.getValue("dot:interpolation_steps")));
break;
}
}
} //end of namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TVToolDiscovery.cpp | .cpp | 8,429 | 262 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: David Voigt $
// $Authors: David Voigt, Ruben Grünberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TVToolDiscovery.h>
#include <OpenMS/APPLICATIONS/ToolHandler.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/SYSTEM/ExternalProcess.h>
#include <QCoreApplication>
#include <QDir>
#include <thread>
namespace OpenMS
{
void TVToolDiscovery::loadToolParams()
{
// tool params are only loaded once by using a immediately evaluated lambda
static bool _ [[maybe_unused]] = [&]() -> bool
{
// Get a map of all tools
const auto &tools = ToolHandler::getTOPPToolList();
// Launch threads for loading tool/util params.
for (const auto& tool : tools)
{
tool_param_futures_.push_back(std::async(std::launch::async, getParamFromIni_, tool.first, false));
}
return true;
}();
}
void TVToolDiscovery::loadPluginParams()
{
plugin_param_futures_.clear();
plugins_.clear();
const auto &plugins = getPlugins_();
for (auto& plugin : plugins)
{
plugin_param_futures_.push_back(std::async(std::launch::async, getParamFromIni_, plugin, true));
}
}
void TVToolDiscovery::waitForToolParams()
{
// Make sure that future results are only waited for and inserted in params_ once
static bool _ [[maybe_unused]] = [&]() -> bool
{
// Make sure threads have been launched before waiting
loadToolParams();
// Wait for futures to finish
for (auto& param_future : tool_param_futures_)
{
while (param_future.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
{
// Keep GUI responsive while waiting
QCoreApplication::processEvents();
}
// Make future results available in tool_params_
tool_params_.insert("", param_future.get());
}
return true;
}();
}
void TVToolDiscovery::waitForPluginParams()
{
// Make sure threads have been launched before waiting
loadPluginParams();
// Wait for futures to finish
for (auto& param_future : plugin_param_futures_)
{
while (param_future.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
{
// Keep GUI responsive while waiting
QCoreApplication::processEvents();
}
// Make future results available in plugin_params_
Param new_param = param_future.get();
// Skip if the param is empty, that means something went wrong during execution
if (new_param.empty()) continue;
plugins_.push_back(new_param.begin().getTrace().begin()->name);
plugin_params_.insert("", new_param);
}
}
const Param& TVToolDiscovery::getToolParams()
{
// Make sure threads have been launched and waited for before accessing results
waitForToolParams();
return tool_params_;
}
const Param& TVToolDiscovery::getPluginParams()
{
plugin_params_.clear();
waitForPluginParams();
return plugin_params_;
}
Param TVToolDiscovery::getParamFromIni_(const String& tool_path, bool plugins)
{
static std::mutex io_mutex;
FileHandler fh;
// Temporary file path and arguments
String path = File::getTemporaryFile();
String working_dir = path.prefix(path.find_last_of('/'));
QStringList args{"-write_ini", path.toQString()};
Param tool_param;
String executable;
// Return empty param if tool executable cannot be found
try
{
std::scoped_lock lock(io_mutex);
// Is an executable already or has a sibling Executable
executable = File::exists(tool_path) ? tool_path : File::findSiblingTOPPExecutable(tool_path);
}
catch (const Exception::FileNotFound& e)
{
std::scoped_lock lock(io_mutex);
OPENMS_LOG_DEBUG << "TOPP tool: " << e << " not found during tool discovery. Skipping." << std::endl;
return tool_param;
}
// Write tool ini to temporary file
static std::atomic<int> running_processes{0}; // used to limit the number of parallel processes
auto lam_out = [&](const String& out) { OPENMS_LOG_INFO << out; };
auto lam_err = [&](const String& out) { OPENMS_LOG_INFO << out; };
// Spawning a thread for all tools is no problem (if std::async decides to do so)
// but spawning that many processes failed with not enough file handles on machines with large number of cores.
// Restricting the number of running processes solves that issue.
while (running_processes >= 6)
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
QCoreApplication::processEvents();
}
ExternalProcess proc(lam_out, lam_err);
// Write tool ini to temporary file
++running_processes;
auto return_state = proc.run(executable.toQString(), args, working_dir.toQString(), true, ExternalProcess::IO_MODE::NO_IO);
--running_processes;
// Return empty param if writing the ini file failed
if (return_state != ExternalProcess::RETURNSTATE::SUCCESS)
{
std::scoped_lock lock(io_mutex);
OPENMS_LOG_DEBUG << "TOPP tool: " << executable << " error during execution: " << (uint32_t)return_state << "\n";
return tool_param;
}
// Parse ini file to param object
ParamXMLFile paramFile;
try
{
paramFile.load((path).c_str(), tool_param);
}
catch(const Exception::FileNotFound& e)
{
std::scoped_lock lock(io_mutex);
OPENMS_LOG_DEBUG << e << "\n" << "TOPP tool: " << executable <<
" not able to write ini. Plugins must implement -write_ini parameter. Skipping." << std::endl;
return tool_param;
}
if (plugins)
{
auto tool_name = tool_param.begin().getTrace().begin()->name;
auto filename = File::basename(tool_path);
tool_param.setValue(tool_name + ":filename", filename, "The filename of the plugin executable. This entry is automatically generated.");
}
return tool_param;
}
const std::vector<std::string>& TVToolDiscovery::getPlugins()
{
return plugins_;
}
const StringList TVToolDiscovery::getPlugins_()
{
StringList plugins;
// here all supported file extensions can be added
std::vector<std::string> valid_extensions {"", ".py"};
const auto comparator = [valid_extensions](const std::string& plugin) -> bool
{
return !File::executable(plugin) ||
(std::find(valid_extensions.begin(), valid_extensions.end(), plugin.substr(plugin.find_last_of('.'))) == valid_extensions.end());
};
if (File::fileList(plugin_path_, "*", plugins, true))
{
plugins.erase(std::remove_if(plugins.begin(), plugins.end(), comparator), plugins.end());
}
return plugins;
}
bool TVToolDiscovery::setPluginPath(const String& plugin_path, bool create)
{
if (!File::exists(plugin_path))
{
if (create)
{
QDir path = QDir(plugin_path.toQString());
QString dir = path.dirName();
path.cdUp();
if (!path.mkdir(dir))
{
OPENMS_LOG_WARN << "Unable to create plugin directory " << plugin_path << std::endl;
//plugin_path_ = plugin_path;
return false;
}
}
else
{
OPENMS_LOG_WARN << "Unable to set plugin directory: " << plugin_path << " does not exist." << std::endl;
return false;
}
}
plugin_path_ = plugin_path;
return true;
}
const std::string TVToolDiscovery::getPluginPath()
{
return plugin_path_;
}
void TVToolDiscovery::setVerbose(int verbosity_level)
{
verbosity_level_ = verbosity_level;
}
std::string TVToolDiscovery::findPluginExecutable(const std::string& name)
{
//TODO: At the moment the usage of subdirectories in the plugin path are not possible
//To change that, the tool scanner has to recursively search all directories in the plugin path
if (!plugin_params_.exists(name + ":filename"))
{
return "";
}
return plugin_path_ + "/" + plugin_params_.getValue(name + ":filename").toString();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerDataBase.cpp | .cpp | 10,281 | 297 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerDataBase.h>
#include <OpenMS/ANALYSIS/ID/AccurateMassSearchEngine.h>// for AMS annotation
#include <OpenMS/ANALYSIS/ID/IDMapper.h>
#include <OpenMS/DATASTRUCTURES/OSWData.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/OSWFile.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
#include <OpenMS/VISUAL/LayerDataConsensus.h>
#include <OpenMS/VISUAL/LayerDataFeature.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox>
using namespace std;
namespace OpenMS
{
LayerDataDefs::ProjectionData::ProjectionData() = default;
LayerDataDefs::ProjectionData::ProjectionData(ProjectionData&&) = default;
LayerDataDefs::ProjectionData::~ProjectionData() = default;
const std::string LayerDataDefs::NamesOfLabelType[] = {"None", "Index", "Label meta data", "Peptide identification", "All peptide identifications"};
std::ostream& operator<<(std::ostream& os, const LayerDataBase& rhs)
{
os << "--LayerDataBase BEGIN--\n";
os << "name: " << rhs.getName() << '\n';
os << "visible: " << rhs.visible << '\n';
os << "--LayerDataBase END--\n";
return os;
}
/// get name plus name_extra plus optionally augmented with attributes, e.g. '*' if modified
String LayerDataBase::getDecoratedName() const
{
String n = name_ + name_suffix_;
if (modified)
{
n += '*';
}
return n;
}
/*
void LayerDataBase::updateCache_()
{
if (peak_map_->getMSExperiment().getNrSpectra() > current_spectrum_idx_ && !(*peak_map_)[current_spectrum_idx_].first.empty())
{
cached_spectrum_ = (*peak_map_)[current_spectrum_idx_].first;
}
else if (on_disc_peaks->getNrSpectra() > current_spectrum_idx_)
{
cached_spectrum_ = on_disc_peaks->getSpectrum(current_spectrum_idx_);
}
}
/// add annotation from an OSW sqlite file.
/// get annotation (e.g. to build a hierachical ID View)
/// Not const, because we might have incomplete data, which needs to be loaded from sql source
LayerDataBase::OSWDataSharedPtrType& LayerDataBase::getChromatogramAnnotation()
{
return chrom_annotation_;
}
const LayerDataBase::OSWDataSharedPtrType& LayerDataBase::getChromatogramAnnotation() const
{
return chrom_annotation_;
}
void LayerDataBase::setChromatogramAnnotation(OSWData&& data)
{
chrom_annotation_ = OSWDataSharedPtrType(new OSWData(std::move(data)));
}
*/
bool LayerDataBase::annotate(const PeptideIdentificationList& identifications,
const vector<ProteinIdentification>& protein_identifications)
{
IDMapper mapper;
if (auto* lp = dynamic_cast<LayerDataPeak*>(this))
{
Param p = mapper.getDefaults();
p.setValue("rt_tolerance", 0.1, "RT tolerance (in seconds) for the matching");
p.setValue("mz_tolerance", 1.0, "m/z tolerance (in ppm or Da) for the matching");
p.setValue("mz_measure", "Da", "unit of 'mz_tolerance' (ppm or Da)");
mapper.setParameters(p);
mapper.annotate(*lp->getPeakDataMuteable(), identifications, protein_identifications, true);
}
if (auto* lp = dynamic_cast<LayerDataFeature*>(this))
{
mapper.annotate(*lp->getFeatureMap(), identifications, protein_identifications);
}
else if (auto* lp = dynamic_cast<LayerDataConsensus*>(this))
{
mapper.annotate(*lp->getConsensusMap(), identifications, protein_identifications);
}
else
{
return false;
}
return false;
}
float LayerDataBase::getMinIntensity() const
{
if (!getRange().RangeIntensity::isEmpty())
{
return getRange().getMinIntensity();
}
else
{
OPENMS_LOG_WARN << "No data in range to get min intensity from. Returning 0.0." << std::endl;
return 0.0f;
}
}
float LayerDataBase::getMaxIntensity() const
{
if (!getRange().RangeIntensity::isEmpty())
{
return getRange().getMaxIntensity();
}
else
{
OPENMS_LOG_WARN << "No data in range to get max intensity from. Returning 0.0." << std::endl;
return 0.0f;
}
}
LayerAnnotatorBase::LayerAnnotatorBase(const FileTypeList& supported_types, const String& file_dialog_text, QWidget* gui_lock) :
supported_types_(supported_types),
file_dialog_text_(file_dialog_text),
gui_lock_(gui_lock)
{
}
bool LayerAnnotatorBase::annotateWithFileDialog(LayerDataBase& layer, LogWindow& log, const String& current_path) const
{
// warn if hidden layer => wrong layer selected...
if (!layer.visible)
{
log.appendNewHeader(LogWindow::LogState::NOTICE, "The current layer is not visible", "Have you selected the right layer for this action? Aborting.");
return false;
}
// load id data
QString fname = QFileDialog::getOpenFileName(nullptr,
file_dialog_text_.toQString(),
current_path.toQString(),
supported_types_.toFileDialogFilter(FilterLayout::BOTH, true).toQString());
bool success = annotateWithFilename(layer, log, fname);
return success;
}
bool LayerAnnotatorBase::annotateWithFilename(LayerDataBase& layer, LogWindow& log, const String& fname) const
{
if (fname.empty())
{
return false;
}
FileTypes::Type type = FileHandler::getType(fname);
if (!supported_types_.contains(type))
{
log.appendNewHeader(LogWindow::LogState::NOTICE, "Error", String("Filename '" + fname + "' has unsupported file type. No annotation performed.").toQString());
return false;
}
GUIHelpers::GUILock glock(gui_lock_);
bool success = annotateWorker_(layer, fname, log);
if (success)
{
log.appendNewHeader(LogWindow::LogState::NOTICE, "Done", "Annotation finished. Open the corresponding view to see results!");
}
return success;
}
std::unique_ptr<LayerAnnotatorBase> LayerAnnotatorBase::getAnnotatorWhichSupports(const FileTypes::Type& type)
{
std::unique_ptr<LayerAnnotatorBase> ptr(nullptr);
auto assign = [&type, &ptr](std::unique_ptr<LayerAnnotatorBase> other) {
if (other->supported_types_.contains(type))
{
if (ptr.get() != nullptr)
{
throw Exception::IllegalSelfOperation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ptr = std::move(other);
}
};
// hint: add new derived classes here, so they are checked as well
assign(std::unique_ptr<LayerAnnotatorBase>(new LayerAnnotatorAMS(nullptr)));
assign(std::unique_ptr<LayerAnnotatorBase>(new LayerAnnotatorPeptideID(nullptr)));
assign(std::unique_ptr<LayerAnnotatorBase>(new LayerAnnotatorOSW(nullptr)));
return ptr;// Note: no std::move here needed because of copy elision
}
std::unique_ptr<LayerAnnotatorBase> LayerAnnotatorBase::getAnnotatorWhichSupports(const String& filename)
{
return getAnnotatorWhichSupports(FileHandler::getType(filename));
}
bool LayerAnnotatorPeptideID::annotateWorker_(LayerDataBase& layer, const String& filename, LogWindow& /*log*/) const
{
FileTypes::Type type = FileHandler::getType(filename);
PeptideIdentificationList identifications;
vector<ProteinIdentification> protein_identifications;
FileHandler().loadIdentifications(filename, protein_identifications, identifications, {type});
layer.annotate(identifications, protein_identifications);
return true;
}
bool LayerAnnotatorAMS::annotateWorker_(LayerDataBase& layer, const String& filename, LogWindow& log) const
{
FeatureMap fm;
FileHandler().loadFeatures(filename, fm, {FileTypes::FEATUREXML});
// last protein ID must be from AccurateMassSearch (it gets appended there)
String engine = "no protein identification section found";
if (fm.getProteinIdentifications().size() > 0)
{
engine = fm.getProteinIdentifications().back().getSearchEngine();
if (engine == AccurateMassSearchEngine::search_engine_identifier)
{
auto* lp = dynamic_cast<LayerDataPeak*>(&layer);
if (!lp)
{
QMessageBox::warning(nullptr, "Error", "Layer type is not DT_PEAK!");
return false;
}
IDMapper im;
Param p = im.getParameters();
p.setValue("rt_tolerance", 30.0);
im.setParameters(p);
log.appendNewHeader(LogWindow::LogState::NOTICE, "Note", "Mapping matches with 30 sec tolerance and no m/z limit to spectra...");
im.annotate((*lp->getPeakDataMuteable()), fm, true, true);
return true;
}
}
QMessageBox::warning(nullptr, "Error", (String("FeatureXML is currently only supported for files generated by the AccurateMassSearch tool (got '") + engine + "', expected 'AccurateMassSearch'.").toQString());
return false;
}
bool LayerAnnotatorOSW::annotateWorker_(LayerDataBase& layer,
const String& filename,
LogWindow& log) const
{
log.appendNewHeader(LogWindow::LogState::NOTICE, "Note", "Reading OSW data ...");
auto* lp = dynamic_cast<LayerDataChrom*>(&layer);
if (!lp)
{
QMessageBox::warning(nullptr, "Error", "Layer type is not DT_CHROM!");
return false;
}
try
{
OSWFile oswf(filename);// this can throw if file does not exist
OSWData data;
oswf.readMinimal(data);
// allow data to map from transition.id (=native.id) to a chromatogram index in MSExperiment
data.buildNativeIDResolver(lp->getChromatogramData().get()->getMSExperiment());
lp->setChromatogramAnnotation(std::move(data));
return true;
}
catch (Exception::BaseException& e)
{
log.appendText(e.what());
return false;
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASResources.cpp | .cpp | 2,906 | 112 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASResources.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <iostream>
#include <map>
namespace OpenMS
{
TOPPASResources::TOPPASResources() :
QObject(),
map_(),
empty_list_()
{
}
TOPPASResources::TOPPASResources(const TOPPASResources& rhs) :
QObject(),
map_(rhs.map_),
empty_list_()
{
}
TOPPASResources::~TOPPASResources() = default;
TOPPASResources& TOPPASResources::operator=(const TOPPASResources& rhs)
{
map_ = rhs.map_;
return *this;
}
void TOPPASResources::load(const QString& file_name)
{
Param load_param;
ParamXMLFile paramFile;
paramFile.load(String(file_name), load_param);
for (Param::ParamIterator it = load_param.begin(); it != load_param.end(); ++it)
{
StringList substrings;
String(it.getName()).split(':', substrings);
if (substrings.size() != 2 ||
substrings.back() != "url_list" ||
(it->value).valueType() != ParamValue::STRING_LIST)
{
std::cerr << "Invalid file format." << std::endl;
return;
}
QString key = (substrings[0]).toQString();
StringList url_list = ListUtils::toStringList<std::string>(it->value);
QList<TOPPASResource> resource_list;
for (StringList::const_iterator it = url_list.begin(); it != url_list.end(); ++it)
{
resource_list << TOPPASResource(QUrl(it->toQString()));
}
add(key, resource_list);
}
}
void TOPPASResources::add(const QString& key, const QList<TOPPASResource>& resource_list)
{
map_[key] = resource_list;
}
void TOPPASResources::store(const QString& file_name)
{
Param save_param;
for (std::map<QString, QList<TOPPASResource> >::const_iterator it = map_.begin(); it != map_.end(); ++it)
{
const String& key = String(it->first);
const QList<TOPPASResource>& resource_list = it->second;
std::vector<std::string> url_list;
for (const TOPPASResource &res : resource_list)
{
url_list.push_back(String(res.getURL().toString().toStdString()));
}
save_param.setValue(key + ":url_list", url_list);
}
ParamXMLFile paramFile;
paramFile.store(String(file_name), save_param);
}
const QList<TOPPASResource>& TOPPASResources::get(const QString& key) const
{
if (map_.find(key) == map_.end())
{
return empty_list_;
}
return map_.at(key);
}
void TOPPASResources::clear()
{
map_.clear();
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerData1DChrom.cpp | .cpp | 3,164 | 89 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
#include <OpenMS/VISUAL/LayerData1DChrom.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/Painter1DBase.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
#include <QMenu>
using namespace std;
namespace OpenMS
{
std::unique_ptr<LayerStoreData> LayerData1DChrom::storeVisibleData(const RangeAllType& visible_range, const DataFilters& layer_filters) const
{
auto ret = std::make_unique<LayerStoreDataPeakMapVisible>();
ret->storeVisibleChromatogram(getCurrentChrom(), visible_range, layer_filters);
return ret;
}
std::unique_ptr<LayerStoreData> LayerData1DChrom::storeFullData() const
{
return LayerDataChrom::storeFullData(); // just forward
}
QMenu* LayerData1DChrom::getContextMenuAnnotation(Annotation1DItem* /*annot_item*/, bool& /*need_repaint*/)
{
auto* context_menu = new QMenu("Chrom1D", nullptr);
return context_menu;
}
PeakIndex LayerData1DChrom::findClosestDataPoint(const RangeAllType& area) const
{
ChromatogramPeak peak_lt {area.getMinRT(), area.getMinIntensity()}, peak_rb {area.getMaxRT(), area.getMaxIntensity()};
// reference to the current data
const auto& chrom = getCurrentChrom();
const Size index = getCurrentIndex();
// get iterator on first peak with lower position than interval_start
auto left_it = lower_bound(chrom.begin(), chrom.end(), peak_lt, ChromatogramPeak::PositionLess());
// get iterator on first peak with higher position than interval_end
auto right_it = lower_bound(left_it, chrom.end(), peak_rb, ChromatogramPeak::PositionLess());
if (left_it == right_it) // both are equal => no peak falls into this interval
{
return PeakIndex();
}
if (left_it == right_it - 1)
{
return PeakIndex(index, left_it - chrom.begin());
}
auto nearest_it = left_it;
const auto center_intensity = (peak_lt.getIntensity() + peak_rb.getIntensity()) * 0.5;
for (auto it = left_it; it != right_it; ++it)
{
if (abs(center_intensity - it->getIntensity()) < abs(center_intensity - nearest_it->getIntensity()))
{
nearest_it = it;
}
}
return PeakIndex(index, nearest_it - chrom.begin());
}
std::unique_ptr<Painter1DBase> LayerData1DChrom::getPainter1D() const
{
return make_unique<Painter1DChrom>(this);
}
Annotation1DItem* LayerData1DChrom::addPeakAnnotation(const PeakIndex& peak_index, const QString& text, const QColor& color)
{
auto peak = getCurrentChrom()[peak_index.peak];
auto* item = new Annotation1DPeakItem<decltype(peak)>(peak, text, color);
item->setSelected(false);
getCurrentAnnotations().push_front(item);
return item;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/EnhancedTabBarWidgetInterface.cpp | .cpp | 1,636 | 53 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/EnhancedTabBarWidgetInterface.h>
#include <OpenMS/VISUAL/EnhancedTabBar.h>
#include <QObject>
namespace OpenMS
{
EnhancedTabBarWidgetInterface::EnhancedTabBarWidgetInterface()
{
/// every new window gets a new ID automatically
static Int window_counter_ = getFirstWindowID();
window_id_ = ++window_counter_;
}
EnhancedTabBarWidgetInterface::~EnhancedTabBarWidgetInterface()
{ // we cannot emit signals (since we cannot derive from QObject), so we let our member do it
sp_.emitAboutToBeDestroyed(window_id_);
}
void EnhancedTabBarWidgetInterface::addToTabBar(EnhancedTabBar* const parent, const String& caption, const bool make_active_tab)
{
// use signal/slot to communicate, since directly storing the parent pointer for later access is dangerous (it may already be destroyed during program exit)
QObject::connect(&this->sp_, &SignalProvider::aboutToBeDestroyed, parent, &EnhancedTabBar::removeId);
parent->addTab(caption.toQString(), window_id_);
if (make_active_tab)
{
parent->show(window_id_);
}
}
Int EnhancedTabBarWidgetInterface::getWindowId() const
{
return window_id_;
}
/*static*/ Int EnhancedTabBarWidgetInterface::getFirstWindowID()
{
return 1234;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/RecentFilesMenu.cpp | .cpp | 3,272 | 140 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/RecentFilesMenu.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/SYSTEM/File.h>
#include <QAction>
/*
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <QAction>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
*/
using namespace std;
namespace OpenMS
{
RecentFilesMenu::RecentFilesMenu(int max_entries)
: recent_menu_("&Recent files"),
max_entries_(max_entries),
recent_files_()
{
// add hidden actions
recent_actions_.resize(max_entries_);
for (int i = 0; i < max_entries_; ++i)
{
recent_actions_[i] = recent_menu_.addAction("", this, &RecentFilesMenu::itemClicked_);
recent_actions_[i]->setVisible(false);
}
}
void RecentFilesMenu::set(const QStringList& initial)
{
recent_files_ = initial;
recent_files_.removeDuplicates();
while (recent_files_.size() > max_entries_)
{
recent_files_.removeLast();
}
sync_();
}
unsigned RecentFilesMenu::setFromParam(const Param& filenames)
{
QStringList rfiles;
unsigned count{ 0 };
for (Param::ParamIterator it = filenames.begin(); it != filenames.end(); ++it)
{
QString filename = String(it->value.toString()).toQString();
if (File::exists(filename))
{
rfiles.append(filename);
++count;
}
}
set(rfiles);
return count;
}
Param RecentFilesMenu::getAsParam() const
{
Param p;
int i{ 0 };
for (const auto& f : recent_files_)
{
p.setValue(String(i), f.toStdString());
++i;
}
return p;
}
QMenu* RecentFilesMenu::getMenu()
{
return &recent_menu_;
}
const QStringList& RecentFilesMenu::get() const
{
return recent_files_;
}
void RecentFilesMenu::add(const String& filename)
{
// find out absolute path
String tmp = File::absolutePath(filename);
// remove the new file if already in the recent list and prepend it
recent_files_.removeAll(tmp.toQString());
recent_files_.prepend(tmp.toQString());
// remove those files exceeding the defined number
while (recent_files_.size() > max_entries_)
{
recent_files_.removeLast();
}
sync_();
}
void RecentFilesMenu::itemClicked_()
{
QAction* action = qobject_cast<QAction*>(sender());
if (!action)
{
return;
}
String filename = String(action->text());
emit recentFileClicked(filename);
}
void RecentFilesMenu::sync_()
{
for (int i = 0; i < max_entries_; ++i)
{
if (i < recent_files_.size())
{
recent_actions_[i]->setText(recent_files_[i]);
recent_actions_[i]->setVisible(true);
}
else
{
recent_actions_[i]->setVisible(false);
}
}
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/SwathLibraryStats.cpp | .cpp | 2,824 | 78 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/SwathLibraryStats.h>
#include <ui_SwathLibraryStats.h>
#include <OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
using namespace std;
namespace OpenMS
{
SwathLibraryStats::SwathLibraryStats(QWidget* parent) :
QWidget(parent),
ui_(new Ui::SwathLibraryStats)
{
ui_->setupUi(this);
ui_->table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::ResizeToContents);
}
SwathLibraryStats::~SwathLibraryStats()
{
delete ui_;
}
void SwathLibraryStats::update(const TargetedExperiment::SummaryStatistics& stats)
{
auto getItem = [](const QString& text) {
auto item = new QTableWidgetItem(text);
item->setTextAlignment(Qt::AlignCenter);
return item;
};
// construct the table
ui_->table->setEditTriggers(QAbstractItemView::NoEditTriggers); // disable editing
ui_->table->setRowCount(1);
ui_->table->setColumnCount(5);
ui_->table->setHorizontalHeaderLabels(QStringList() << "# Proteins" << "# Peptides" << "# Transitions" << "Decoy Frequency (%)" << "Reference Status");
ui_->table->setItem(0, 0, getItem(QString::number(stats.protein_count)));
ui_->table->setItem(0, 1, getItem(QString::number(stats.peptide_count)));
ui_->table->setItem(0, 2, getItem(QString::number(stats.transition_count)));
using TYPE = ReactionMonitoringTransition::DecoyTransitionType;
auto count_copy = stats.decoy_counts; // allow to default construct missing values with 0 counts
size_t all = count_copy[TYPE::DECOY] +
count_copy[TYPE::TARGET] +
count_copy[TYPE::UNKNOWN];
if (all == 0)
{
all = 1; // avoid division by zero below
}
ui_->table->setItem(0, 3, getItem(QString::number(count_copy[TYPE::DECOY] * 100 / all)));
ui_->table->setItem(0, 4, getItem((!stats.contains_invalid_references ? "valid" : "invalid")));
}
void SwathLibraryStats::updateFromFile(const QString& pqp_file)
{
TargetedExperiment te;
TransitionPQPFile tr_file;
tr_file.setLogType(ProgressLogger::GUI);
tr_file.convertPQPToTargetedExperiment(pqp_file.toStdString().c_str(), te, true);
//OpenSwath::LightTargetedExperiment transition_exp;
//OpenSwathDataAccessHelper::convertTargetedExp(te, transition_exp);
update(te.getSummary());
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Plot2DWidget.cpp | .cpp | 10,076 | 268 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS
#include <OpenMS/VISUAL/Plot1DWidget.h>
#include <OpenMS/VISUAL/Plot2DWidget.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/DIALOGS/Plot2DGoToDialog.h>
#include <OpenMS/CONCEPT/UniqueIdInterface.h>
#include <OpenMS/VISUAL/LayerDataConsensus.h>
#include <OpenMS/VISUAL/LayerDataFeature.h>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QCheckBox>
#include <QtCore/QTimer>
using namespace std;
namespace OpenMS
{
using namespace Internal;
using namespace Math;
Plot2DWidget::Plot2DWidget(const Param& preferences, QWidget* parent) :
PlotWidget(preferences, parent)
{
setCanvas_(new Plot2DCanvas(preferences, this), 1, 2);
// add axes
y_axis_->setMinimumWidth(50);
// add projections
grid_->setColumnStretch(2, 3);
grid_->setRowStretch(1, 3);
projection_onto_X_ = new Plot1DWidget(Param(), DIM::Y, this);
projection_onto_X_->hide();
grid_->addWidget(projection_onto_X_, 0, 1, 1, 2);
projection_onto_Y_ = new Plot1DWidget(Param(), DIM::X, this);
projection_onto_Y_->hide();
grid_->addWidget(projection_onto_Y_, 1, 3, 2, 1);
connect(canvas(), &Plot2DCanvas::showProjections, this, &Plot2DWidget::showProjections_);
connect(canvas(), &Plot2DCanvas::toggleProjections, this, &Plot2DWidget::toggleProjections);
connect(canvas(), &Plot2DCanvas::visibleAreaChanged, this, &Plot2DWidget::autoUpdateProjections_);
// delegate signals from canvas
connect(canvas(), &Plot2DCanvas::showSpectrumAsNew1D, this, &Plot2DWidget::showSpectrumAsNew1D);
connect(canvas(), &Plot2DCanvas::showChromatogramsAsNew1D, this, &Plot2DWidget::showChromatogramsAsNew1D);
connect(canvas(), &Plot2DCanvas::showCurrentPeaksAsIonMobility, this, &Plot2DWidget::showCurrentPeaksAsIonMobility);
connect(canvas(), &Plot2DCanvas::showCurrentPeaksAs3D, this, &Plot2DWidget::showCurrentPeaksAs3D);
// add projections box
projection_box_ = new QGroupBox("Projections", this);
projection_box_->hide();
grid_->addWidget(projection_box_, 0, 3);
QGridLayout* box_grid = new QGridLayout(projection_box_);
QLabel* label = new QLabel("Peaks: ");
box_grid->addWidget(label, 0, 0);
projection_peaks_ = new QLabel("");
box_grid->addWidget(projection_peaks_, 0, 1);
label = new QLabel("Intensity sum: ");
box_grid->addWidget(label, 1, 0);
projection_sum_ = new QLabel("");
box_grid->addWidget(projection_sum_, 1, 1);
label = new QLabel("Maximum intensity: ");
box_grid->addWidget(label, 2, 0);
projection_max_ = new QLabel("");
box_grid->addWidget(projection_max_, 2, 1);
box_grid->setRowStretch(3, 2);
QPushButton* button = new QPushButton("Update", projection_box_);
connect(button, &QPushButton::clicked, canvas(), &Plot2DCanvas::pickProjectionLayer);
box_grid->addWidget(button, 4, 0);
projections_auto_ = new QCheckBox("Auto-update", projection_box_);
projections_auto_->setWhatsThis("When activated, projections are automatically updated one second after the last change of the visible area.");
projections_auto_->setChecked(true);
box_grid->addWidget(projections_auto_, 4, 1);
//set up projections auto-update
projections_timer_ = new QTimer(this);
projections_timer_->setSingleShot(true);
projections_timer_->setInterval(1000);
connect(projections_timer_, &QTimer::timeout, canvas(), &Plot2DCanvas::pickProjectionLayer);
}
void Plot2DWidget::projectionInfo_(int peaks, double intensity, double max)
{
projection_peaks_->setText(QString::number(peaks));
projection_sum_->setText(QString::number(intensity, 'f', 1));
projection_max_->setText(QString::number(max, 'f', 1));
}
void Plot2DWidget::recalculateAxes_()
{
// set names
x_axis_->setLegend(string(canvas()->getMapper().getDim(DIM::X).getDimName()));
y_axis_->setLegend(string(canvas()->getMapper().getDim(DIM::Y).getDimName()));
const auto& area = canvas()->getVisibleArea().getAreaXY();
x_axis_->setAxisBounds(area.minX(), area.maxX());
y_axis_->setAxisBounds(area.minY(), area.maxY());
}
void Plot2DWidget::toggleProjections()
{
if (projectionsVisible())
{
setMinimumSize(250, 250);
projection_box_->hide();
projection_onto_Y_->hide();
projection_onto_X_->hide();
grid_->setColumnStretch(3, 0);
grid_->setRowStretch(0, 0);
}
else
{
setMinimumSize(500, 500);
canvas()->pickProjectionLayer();
}
}
// projections
void Plot2DWidget::showProjections_(const LayerDataBase* source_layer)
{
auto [projection_ontoX, projection_ontoY, stats] =
source_layer->getProjection(canvas_->getMapper().getDim(DIM::X).getUnit(), canvas_->getMapper().getDim(DIM::Y).getUnit(), canvas_->getVisibleArea().getAreaUnit());
projectionInfo_(stats.number_of_datapoints, stats.sum_intensity, stats.max_intensity);
auto va = canvas()->getVisibleArea().getAreaXY();
projection_onto_Y_->showLegend(false);
projection_onto_Y_->setMapper({{DIM_UNIT::INT, canvas_->getMapper().getDim(DIM::Y).getUnit()}}); // must be done before addLayer()
projection_onto_Y_->canvas()->removeLayers();
projection_onto_Y_->canvas()->addLayer(std::move(projection_ontoY));
// manually set projected unit, since 'addPeakLayer' will guess a visible area, but we want the exact same scaling
projection_onto_Y_->canvas()->setVisibleAreaY(va.minY(), va.maxY());
grid_->setColumnStretch(3, 2);
projection_onto_X_->showLegend(false);
projection_onto_X_->setMapper({{canvas_->getMapper().getDim(DIM::X).getUnit(), DIM_UNIT::INT}}); // must be done before addLayer()
projection_onto_X_->canvas()->removeLayers();
projection_onto_X_->canvas()->addLayer(std::move(projection_ontoX));
// manually set projected unit, since 'addPeakLayer' will guess a visible area, but we want the exact same scaling
projection_onto_X_->canvas()->setVisibleAreaX(va.minX(), va.maxX());
grid_->setRowStretch(0, 2);
projection_box_->show();
projection_onto_X_->show();
projection_onto_Y_->show();
}
const Plot1DWidget* Plot2DWidget::getProjectionOntoX() const
{
return projection_onto_X_;
}
const Plot1DWidget* Plot2DWidget::getProjectionOntoY() const
{
return projection_onto_Y_;
}
void Plot2DWidget::showGoToDialog()
{
Plot2DGoToDialog goto_dialog(this,
canvas_->getMapper().getDim(DIM::X).getDimNameShort(),
canvas_->getMapper().getDim(DIM::Y).getDimNameShort());
//set range
const auto& area = canvas()->getVisibleArea().getAreaXY();
goto_dialog.setRange(area);
auto all_area_xy = canvas_->getMapper().mapRange(canvas_->getDataRange());
goto_dialog.setMinMaxOfRange(all_area_xy);
// feature numbers only for consensus&feature maps
goto_dialog.enableFeatureNumber(canvas()->getCurrentLayer().type == LayerDataBase::DT_FEATURE || canvas()->getCurrentLayer().type == LayerDataBase::DT_CONSENSUS);
// execute
if (goto_dialog.exec())
{
if (goto_dialog.showRange())
{
canvas()->setVisibleArea(goto_dialog.getRange());
}
else
{
String feature_id = goto_dialog.getFeatureNumber();
//try to convert to UInt64 id
UniqueIdInterface uid;
uid.setUniqueId(feature_id);
Size feature_index(-1); // TODO : not use -1
auto* lf = dynamic_cast<LayerDataFeature*>(&canvas()->getCurrentLayer());
auto* lc = dynamic_cast<LayerDataConsensus*>(&canvas()->getCurrentLayer());
if (lf)
{
feature_index = lf->getFeatureMap()->uniqueIdToIndex(uid.getUniqueId());
}
else if (lc)
{
feature_index = lc->getConsensusMap()->uniqueIdToIndex(uid.getUniqueId());
}
if (feature_index == Size(-1)) // UID does not exist
{
try
{
feature_index = feature_id.toInt(); // normal feature index as stored in map
}
catch (...) // we might still deal with a UID, so toInt() will throw as the number is too big
{
feature_index = Size(-1);
}
}
//check if the feature index exists
if ((lf && feature_index >= lf->getFeatureMap()->size()) || (lc && feature_index >= lc->getConsensusMap()->size()))
{
QMessageBox::warning(this, "Invalid feature number", "Feature number too large/UniqueID not found.\nPlease select a valid feature!");
return;
}
// display feature with a margin
RangeAllType range;
if (lf)
{
const FeatureMap& map = *lf->getFeatureMap();
const DBoundingBox<2> bb = map[feature_index].getConvexHull().getBoundingBox();
range.RangeRT::operator=(RangeBase{bb.minPosition()[0], bb.maxPosition()[0]});
range.RangeMZ::operator=(RangeBase{bb.minPosition()[1], bb.maxPosition()[1]});
}
else // Consensus Feature
{
const ConsensusFeature& cf = (*lc->getConsensusMap())[feature_index];
range = canvas_->getMapper().fromXY(canvas_->getMapper().map(cf));
}
range.RangeRT::extendLeftRight(30);
range.RangeMZ::extendLeftRight(5);
canvas()->setVisibleArea(range);
}
}
}
bool Plot2DWidget::projectionsVisible() const
{
return projection_onto_Y_->isVisible() || projection_onto_X_->isVisible();
}
void Plot2DWidget::autoUpdateProjections_()
{
if (projectionsVisible() && projections_auto_->isChecked())
{
projections_timer_->start();
}
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASToolVertex.cpp | .cpp | 43,474 | 1,301 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/DIALOGS/TOPPASToolConfigDialog.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <QtWidgets/QGraphicsScene>
#include <QtWidgets/QMessageBox>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QRegularExpression>
#include <QSvgRenderer>
#include <map>
namespace OpenMS
{
struct NameComponent
{
String prefix, suffix;
int counter = -1;
NameComponent() = default;
NameComponent(const String& r_prefix, const String& r_suffix)
: prefix(r_prefix),
suffix(r_suffix)
{}
String toString() const
{
return (prefix + (counter != -1 ? String("_") + String(counter).fillLeft('0', 3) : String()) + "." + suffix);
}
};
TOPPASToolVertex::TOPPASToolVertex()
: TOPPASToolVertex("", "")
{
}
TOPPASToolVertex::TOPPASToolVertex(const String& name, const String& type) :
name_(name),
type_(type)
{
brush_color_ = brush_color_.lighter(130); // make TOPP tools more white compared to all other nodes
initParam_();
connect(this, SIGNAL(toolStarted()), this, SLOT(toolStartedSlot()));
connect(this, SIGNAL(toolFinished()), this, SLOT(toolFinishedSlot()));
connect(this, SIGNAL(toolFailed()), this, SLOT(toolFailedSlot()));
connect(this, SIGNAL(toolCrashed()), this, SLOT(toolCrashedSlot()));
}
TOPPASToolVertex::TOPPASToolVertex(const TOPPASToolVertex& rhs) :
TOPPASVertex(rhs),
name_(rhs.name_),
type_(rhs.type_),
param_(rhs.param_),
status_(rhs.status_),
tool_ready_(rhs.tool_ready_)
{
}
TOPPASToolVertex& TOPPASToolVertex::operator=(const TOPPASToolVertex& rhs)
{
TOPPASVertex::operator=(rhs);
param_ = rhs.param_;
name_ = rhs.name_;
type_ = rhs.type_;
finished_ = rhs.finished_;
status_ = rhs.status_;
breakpoint_set_ = false;
return *this;
}
std::unique_ptr<TOPPASVertex> TOPPASToolVertex::clone() const
{
return std::make_unique<TOPPASToolVertex>(*this);
}
bool TOPPASToolVertex::initParam_(const QString& old_ini_file)
{
// this is the only exception for writing directly to the tmpDir, instead of a subdir of tmpDir, as scene()->getTempDir() might not be available yet
QString ini_file = File::getTemporaryFile().toQString();
QString program = File::findSiblingTOPPExecutable(name_).toQString();
QStringList arguments;
arguments << "-write_ini" << ini_file;
if (!type_.empty())
{
arguments << "-type";
arguments << type_.toQString();
}
// allow for update using old parameters
if (old_ini_file != "")
{
if (!File::exists(old_ini_file))
{
String msg = String("Could not open old INI file '") + old_ini_file + "'! File does not exist!";
if (getScene_() && getScene_()->isGUIMode())
{
QMessageBox::critical(nullptr, "Error", msg.c_str());
}
else
{
OPENMS_LOG_ERROR << msg << std::endl;
}
tool_ready_ = false;
return false;
}
arguments << "-ini" << old_ini_file;
}
// actually request the INI
QProcess p;
p.start(program, arguments);
if (!p.waitForFinished(-1) || p.exitStatus() != 0 || p.exitCode() != 0)
{
String msg = String("Error! Call to '") + program + "' '" + String(arguments.join("' '")) +
" returned with exit code (" + String(p.exitCode()) + "), exit status (" + String(p.exitStatus()) + ")." +
"\noutput:\n" + String(QString(p.readAll())) +
"\n";
if (getScene_() && getScene_()->isGUIMode())
{
QMessageBox::critical(nullptr, "Error", msg.c_str());
}
else
{
OPENMS_LOG_ERROR << msg << std::endl;
}
tool_ready_ = false;
return false;
}
if (!File::exists(ini_file))
{ // it would be weird to get here, since the TOPP tool ran successfully above, so INI file should exist, but nevertheless:
String msg = String("Could not open '") + ini_file + "'! It does not exist!";
if (getScene_() && getScene_()->isGUIMode())
{
QMessageBox::critical(nullptr, "Error", msg.c_str());
}
else
{
OPENMS_LOG_ERROR << msg << std::endl;
}
tool_ready_ = false;
return false;
}
Param tmp_param;
ParamXMLFile().load(String(ini_file).c_str(), tmp_param);
// remember the parameters of this tool
param_ = tmp_param.copy(name_ + ":1:", true); // get first instance (we never use more -- this is a legacy layer in paramXML)
param_.setValue("no_progress", "true"); // by default, we do not want each tool to report loading/status statistics (would clutter the log window)
// the user is free however, to re-enable it for individual nodes
// write to disk to see if anything has changed
writeParam_(param_, ini_file);
bool changed = false;
if (old_ini_file != "")
{
//check if INI file has changed (quick & dirty by file size)
QFile q_ini(ini_file);
QFile q_old_ini(old_ini_file);
changed = q_ini.size() != q_old_ini.size();
}
setToolTip(String(param_.getSectionDescription(name_)).toQString());
return changed;
}
void TOPPASToolVertex::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* /*e*/)
{
editParam();
}
void TOPPASToolVertex::editParam()
{
// use a copy for editing
Param edit_param(param_);
QVector<String> hidden_entries;
// remove entries that are handled by edges already, user should not see them
QVector<IOInfo> input_infos = getInputParameters();
for (ConstEdgeIterator it = inEdgesBegin(); it != inEdgesEnd(); ++it)
{
int index = (*it)->getTargetInParam();
if (index < 0)
{
continue;
}
const String& name = input_infos[index].param_name;
if (edit_param.exists(name))
{
hidden_entries.push_back(name);
}
}
QVector<IOInfo> output_infos = getOutputParameters();
for (ConstEdgeIterator it = outEdgesBegin(); it != outEdgesEnd(); ++it)
{
int index = (*it)->getSourceOutParam();
if (index < 0)
{
continue;
}
const String& name = output_infos[index].param_name;
if (edit_param.exists(name))
{
hidden_entries.push_back(name);
}
}
// remove entries explained by edges
for (const String &name : hidden_entries)
{
edit_param.remove(name);
}
// edit_param no longer contains tool description, take it from the node tooltip
QWidget* parent_widget = qobject_cast<QWidget*>(scene()->parent());
String default_dir;
TOPPASToolConfigDialog dialog(parent_widget, edit_param, default_dir, name_, type_, toolTip(), hidden_entries);
if (dialog.exec())
{
// take new values
param_.update(edit_param);
reset(true);
emit parameterChanged(doesParamChangeInvalidate_());
}
getScene_()->updateEdgeColors();
}
TOPPASScene* TOPPASToolVertex::getScene_() const
{
return qobject_cast<TOPPASScene*>(scene());
}
bool TOPPASToolVertex::doesParamChangeInvalidate_()
{
return status_ == TOPPASToolVertex::TOOL_SCHEDULED || // all stati that will not tolerate a change in parameters
status_ == TOPPASToolVertex::TOOL_RUNNING ||
status_ == TOPPASToolVertex::TOOL_SUCCESS;
}
bool TOPPASToolVertex::invertRecylingMode()
{
allow_output_recycling_ = !allow_output_recycling_;
emit parameterChanged(doesParamChangeInvalidate_()); // using 'true' is very conservative but safe. One could override this in child classes.
return allow_output_recycling_;
}
QVector<TOPPASToolVertex::IOInfo> TOPPASToolVertex::getInputParameters() const
{
return getParameters_(true);
}
QVector<TOPPASToolVertex::IOInfo> TOPPASToolVertex::getOutputParameters() const
{
return getParameters_(false);
}
QVector<TOPPASToolVertex::IOInfo> TOPPASToolVertex::getParameters_(bool input_params) const
{
QVector<IOInfo> io_infos;
auto add_params = [&](const String& search_tag) {
for (Param::ParamIterator it = param_.begin(); it != param_.end(); ++it)
{
if (! it->tags.count(search_tag)) continue; // skip irrelevant parameters
StringList valid_types(ListUtils::toStringList<std::string>(it->valid_strings));
for (Size i = 0; i < valid_types.size(); ++i)
{
if (! valid_types[i].hasPrefix("*."))
{
std::cerr << "Invalid restriction \"" + valid_types[i] + "\"" + " for parameter \"" + it->name + "\"!" << std::endl;
break;
}
valid_types[i] = valid_types[i].suffix(valid_types[i].size() - 2);
}
IOInfo io_info;
io_info.param_name = it.getName();
io_info.valid_types = valid_types;
if (it->value.valueType() == ParamValue::STRING_LIST)
{
io_info.type = IOInfo::IOT_LIST;
}
else if (it->value.valueType() == ParamValue::STRING_VALUE)
{
io_info.type = search_tag == TOPPBase::TAG_OUTPUT_DIR ?IOInfo::IOT_DIR : IOInfo::IOT_FILE;
}
else { std::cerr << "TOPPAS: Unexpected parameter value!" << std::endl; }
io_infos.push_back(io_info);
}
};
if (input_params)
{
add_params(TOPPBase::TAG_INPUT_FILE);
}
else
{
add_params(TOPPBase::TAG_OUTPUT_FILE);
add_params(TOPPBase::TAG_OUTPUT_DIR);
}
// order in param can change --> sort
std::sort(io_infos.begin(), io_infos.end());
return io_infos;
}
void TOPPASToolVertex::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
TOPPASVertex::paint(painter, option, widget, false);
QString draw_str = (type_.empty() ? name_ : name_ + " (" + type_ + ")").toQString();
for (int i = 0; i < 10; ++i)
{
QString prev_str = draw_str;
draw_str = toolnameWithWhitespacesForFancyWordWrapping_(painter, draw_str);
if (draw_str == prev_str)
{
break;
}
}
QRectF text_boundings = painter->boundingRect(QRectF(-65, -35, 130, 70), Qt::AlignCenter | Qt::TextWordWrap, draw_str);
painter->drawText(text_boundings, Qt::AlignCenter | Qt::TextWordWrap, draw_str);
if (status_ != TOOL_READY)
{
QString text = QString::number(round_counter_) + " / " + QString::number(round_total_);
QRectF text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText((int)(62.0 - text_boundings.width()), 48, text);
}
// progress light
painter->setPen(Qt::black);
QColor progress_color;
switch (status_)
{
case TOOL_READY:
progress_color = Qt::lightGray; break;
case TOOL_SCHEDULED:
progress_color = Qt::darkBlue; break;
case TOOL_RUNNING:
progress_color = Qt::yellow; break;
case TOOL_SUCCESS:
progress_color = Qt::green; break;
case TOOL_CRASH:
progress_color = Qt::red; break;
default:
progress_color = Qt::magenta; break; // signal weird status by color
}
painter->setBrush(progress_color);
painter->drawEllipse(46, -52, 14, 14);
// breakpoint set?
if (breakpoint_set_)
{
QSvgRenderer* svg_renderer = new QSvgRenderer(QString(":/stop_sign.svg"), nullptr);
painter->setOpacity(0.35);
svg_renderer->render(painter, QRectF(-60, -60, 120, 120));
}
}
QString TOPPASToolVertex::toolnameWithWhitespacesForFancyWordWrapping_(QPainter* painter, const QString& str)
{
qreal max_width = 130;
QStringList parts = str.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
QStringList new_parts;
for(const QString& part : parts)
{
QRectF text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter | Qt::TextWordWrap, part);
if (text_boundings.width() <= max_width)
{
//word not too long
new_parts.append(part);
}
else
{
//word too long -> insert space at reasonable position -> Qt::TextWordWrap can break the line there
int last_capital_index = 1;
for (int i = 1; i <= part.size(); ++i)
{
QString tmp_str = part.left(i);
//remember position of last capital letter
if (tmp_str.at(i - 1).isUpper())
{
last_capital_index = i;
}
QRectF text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter | Qt::TextWordWrap, tmp_str);
if (text_boundings.width() > max_width)
{
//break line at next capital letter before this position
new_parts.append(part.left(last_capital_index - 1) + "-");
new_parts.append(part.right(part.size() - last_capital_index + 1));
break;
}
}
}
}
return new_parts.join(" ");
}
QRectF TOPPASToolVertex::boundingRect() const
{
return QRectF(-71, -61, 142, 122);
}
String TOPPASToolVertex::getName() const
{
return name_;
}
const String& TOPPASToolVertex::getType() const
{
return type_;
}
void TOPPASToolVertex::run()
{
__DEBUG_BEGIN_METHOD__
//check if everything ready (there might be more than one upstream node - ALL need to be ready)
if (!isUpstreamFinished())
{
return;
}
if (finished_)
{
OPENMS_LOG_ERROR << "This should not happen. Calling an already finished node '" << this->name_ << "' (#" << this->getTopoNr() << ")!" << std::endl;
throw Exception::IllegalSelfOperation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
TOPPASScene* ts = getScene_();
QString ini_file = ts->getTempDir()
+ QDir::separator()
+ getOutputDir().toQString()
+ QDir::separator()
+ name_.toQString();
if (!type_.empty())
{
ini_file += "_" + type_.toQString();
}
// do not write the ini yet - we might need to alter it
RoundPackages pkg;
String error_msg("");
bool success = buildRoundPackages(pkg, error_msg);
if (!success)
{
OPENMS_LOG_ERROR << "Could not retrieve input files from upstream nodes...\n";
emit toolFailed(-1, error_msg.toQString());
return;
}
// all inputs are ready --> GO!
if (!updateCurrentOutputFileNames(pkg, error_msg)) // based on input, we prepare output names
{
emit toolFailed(-1, error_msg.toQString());
return;
}
createDirs();
//emit toolStarted(); //disabled! Every signal emitted here does only mean the process is queued(!) not that its executed right away
/// update round status
round_total_ = (int) pkg.size(); // take number of rounds from previous tool(s) - should all be equal
round_counter_ = 0; // once round_counter_ reaches round_total_, we are done
QStringList shared_args;
if (!type_.empty())
{
shared_args << "-type" << type_.toQString();
}
// get *all* input|output file parameters (regardless if edge exists)
QVector<IOInfo> in_params = getInputParameters(), out_params = getOutputParameters();
bool ini_round_dependent = false; // indicates if we need a new INI file for each round (usually GenericWrapper issue)
// maximum number of filenames per TOPP parameter file-list to put on the commandline
// If more filenames are needed, e.g. for MapAligner's -in/-out etc., they are put in the .INI file
// to avoid exceeding the 8KB length limit of the Windows commandline
static constexpr int MAX_FILES_CMDLINE {10};
for (int round = 0; round < round_total_; ++round)
{
debugOut_(String("Enqueueing process nr ") + round + "/" + round_total_);
QStringList args = shared_args;
// we might need to modify input/output file parameters before storing to INI
Param param_tmp = param_;
/// INCOMING EDGES
for (RoundPackageConstIt ite = pkg[round].begin();
ite != pkg[round].end();
++ite)
{
TOPPASEdge incoming_edge = *(ite->second.edge);
int param_index = incoming_edge.getTargetInParam();
if (param_index < 0 || param_index >= in_params.size())
{
OPENMS_LOG_ERROR << "TOPPAS: Input parameter index out of bounds!" << std::endl;
return;
}
String param_name = in_params[param_index].param_name;
const QStringList& file_list = ite->second.filenames.get();
bool store_to_ini = false;
// check for GenericWrapper input/output files and put them in INI file:
// OR if there are a lot of input files (which might exceed the 8k length limit of cmd.exe on Windows)
if (param_name.hasPrefix("ETool:") || file_list.size() > MAX_FILES_CMDLINE)
{
store_to_ini = true;
ini_round_dependent = true;
}
if (!store_to_ini)
{
args << "-" + param_name.toQString() << file_list;
}
else
{
if (param_tmp.getValue(param_name).valueType() == ParamValue::STRING_LIST)
{
param_tmp.setValue(param_name, ListUtils::create<std::string>(StringListUtils::fromQStringList(file_list)));
}
else
{
if (file_list.size() > 1)
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Multiple files were given to a param which supports only single files! ('" + param_name + "')");
}
param_tmp.setValue(param_name, String(file_list[0]));
}
}
}
// OUTGOING EDGES (output files and output folders)
// ;output names are already prepared by 'updateCurrentOutputFileNames()'
typedef RoundPackage::iterator EdgeIndexIt;
for (EdgeIndexIt it_edge = output_files_[round].begin();
it_edge != output_files_[round].end();
++it_edge)
{
int param_index = it_edge->first;
String param_name = out_params[param_index].param_name;
bool store_to_ini = false;
const QStringList& output_files = output_files_[round][param_index].filenames.get();
// check for GenericWrapper input/output files and put them in INI file:
// OR if there are a lot of input files (which might exceed the 8k length limit of cmd.exe on Windows)
if (param_name.hasPrefix("ETool:") || output_files.size() > MAX_FILES_CMDLINE)
{
store_to_ini = true;
ini_round_dependent = true;
}
if (!store_to_ini)
{
args << "-" + param_name.toQString() << output_files;
}
else
{
if (param_tmp.getValue(param_name).valueType() == ParamValue::STRING_LIST)
{
param_tmp.setValue(param_name, ListUtils::create<std::string>(StringListUtils::fromQStringList(output_files)));
}
else
{
if (output_files.size() > 1)
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Multiple files were given to a param which supports only single files! ('" + param_name + "')");
}
param_tmp.setValue(param_name, String(output_files[0]));
}
}
}
// each iteration might have different params (input/output items which are registered in subsections (GenericWrapper stuff))
QString ini_file_iteration;
if (ini_round_dependent)
{
ini_file_iteration = QDir::toNativeSeparators(ini_file + QString::number(round) + ".ini");
}
else
{
ini_file_iteration = QDir::toNativeSeparators(ini_file + ".ini");
}
writeParam_(param_tmp, ini_file_iteration);
args << "-ini" << ini_file_iteration;
// create process
QProcess* p;
if (!ts->isDryRun())
{
p = new QProcess();
}
else
{
p = new FakeProcess();
}
p->setProcessChannelMode(QProcess::MergedChannels);
connect(p, SIGNAL(readyReadStandardOutput()), this, SLOT(forwardTOPPOutput()));
connect(ts, SIGNAL(terminateCurrentPipeline()), p, SLOT(kill()));
// let this node know that round is done
connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(executionFinished(int, QProcess::ExitStatus)));
// enqueue process
String msg_enqueue = String("\nEnqueue: \"") + File::getExecutablePath() + name_ + "\" \"" + String(args.join("\" \"")) + "\"\n";
if (round == 0)
{
// active if TOPPAS is run with --debug; will print to console
OPENMS_LOG_DEBUG << msg_enqueue << std::endl;
// show sys-call in logWindow of TOPPAS (or console for non-gui)
if ((int) param_tmp.getValue("debug") > 0)
{
ts->logTOPPOutput(msg_enqueue.toQString());
}
}
toolScheduledSlot();
ts->enqueueProcess(TOPPASScene::TOPPProcess(p, File::findSiblingTOPPExecutable(name_).toQString(), args, this));
}
// run pending processes
ts->runNextProcess();
__DEBUG_END_METHOD__
}
void TOPPASToolVertex::emitToolStarted()
{
emit toolStarted();
}
void TOPPASToolVertex::executionFinished(int ec, QProcess::ExitStatus es)
{
__DEBUG_BEGIN_METHOD__
TOPPASScene* ts = getScene_();
QProcess* p = qobject_cast<QProcess*>(QObject::sender());
RAIICleanup clean([&]() {
// clean up at end
if (p)
{
delete p;
}
ts->processFinished();
});
//** ERROR handling
if (es != QProcess::NormalExit)
{
emit toolCrashed();
}
else if (ec != 0)
{
emit toolFailed(ec);
}
else
{
//** no error ... proceed
++round_counter_;
//std::cout << (String("Increased iteration_nr_ to ") + round_counter_ + " / " + round_total_ ) << " for " << this->name_ << std::endl;
if (round_counter_ == round_total_) // all iterations performed --> proceed in pipeline
{
debugOut_("All iterations finished!");
if (finished_)
{
OPENMS_LOG_ERROR << "SOMETHING is very fishy. The vertex is already set to finished, yet there was still a thread spawning..." << std::endl;
throw Exception::IllegalSelfOperation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
if (!ts->isDryRun())
{
renameOutput_(); // rename generated files by content
emit toolFinished();
}
finished_ = true;
if (!breakpoint_set_)
{
// call all children, proceed in pipeline
for (ConstEdgeIterator it = outEdgesBegin(); it != outEdgesEnd(); ++it)
{
TOPPASVertex* tv = (*it)->getTargetVertex();
debugOut_(String("Starting child ") + tv->getTopoNr());
tv->run();
}
debugOut_("All children started!");
}
}
}
__DEBUG_END_METHOD__
}
bool TOPPASToolVertex::renameOutput_()
{
// get all output names
QStringList files = this->getFileNames();
std::map<String, NameComponent> name_old_to_new;
std::map<String, int> name_new_count, name_new_idx; // count occurrence (for optional counter infix)
// a first round to find which filenames are not unique (and require augmentation with a counter)
for (const QString& file : files)
{
if (File::isDirectory(file)) continue; // skip output directories
String new_prefix = FileHandler::stripExtension(file);
String new_suffix = FileTypes::typeToName(FileHandler::getTypeByContent(file)); // this might replace bla.fasta with bla.FASTA ... which is the same file on Windows
if (file.endsWith(new_suffix.toQString(), Qt::CaseInsensitive)) // --> use the native suffix (to avoid deleting the source file when renaming)
{
new_suffix = String(file).suffix(new_suffix.size());
}
NameComponent nc(new_prefix, new_suffix);
name_old_to_new[file] = nc;
++name_new_count[nc.toString()];
}
// for all names which occur more than once, introduce a counter
for (const QString& file : files)
{
if (name_new_count[name_old_to_new[file].toString()] > 1) // candidate for counter
{
name_old_to_new[file].counter = ++name_new_idx[name_old_to_new[file].toString()]; // start at index 1
}
}
for (Size i = 0; i < output_files_.size(); ++i)
{
for (RoundPackageIt it = output_files_[i].begin();
it != output_files_[i].end();
++it)
{
for (int fi = 0; fi < it->second.filenames.size(); ++fi)
{
// skip output directories
if (File::isDirectory(it->second.filenames[fi]))
{
continue;
}
// rename file and update record
String old_filename = QDir::toNativeSeparators(it->second.filenames[fi]);
String new_filename = QDir::toNativeSeparators(name_old_to_new[it->second.filenames[fi]].toString().toQString());
if (QFileInfo(old_filename.toQString()).canonicalFilePath() == QFileInfo(new_filename.toQString()).canonicalFilePath())
{ // source and target are identical -- no action required
continue;
}
QFile file(old_filename.toQString());
if (File::exists(new_filename))
{ // rename only works if the target file does not exist: delete it first
bool success = File::remove(new_filename);
if (!success)
{
OPENMS_LOG_ERROR << "Could not remove '" << new_filename << "'.\n";
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, new_filename);
}
}
bool success = file.rename(new_filename.toQString());
if (!success)
{
OPENMS_LOG_ERROR << "Could not rename '" << String(it->second.filenames[fi]) << "' to '" << new_filename << "'\n";
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, new_filename);
}
it->second.filenames.set(new_filename.toQString(), fi);
}
}
}
return true;
}
const Param& TOPPASToolVertex::getParam()
{
return param_;
}
void TOPPASToolVertex::setParam(const Param& param)
{
param_ = param;
}
TOPPASToolVertex::TOOLSTATUS TOPPASToolVertex::getStatus() const
{
return status_;
}
bool TOPPASToolVertex::updateCurrentOutputFileNames(const RoundPackages& pkg, String& error_msg)
{
const auto number_of_rounds = pkg.size();
if (pkg.empty())
{
error_msg = "Less than one round received from upstream tools. Something is fishy!\n";
OPENMS_LOG_ERROR << error_msg;
return false;
}
QVector<IOInfo> out_params = getOutputParameters();
// check if this tool outputs a list of files, or only single files
bool has_only_singlefile_output = !IOInfo::isAnyList(out_params);
// look for the input with the most files in round 0 (as this is the maximal number of output files we can produce)
// we assume the number of files is equal in all rounds...
int max_size_index(-1);
int max_size(-1);
// iterate over input edges
for (RoundPackageConstIt it = pkg[0].begin();
it != pkg[0].end();
++it)
{
if (it->second.edge->getSourceVertex()->isRecyclingEnabled())
{ // skip recycling input nodes
continue;
}
// we only need to find a good upstream node with a single file -- since we only output single files
if (has_only_singlefile_output)
{ // .. take any non-recycled input edge, preferably from 'in' and/or single inputs
if ((max_size < 1 || (it->second.edge->getTargetInParamName() == "in") || it->second.filenames.size() == 1))
{
max_size_index = it->first;
max_size = 1;
}
}
else if ((it->second.filenames.size() > max_size) || // either just larger
// ... or it's from '-in' (which we prefer as naming source).. only for non-recycling -in though
((it->second.filenames.size () == max_size) && (it->second.edge->getTargetInParamName() == "in")))
{
max_size_index = it->first;
max_size = it->second.filenames.size();
}
}
if (max_size_index == -1)
{
error_msg = "Did not find upstream nodes with un-recycled names. Something is fishy!\n";
OPENMS_LOG_ERROR << error_msg;
return false;
}
// now we construct output filenames for this node
// use names from the selected upstream vertex (hoping that this is the maximal number of files we are going to produce)
std::vector<QStringList> per_round_basenames;
for (Size i = 0; i < number_of_rounds; ++i)
{
QStringList filenames = pkg[i].find(max_size_index)->second.filenames.get();
//
// remove suffix to avoid chaining .mzML.idxml.tsv
// a new suffix is added later, depending on edge-type etc
//
// try to find the type (only by looking at the suffix); not doing it manually, since it could be .mzXML.gz
for (QString& filename : filenames)
{
filename = FileHandler::stripExtension(filename).toQString();
}
per_round_basenames.push_back(filenames);
//std::cerr << " output filenames (round " << i <<"): " << per_round_basenames.back().join(", ") << std::endl;
}
// maybe we find something more unique, e.g. last base directory if all filenames are equal
smartFileNames_(per_round_basenames);
// clear output file list
output_files_.clear();
output_files_.resize(number_of_rounds);
const TOPPASScene* ts = getScene_();
// output names for each outgoing edge
for (int i = 0; i < out_params.size(); ++i)
{
// search for an out edge for this parameter (not required to exist)
int param_index;
TOPPASEdge* edge_out(nullptr);
for (ConstEdgeIterator it_edge = outEdgesBegin(); it_edge != outEdgesEnd(); ++it_edge)
{
param_index = (*it_edge)->getSourceOutParam();
if (i == param_index) // corresponding out edge found
{
edge_out = *it_edge;
break;
}
}
if (!edge_out)
{
continue;
}
// determine output file format if possible (for suffix)
String file_suffix;
if (out_params[i].type == IOInfo::IOT_DIR)
{
file_suffix = "_dir"; // we need something non-empty
}
// Single file or list of files
else if (out_params[i].valid_types.size() == 1)
{ // only one format allowed
auto t = FileTypes::nameToType(out_params[i].valid_types[0]);
if (t != FileTypes::UNKNOWN)
{ // only use canonical names for suffixes, i.e. exact upper/lowercase match, i.e. always use "consensusXML", not "ConsensusXML" or "cOnsensusXML"
// (TOPPAS requires this, to avoid errors when copying temporary files)
file_suffix = "." + FileTypes::typeToName(t);
}
else
{ // unknown type... just use it as it is
file_suffix = "." + out_params[i].valid_types[0];
}
}
else if (String p_out_format = out_params[i].param_name + "_type"; // expected parameter name which determines output format
param_.exists(p_out_format))
{ // 'out_type' or alike is specified
if (!param_.getValue(p_out_format).toString().empty())
{
file_suffix = "." + param_.getValue(p_out_format).toString();
}
else
{
OPENMS_LOG_WARN << "TOPPAS cannot determine output file format for param '" << out_params[i].param_name
<< "' of Node " + this->name_ + "(" + String(this->getTopoNr()) + "). Format is ambiguous. Use parameter '" + p_out_format + "' to name intermediate output correctly!\n";
}
}
if (file_suffix.empty())
{
// Are we FileMerger? If so we can recover the out_type from the type of our input files
if (name_ == "FileMerger")
{
// For this very specific case we know that all the upstream nodes have to have the same types
file_suffix = "." + param_.getValue("in_type").toString();
}
// tag as unknown (TOPPAS will try to rename the output file once its written - see renameOutput_())
else
{
OPENMS_LOG_DEBUG << " unknown extension for : " << out_params[i].param_name << " in: " << name_ <<"\n";
file_suffix = ".unknown";
}
}
//std::cerr << "suffix is: " << file_suffix << "\n\n";
// create common path of output files
QString path = ts->getTempDir()
+ QDir::separator()
+ getOutputDir().toQString() // includes TopoNr
+ QDir::separator()
+ out_params[param_index].param_name.remove(':').toQString().left(50) // max 50 chars per subdir
+ QDir::separator();
VertexRoundPackage vrp;
vrp.edge = edge_out;
std::set<QString> filename_output_set; // verify that output files are unique (avoid overwriting)
assert(per_round_basenames.size() == number_of_rounds);
for (Size round = 0; round < number_of_rounds; ++round)
{
// store edge for this param for all rounds
output_files_[round][param_index] = vrp; // index by index of source-out param
// list --> single file (e.g. IDMerger or FileMerger)
bool list_to_single = (per_round_basenames[round].size() > 1 && out_params[param_index].type == IOInfo::IOT_FILE);
for (const QString &input_file : per_round_basenames[round])
{
QString fn = path + QFileInfo(input_file).fileName(); // out_path + filename
OPENMS_LOG_DEBUG << "Single:" << fn.toStdString() << "\n";
if (out_params[param_index].type == IOInfo::IOT_DIR)
{ // output is a directory
fn = QDir::toNativeSeparators(path);
if (number_of_rounds > 1)
{ // use a different output folder for each round if multiple rounds are present
fn += QFileInfo(input_file).baseName();
}
output_files_[round][param_index].filenames.push_back(fn);
OPENMS_LOG_DEBUG << "Dir:" << fn.toStdString() << "\n";
break; // only one iteration required (there is only one output dir per output param, irrespective of #input files)
}
else if (list_to_single)
{
if (fn.contains(QRegularExpression(".*_to_.*_mrgd")))
{
fn = fn.left(fn.indexOf("_to_"));
OPENMS_LOG_DEBUG << " first merge in merge: " << fn.toStdString() << "\n";
}
QString fn_last = QFileInfo(per_round_basenames[round].last()).fileName();
if (fn_last.contains(QRegularExpression(".*_to_.*_mrgd")))
{
int i_start = fn_last.indexOf("_to_") + 4;
fn_last = fn_last.mid(i_start, fn_last.indexOf("_mrgd", i_start) - i_start);
OPENMS_LOG_DEBUG << " last merge in merge: " << fn_last.toStdString() << "\n";
}
fn += "_to_" + fn_last + "_mrgd";
OPENMS_LOG_DEBUG << " List: ..." << "_to_" + fn_last.toStdString() + "_mrgd" << "\n";
}
if (!fn.endsWith(file_suffix.toQString()))
{
fn += file_suffix.toQString();
OPENMS_LOG_DEBUG << " Suffix-add: " << file_suffix << "\n";
}
fn = QDir::toNativeSeparators(fn);
output_files_[round][param_index].filenames.push_back(fn);
if (list_to_single)
{
break; // only one iteration required
}
if (auto [it, newly_inserted] = filename_output_set.insert(fn); !newly_inserted)
{
error_msg = "TOPPAS failed to build correct filenames. Please report this bug, along with your Pipeline\n!";
OPENMS_LOG_ERROR << error_msg;
return false;
}
}
} // end for rounds
//std::cerr << "output filenames (" << out_params[i].param_name <<") final: " << ListUtils::concatenate< std::set<QString> >(filename_output_set, ", ") << std::endl;
} // end for out params (each edge)
return true;
}
void TOPPASToolVertex::smartFileNames_(std::vector<QStringList>& filenames)
{
/* TODO:
* implement this carefully; also take care of what happens after the call
* of this method in updateCurrentOutputFileNames()
*/
// special case #1, only one filename in each round (at least 2 rounds), with different directory but same basename
// --> use LAST directory as new name, e.g. 'subdir' from 'c:\mydir\subdir\samesame.mzML'
bool passes_constraints = false;
if (filenames.size() > 1) // more than one round
{
passes_constraints = true;
for (Size i = 1; i < filenames.size(); ++i)
{
if ((filenames[i].size() > 1) // one file per round AND unique filename
|| (QFileInfo(filenames[0][0]).fileName() != QFileInfo(filenames[i][0]).fileName()))
{
passes_constraints = false;
break;
}
}
}
if (passes_constraints) // rename
{
for (Size i = 0; i < filenames.size(); ++i)
{
QString p = QDir::toNativeSeparators(QFileInfo(filenames[i][0]).canonicalPath());
if (p.isEmpty())
{
continue;
}
//std::cout << "PATH: " << p << "\n";
String tmp = String(p).suffix(String(QString(QDir::separator()))[0]);
//std::cout << "INTER: " << tmp << "\n";
if (tmp.size() <= 2 || tmp.has(':'))
{
continue; // too small to be reliable; might even be 'c:'
}
filenames[i][0] = tmp.toQString();
//std::cout << " -->: " << filenames[i][0] << "\n";
}
return; // we do not want the next special case on top of this...
}
// possibilities for more good naming schemes...
// special case #2 ...
return;
}
void TOPPASToolVertex::forwardTOPPOutput()
{
QProcess* p = qobject_cast<QProcess*>(QObject::sender());
if (!p)
{
return;
}
QString out = p->readAllStandardOutput();
emit toppOutputReady(out);
}
void TOPPASToolVertex::toolStartedSlot()
{
status_ = TOOL_RUNNING;
update(boundingRect());
}
void TOPPASToolVertex::toolFinishedSlot()
{
status_ = TOOL_SUCCESS;
update(boundingRect());
}
void TOPPASToolVertex::toolScheduledSlot()
{
status_ = TOOL_SCHEDULED;
update(boundingRect());
}
void TOPPASToolVertex::toolFailedSlot()
{
status_ = TOOL_CRASH;
update(boundingRect());
}
void TOPPASToolVertex::toolCrashedSlot()
{
status_ = TOOL_CRASH;
update(boundingRect());
}
void TOPPASToolVertex::inEdgeHasChanged()
{
// something has changed --> tmp files might be invalid --> reset
reset(true);
TOPPASVertex::inEdgeHasChanged();
}
void TOPPASToolVertex::outEdgeHasChanged()
{
// something has changed --> tmp files might be invalid --> reset
reset(true);
TOPPASVertex::outEdgeHasChanged();
}
void TOPPASToolVertex::openContainingFolder() const
{
QString path = getFullOutputDirectory().toQString();
GUIHelpers::openFolder(path);
}
String TOPPASToolVertex::getFullOutputDirectory() const
{
TOPPASScene* ts = getScene_();
return QDir::toNativeSeparators(ts->getTempDir() + QDir::separator() + getOutputDir().toQString());
}
String TOPPASToolVertex::getOutputDir() const
{
TOPPASScene* ts = getScene_();
String workflow_dir = FileHandler::stripExtension(File::basename(ts->getSaveFileName()));
if (workflow_dir.empty())
{
workflow_dir = "Untitled_workflow";
}
String dir = workflow_dir +
String(QDir::separator()) +
get3CharsNumber_(topo_nr_) + "_" + getName();
if (!getType().empty())
{
dir += "_" + getType();
}
return dir;
}
void TOPPASToolVertex::createDirs()
{
QDir dir;
if (!dir.mkpath(getFullOutputDirectory().toQString()))
{
OPENMS_LOG_ERROR << "TOPPAS: Could not create path " << getFullOutputDirectory() << std::endl;
}
// subsdirectories named after the output parameter name
QStringList files = this->getFileNames();
for (const QString &file : files)
{
QString sdir = File::path(file).toQString();
if (!File::exists(sdir))
{
if (!dir.mkpath(sdir))
{
OPENMS_LOG_ERROR << "TOPPAS: Could not create path " << String(sdir) << std::endl;
}
}
}
}
void TOPPASToolVertex::setTopoNr(UInt nr)
{
if (topo_nr_ != nr)
{
// topological number changes --> output dir changes --> reset
reset(true);
topo_nr_ = nr;
emit somethingHasChanged();
}
}
void TOPPASToolVertex::reset(bool reset_all_files)
{
__DEBUG_BEGIN_METHOD__
finished_ = false;
status_ = TOOL_READY;
output_files_.clear();
if (reset_all_files)
{
QString remove_dir = getFullOutputDirectory().toQString();
if (File::exists(remove_dir))
{
File::removeDirRecursively(remove_dir);
}
}
TOPPASVertex::reset(reset_all_files);
__DEBUG_END_METHOD__
}
bool TOPPASToolVertex::refreshParameters()
{
TOPPASScene* ts = getScene_();
QString old_ini_file = ts->getTempDir() + QDir::separator() + "TOPPAS_" + name_.toQString() + "_";
if (!type_.empty())
{
old_ini_file += type_.toQString() + "_";
}
old_ini_file += File::getUniqueName().toQString() + "_tmp_OLD.ini";
writeParam_(param_, old_ini_file);
bool changed = initParam_(old_ini_file);
QFile::remove(old_ini_file);
return changed;
}
bool TOPPASToolVertex::isToolReady() const
{
return tool_ready_;
}
void TOPPASToolVertex::writeParam_(const Param& param, const QString& ini_file)
{
Param save_param;
save_param.setValue(name_ + ":1:toppas_dummy", "blub");
save_param.insert(name_ + ":1:", param);
save_param.remove(name_ + ":1:toppas_dummy");
save_param.setSectionDescription(name_ + ":1", "Instance '1' section for '" + name_ + "'");
ParamXMLFile paramFile;
paramFile.store(ini_file, save_param);
}
void TOPPASToolVertex::toggleBreakpoint()
{
breakpoint_set_ = !breakpoint_set_;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/MultiGradientSelector.cpp | .cpp | 10,694 | 318 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/MultiGradientSelector.h>
//qt includes
#include <QPainter>
#include <QtWidgets/QColorDialog>
#include <QPixmap>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QPaintEvent>
#include <QContextMenuEvent>
#include <QtWidgets/QMenu>
using namespace std;
namespace OpenMS
{
MultiGradientSelector::MultiGradientSelector(QWidget * parent) :
QWidget(parent),
gradient_(),
margin_(5),
gradient_area_width_(0),
lever_area_height_(17),
selected_(-1),
selected_color_(Qt::white)
{
setMinimumSize(250, 45);
setFocusPolicy(Qt::ClickFocus);
setToolTip("Click the lever area to add new levers. Levers can be removed with the DEL key. "
"Double click a lever to change its color. Levers can be dragged.<BR><BR>"
"In the context menu you can select default gradients and change the interplation mode."
);
}
MultiGradientSelector::~MultiGradientSelector() = default;
const MultiGradient & MultiGradientSelector::gradient() const
{
return gradient_;
}
MultiGradient & MultiGradientSelector::gradient()
{
return gradient_;
}
void MultiGradientSelector::paintEvent(QPaintEvent * /* e */)
{
static QPixmap pixmap = QPixmap(size());
pixmap.fill(palette().window().color());
//calculate gradient area width
if (gradient_area_width_ == 0)
{
gradient_area_width_ = width() - 2 * margin_ - 2;
}
QPainter painter(&pixmap);
//gradient field outline
painter.setPen(QColor(0, 0, 0));
painter.drawRect(margin_, margin_, width() - 2 * margin_, height() - 2 * margin_ - lever_area_height_);
//draw gradient
for (Int i = 0; i <= gradient_area_width_; ++i)
{
painter.setPen(gradient_.interpolatedColorAt(i, 0, gradient_area_width_));
painter.drawLine(margin_ + 1 + i, margin_ + 1, margin_ + 1 + i, height() - margin_ - lever_area_height_ - 1);
}
//levers
painter.setPen(QColor(0, 0, 0));
for (UInt i = 0; i < (UInt)gradient_.size(); ++i)
{
Int pos = Int(float(gradient_.position(i)) / 100.0 * gradient_area_width_ + margin_ + 1);
painter.drawRect(pos - 4, height() - margin_ - lever_area_height_ + 5, 9, 9);
painter.drawLine(pos - 4, height() - margin_ - lever_area_height_ + 5, pos, height() - margin_ - lever_area_height_);
painter.drawLine(pos, height() - margin_ - lever_area_height_, pos + 4, height() - margin_ - lever_area_height_ + 5);
painter.fillRect(pos - 3, height() - margin_ - lever_area_height_ + 6, 8, 8, gradient_.color(i));
//selected lever
if (Int(gradient_.position(i)) == selected_)
{
painter.fillRect(pos - 2, height() - margin_ - lever_area_height_ + 3, 6, 3, QColor(0, 0, 0));
painter.fillRect(pos - 1, height() - margin_ - lever_area_height_ + 1, 4, 3, QColor(0, 0, 0));
}
}
QPainter painter2(this);
painter2.drawPixmap(0, 0, pixmap);
}
void MultiGradientSelector::mousePressEvent(QMouseEvent * e)
{
if (e->button() != Qt::LeftButton)
{
e->ignore();
return;
}
left_button_pressed_ = true;
// select lever
// Starting with the rightmost lever, the first lever that overlaps the mouse pointer is selected (only lever with higher index can overlap lever with lower index).
for (Int i = (Int)gradient_.size() - 1; i >= 0; --i)
{
Int pos = Int(float(gradient_.position(i)) / 100.0 * gradient_area_width_ + margin_ + 1);
// mouse pointer over lever?
if (e->position().toPoint().x() >= pos - 3 && e->position().toPoint().x() <= pos + 4 && e->position().toPoint().y() >= height() - margin_ - lever_area_height_ + 8 && e->position().toPoint().y() <= height() - margin_ - lever_area_height_ + 15)
{
selected_ = gradient_.position(i);
selected_color_ = gradient_.color(i);
repaint();
return;
}
}
//create new lever
if (e->position().toPoint().x() >= margin_ && e->position().toPoint().x() <= width() - margin_ && e->position().toPoint().y() >= height() - margin_ - lever_area_height_ && e->position().toPoint().y() <= height() - margin_)
{
Int pos = Int(100 * (e->position().toPoint().x() - margin_) / float(gradient_area_width_));
gradient_.insert(pos, selected_color_);
selected_ = pos;
repaint();
}
}
void MultiGradientSelector::mouseMoveEvent(QMouseEvent * e)
{
if (left_button_pressed_ && selected_ > 0 && selected_ < 100) // don't move first or last lever
{
//inside lever area
if (e->position().toPoint().x() >= margin_ && e->position().toPoint().x() <= width() - margin_ && e->position().toPoint().y() >= height() - margin_ - lever_area_height_ && e->position().toPoint().y() <= height() - margin_)
{
Int pos = Int(100 * (e->position().toPoint().x() - margin_) / float(gradient_area_width_));
if (pos != selected_ && !gradient_.exists(pos)) // lever has been moved AND no other lever at the new position?
{
gradient_.remove(selected_);
gradient_.insert(pos, selected_color_);
selected_ = pos;
repaint();
}
}
}
}
void MultiGradientSelector::mouseReleaseEvent(QMouseEvent * e)
{
if (e->button() != Qt::LeftButton)
{
e->ignore();
return;
}
left_button_pressed_ = false;
}
void MultiGradientSelector::mouseDoubleClickEvent(QMouseEvent * e)
{
for (UInt i = 0; i < (UInt)gradient_.size(); ++i)
{
Int pos = Int(float(gradient_.position(i)) / 100.0 * gradient_area_width_ + margin_ + 1);
if (e->position().toPoint().x() >= pos - 3 && e->position().toPoint().x() <= pos + 4 && e->position().toPoint().y() >= height() - margin_ - lever_area_height_ + 8 && e->position().toPoint().y() <= height() - margin_ - lever_area_height_ + 15)
{
gradient_.insert(gradient_.position(i), QColorDialog::getColor(gradient_.color(i), this));
if (Int(gradient_.position(i)) == selected_)
{
selected_color_ = gradient_.color(i);
}
return;
}
}
}
void MultiGradientSelector::keyPressEvent(QKeyEvent * e)
{
if (e->key() == Qt::Key_Delete && selected_ > 0 && selected_ < 100) // don't remove first or last lever)
{
gradient_.remove(selected_);
selected_ = -1;
selected_color_ = Qt::white;
repaint();
}
else
{
e->ignore();
}
}
void MultiGradientSelector::stairsInterpolation(bool state)
{
if (state)
{
gradient_.setInterpolationMode(MultiGradient::IM_STAIRS);
}
else
{
gradient_.setInterpolationMode(MultiGradient::IM_LINEAR);
}
}
void MultiGradientSelector::setInterpolationMode(MultiGradient::InterpolationMode mode)
{
gradient_.setInterpolationMode(mode);
}
MultiGradient::InterpolationMode MultiGradientSelector::getInterpolationMode() const
{
return gradient_.getInterpolationMode();
}
void MultiGradientSelector::contextMenuEvent(QContextMenuEvent * e)
{
QMenu main_menu(this);
//Default gradient
QMenu * defaults = main_menu.addMenu("Default gradients");
defaults->addAction("grey - yellow - red - purple - blue - black");
defaults->addAction("grey - black");
defaults->addAction("yellow - red - purple - blue - black");
defaults->addAction("orange - red - purple - blue - black");
defaults->addAction("yellow - orange - red");
defaults->addSeparator();
defaults->addAction("black");
defaults->addAction("white");
defaults->addAction("red");
defaults->addAction("green");
defaults->addAction("blue");
defaults->addAction("magenta");
defaults->addAction("turquoise");
defaults->addAction("yellow");
//Interploate/Stairs
QMenu * inter = main_menu.addMenu("Interpolation");
QAction * current = inter->addAction("None");
if (gradient_.getInterpolationMode() == MultiGradient::IM_STAIRS)
current->setEnabled(false);
current = inter->addAction("Linear");
if (gradient_.getInterpolationMode() == MultiGradient::IM_LINEAR)
current->setEnabled(false);
//Execute
QAction * result;
if ((result = main_menu.exec(e->globalPos())))
{
if (result->text() == "grey - yellow - red - purple - blue - black")
{
gradient_ = MultiGradient::getDefaultGradientLinearIntensityMode();
}
if (result->text() == "grey - black")
{
gradient_ = MultiGradient::getDefaultGradientLogarithmicIntensityMode();
}
else if (result->text() == "yellow - red - purple - blue - black")
{
gradient_.fromString("Linear|0,#ffea00;6,#ff0000;14,#aa00ff;23,#5500ff;100,#000000");
}
else if (result->text() == "orange - red - purple - blue - black")
{
gradient_.fromString("Linear|0,#ffaa00;6,#ff0000;14,#aa00ff;23,#5500ff;100,#000000");
}
else if (result->text() == "yellow - orange - red")
{
gradient_.fromString("Linear|0,#ffea00;6,#ffaa00;100,#ff0000");
}
else if (result->text() == "black")
{
gradient_.fromString("Linear|0,#000000;100,#000000");
}
else if (result->text() == "white")
{
gradient_.fromString("Linear|0,#FFFFFF;100,#FFFFFF");
}
else if (result->text() == "red")
{
gradient_.fromString("Linear|0,#ff0000;100,#ff0000");
}
else if (result->text() == "green")
{
gradient_.fromString("Linear|0,#00ff00;100,#00ff00");
}
else if (result->text() == "blue")
{
gradient_.fromString("Linear|0,#0000ff;100,#0000ff");
}
else if (result->text() == "magenta")
{
gradient_.fromString("Linear|0,#ff00ff;100,#ff00ff");
}
else if (result->text() == "turquoise")
{
gradient_.fromString("Linear|0,#00ffff;100,#00ffff");
}
else if (result->text() == "yellow")
{
gradient_.fromString("Linear|0,#ffff00;100,#ffff00");
}
else if (result->text() == "None")
{
setInterpolationMode(MultiGradient::IM_STAIRS);
}
else if (result->text() == "Linear")
{
setInterpolationMode(MultiGradient::IM_LINEAR);
}
}
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerDataFeature.cpp | .cpp | 2,833 | 85 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include "OpenMS/VISUAL/LayerDataPeak.h"
#include <OpenMS/ANALYSIS/ID/IDMapper.h>
#include <OpenMS/KERNEL/DimMapper.h>
#include <OpenMS/VISUAL/LayerDataFeature.h>
#include <OpenMS/VISUAL/Painter2DBase.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
using namespace std;
namespace OpenMS
{
/// Default constructor
LayerDataFeature::LayerDataFeature() : LayerDataBase(LayerDataBase::DT_FEATURE)
{
flags.set(LayerDataBase::F_HULL);
}
std::unique_ptr<Painter2DBase> LayerDataFeature::getPainter2D() const
{
return make_unique<Painter2DFeature>(this);
}
std::unique_ptr<LayerStoreData> LayerDataFeature::storeVisibleData(const RangeAllType& visible_range, const DataFilters& layer_filters) const
{
auto ret = make_unique<LayerStoreDataFeatureMapVisible>();
ret->storeVisibleFM(*features_.get(), visible_range, layer_filters);
return ret;
}
std::unique_ptr<LayerStoreData> LayerDataFeature::storeFullData() const
{
auto ret = make_unique<LayerStoreDataFeatureMapAll>();
ret->storeFullFM(*features_.get());
return ret;
}
PeakIndex LayerDataFeature::findHighestDataPoint(const RangeAllType& area) const
{
using IntType = MSExperiment::ConstAreaIterator::PeakType::IntensityType;
auto max_int = numeric_limits<IntType>::lowest();
PeakIndex max_pi;
for (FeatureMapType::ConstIterator i = getFeatureMap()->begin(); i != getFeatureMap()->end(); ++i)
{
if (area.containsRT(i->getRT()) && area.containsMZ(i->getMZ()) && filters.passes(*i))
{
if (i->getIntensity() > max_int)
{
max_int = i->getIntensity();
max_pi = PeakIndex(i - getFeatureMap()->begin());
}
}
}
return max_pi;
}
PointXYType LayerDataFeature::peakIndexToXY(const PeakIndex& peak, const DimMapper<2>& mapper) const
{
return mapper.map(peak.getFeature(*getFeatureMap()));
}
std::unique_ptr<LayerStatistics> LayerDataFeature::getStats() const
{
return make_unique<LayerStatisticsFeatureMap>(*getFeatureMap());
}
bool LayerDataFeature::annotate(const PeptideIdentificationList& identifications, const vector<ProteinIdentification>& protein_identifications)
{
IDMapper mapper;
mapper.annotate(*getFeatureMap(), identifications, protein_identifications);
return true;
}
}// namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/FileWatcher.cpp | .cpp | 2,872 | 82 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/FileWatcher.h>
#include <QtCore/QTimer>
using namespace std;
namespace OpenMS
{
FileWatcher::FileWatcher(QObject * parent) :
QFileSystemWatcher(parent),
timers_(),
delay_in_seconds_(1.0)
{
// Connect the slot for monitoring file changes
connect(this, &FileWatcher::fileChanged, [this](const String& s) { monitorFileChanged_(s.toQString()); });
}
FileWatcher::~FileWatcher() = default;
void FileWatcher::monitorFileChanged_(const QString & name)
{
//cout << "File changed: " << String(name) << endl;
// Look up if there is already a timer for this file
QTimer * timer = nullptr;
for (map<QString, QString>::const_iterator it = timers_.begin(); it != timers_.end(); ++it)
{
if (it->second == name) //we found the timer name and id
{
//cout << " - Found timer name: " << String(it->second) << endl;
//search for the timer instance with the corresponding Id
timer = findChild<QTimer *>(it->first);
}
}
//timer does not exist => create and start a new one
if (!timer)
{
//static timer counter
static int timer_id = 0;
//cout << " - no timer found => creating a new one with name: ";
timer = new QTimer(this);
timer->setInterval((int)(1000.0 * delay_in_seconds_));
timer->setSingleShot(true);
timer->setObjectName(QString::number(++timer_id));
connect(timer, SIGNAL(timeout()), this, SLOT(timerTriggered_()));
timer->start();
timers_[QString::number(timer_id)] = name;
//cout << timer_id << endl;
}
//timer exists => restart it as the file changed another time
else
{
//cout << " - timer found => resetting" << endl;
timer->start();
}
}
void FileWatcher::timerTriggered_()
{
//cout << "Timer activated" << endl;
//get the timer instance
QTimer * timer = qobject_cast<QTimer *>(sender());
//emit the final for the file corresponding to the timer name
//cout << " - timer name: " << String(timer->objectName()) << endl;
//cout << " - timer file: " << String(timers_[timer->objectName()]) << endl;
emit fileChanged(String(timers_[timer->objectName()]));
//erase the timer name from the list
timers_.erase(timer->objectName());
}
//OPENMS_DLLAPI FileWatcher myFileWatcher_instance; // required, such that the moc file get generated during building OpenMS.dll, not later during OpenMS_GUI.dll as DLL flags are wrong then
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASVertex.cpp | .cpp | 17,362 | 645 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASVertex.h>
#include <OpenMS/VISUAL/TOPPASEdge.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <QSvgRenderer>
#include <QtCore/QFileInfo>
#include <iostream>
#include <map>
namespace OpenMS
{
#ifdef TOPPAS_DEBUG
int TOPPASVertex::global_debug_indent_ = 0;
#endif
TOPPASVertex::TOPPASFilenames::TOPPASFilenames(const QStringList& filenames)
{
append(filenames);
}
int TOPPASVertex::TOPPASFilenames::size() const
{
return filenames_.size();
}
const QStringList& TOPPASVertex::TOPPASFilenames::get() const
{
return filenames_;
}
const QString& TOPPASVertex::TOPPASFilenames::operator[](int i) const
{
return filenames_[i];
}
void TOPPASVertex::TOPPASFilenames::set(const QStringList& filenames)
{
filenames_.clear();
this->append(filenames);
}
void TOPPASVertex::TOPPASFilenames::set(const QString& filename, int i)
{
check_(filename);
filenames_[i] = filename;
}
void TOPPASVertex::TOPPASFilenames::push_back(const QString& filename)
{
check_(filename);
filenames_.push_back(filename);
}
void TOPPASVertex::TOPPASFilenames::append(const QStringList& filenames)
{
for (const QString& fn : filenames)
{
check_(fn);
push_back(fn);
}
}
QStringList TOPPASVertex::TOPPASFilenames::getSuffixCounts() const
{
// display file type(s)
std::map<String, Size> suffices;
try
{
for (const auto& fn : filenames_)
{
auto type = FileHandler::getType(fn.toStdString());
++suffices[FileTypes::typeToName(type)];
}
}
catch (...)
{ // in a dry-run, the file might not exist, so we cannot determine the type
++suffices[FileTypes::typeToName(FileTypes::UNKNOWN)];
}
QStringList text_l;
for (const auto& [suffix, count] : suffices)
{
if (suffices.size() > 1)
text_l.push_back(String("." + suffix + "(" + String(count) + ")").toQString());
else
text_l.push_back("." + suffix.toQString());
}
return text_l;
}
void TOPPASVertex::TOPPASFilenames::check_(const QString& filename)
{
const Size max_filename_length = 255;
#ifdef OPENMS_WINDOWSPLATFORM
// on Windows, constraint applies to the whole path:
if (filename.count() > max_filename_length)
{
throw Exception::FileNameTooLong(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename.toStdString(), max_filename_length);
}
#else
// on Unix (Linux/Mac), constraint applies to the file name:
if (File::basename(filename).size() > max_filename_length)
{
throw Exception::FileNameTooLong(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, File::basename(filename), max_filename_length);
}
#endif
}
TOPPASVertex::TOPPASVertex()
{
setFlag(QGraphicsItem::ItemIsSelectable, true);
setZValue(42);
}
TOPPASVertex::TOPPASVertex(const TOPPASVertex& rhs) :
QObject(),
QGraphicsItem(),
// do not copy pointers to edges
in_edges_(/*rhs.in_edges_*/),
out_edges_(/*rhs.out_edges_*/),
edge_being_created_(rhs.edge_being_created_),
pen_color_(rhs.pen_color_),
brush_color_(rhs.brush_color_),
dfs_color_(rhs.dfs_color_),
topo_sort_marked_(rhs.topo_sort_marked_),
topo_nr_(rhs.topo_nr_),
round_total_(rhs.round_total_),
round_counter_(rhs.round_counter_),
finished_(rhs.finished_),
reachable_(rhs.reachable_),
allow_output_recycling_(rhs.allow_output_recycling_)
{
setFlag(QGraphicsItem::ItemIsSelectable, true);
setZValue(42);
setPos(rhs.pos());
}
TOPPASVertex& TOPPASVertex::operator=(const TOPPASVertex& rhs)
{
in_edges_ = rhs.in_edges_;
out_edges_ = rhs.out_edges_;
edge_being_created_ = rhs.edge_being_created_;
pen_color_ = rhs.pen_color_;
brush_color_ = rhs.brush_color_;
dfs_color_ = rhs.dfs_color_;
topo_sort_marked_ = rhs.topo_sort_marked_;
topo_nr_ = rhs.topo_nr_;
round_total_ = rhs.round_total_;
round_counter_ = rhs.round_counter_;
finished_ = rhs.finished_;
reachable_ = rhs.reachable_;
allow_output_recycling_ = rhs.allow_output_recycling_;
setPos(rhs.pos());
return *this;
}
void TOPPASVertex::paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/, bool round_shape)
{
QPen pen(pen_color_, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin);
if (isSelected())
{
pen.setWidth(2);
painter->setBrush(brush_color_.darker(130));
pen.setColor(Qt::darkBlue);
}
else
{
painter->setBrush(brush_color_);
}
painter->setPen(pen);
QPainterPath path;
if (round_shape)
{
path.addRoundedRect(boundingRect().marginsRemoved(QMarginsF(1, 1, 1, 1)), 20, 20);
}
else
{
path.addRect(boundingRect().marginsRemoved(QMarginsF(1, 1, 1, 1)));
}
painter->drawPath(path);
pen.setColor(pen_color_);
painter->setPen(pen);
// topo sort number
painter->drawText(boundingRect().x() + 7, boundingRect().y() + 20, QString::number(topo_nr_));
// recycling status
if (this->allow_output_recycling_)
{
QSvgRenderer svg_renderer(QString(":/Recycling_symbol.svg"), nullptr);
svg_renderer.render(painter, QRectF(-7, boundingRect().y() + 9.0, 14, 14));
}
}
QPainterPath TOPPASVertex::shape() const
{
QPainterPath shape;
shape.addRoundedRect(boundingRect(), 20, 20);
return shape;
}
bool TOPPASVertex::isUpstreamFinished() const
{
for (ConstEdgeIterator it = inEdgesBegin(); it != inEdgesEnd(); ++it)
{
TOPPASVertex * tv = (*it)->getSourceVertex();
if (!tv->isFinished())
{
// some tool that we depend on has not finished execution yet --> do not start yet
debugOut_("Not run (parent not finished)");
return false;
}
}
//std::cerr << "upstream of " << this->getTopoNr() << " is ready!\n";
return true;
}
bool TOPPASVertex::buildRoundPackages(RoundPackages& pkg, String& error_msg) // check all incoming edges for this node and construct the package
{
if (inEdgesBegin() == inEdgesEnd())
{
error_msg = "buildRoundPackages() called on vertex with no input edges!\n";
OPENMS_LOG_ERROR << error_msg;
return false;
}
// -- determine number of rounds from incoming edges
int round_common = -1; // number of rounds common to all
int no_recycle_count = 0; // number of edges that do NOT do recycling (there needs to be at least one)
for (ConstEdgeIterator it = inEdgesBegin(); it != inEdgesEnd(); ++it) // all incoming edges should have the same number of rounds (or should be set to 'recycle') !
{
TOPPASVertex* tv = (*it)->getSourceVertex();
if (tv->allow_output_recycling_)
{
continue;
}
++no_recycle_count;
if (round_common == -1)
{
round_common = tv->round_total_; // first non-recycler sets the pace
}
if (round_common != tv->round_total_)
{
error_msg = String("Number of rounds for incoming edges of node #") + this->getTopoNr() + " are not equal. No idea on how to combine them! Did you want to recycle its input?\n";
std::cerr << error_msg;
return false;
}
}
// -- we demand at least one node with no recycling to allow to determine number of rounds
if (no_recycle_count == 0)
{
error_msg = String("Number of rounds of node #") + this->getTopoNr() + " cannot be determined since all input nodes have recycling enabled. Disable for at least one input!\n";
std::cerr << error_msg;
return false;
}
// -- check if rounds from recyling nodes are an integer part of total rounds, i.e. total_rounds = X * node_rounds, X from N+
for (ConstEdgeIterator it = inEdgesBegin(); it != inEdgesEnd(); ++it) // look at all all recycling edges
{
TOPPASVertex * tv = (*it)->getSourceVertex();
if (!tv->allow_output_recycling_)
{
continue;
}
if (round_common % tv->round_total_ != 0) // modulo should be 0, if not ...
{
error_msg = String(tv->round_total_) + " rounds for incoming edges of node #" + this->getTopoNr() + " are recycled to meet a total of " + round_common + " rounds. But modulo is not 0. No idea on how to combine them! Adapt the number of input files?\n";
std::cerr << error_msg;
return false;
}
}
if (round_common <= 0)
{
error_msg = "Number of input rounds is 0 or negative. This cannot be! Aborting!\n";
std::cerr << error_msg;
return false;
}
pkg.clear();
pkg.resize(round_common);
// all incoming edges should have the same number of rounds!
for (ConstEdgeIterator it = inEdgesBegin(); it != inEdgesEnd(); ++it)
{
TOPPASVertex* tv_upstream = (*it)->getSourceVertex();
// fill files for each round
int param_index_src_out = (*it)->getSourceOutParam();
int param_index_tgt_in = (*it)->getTargetInParam();
for (int round = 0; round < round_common; ++round)
{
VertexRoundPackage rpg;
rpg.edge = *it;
int upstream_round = round;
if (tv_upstream->allow_output_recycling_ && upstream_round >= tv_upstream->round_total_)
{
upstream_round %= tv_upstream->round_total_;
}
rpg.filenames.set(tv_upstream->getFileNames(param_index_src_out, upstream_round));
// hack for merger vertices, as they have multiple incoming edges with -1 as index
while (pkg[round].count(param_index_tgt_in))
{
--param_index_tgt_in; // find free slot, i.e. -2, -3 ....
}
pkg[round][param_index_tgt_in] = rpg; // index by incoming edge number
}
}
return true;
}
QStringList TOPPASVertex::getFileNames(int param_index, int round) const
{
if ((Size)round >= output_files_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, round, output_files_.size());
}
RoundPackage rp = output_files_[round];
if (rp.find(param_index) == rp.end())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, param_index, rp.size()); // index could be larger (its a map, but nevertheless)
}
//String s = String(rp[param_index].filenames.join("\" \""));
return rp[param_index].filenames.get();
}
QStringList TOPPASVertex::getFileNames() const
{
// concatenate over all rounds
QStringList fl;
for (Size r = 0; r < output_files_.size(); ++r)
{
for (RoundPackage::const_iterator it = output_files_[r].begin();
it != output_files_[r].end();
++it)
{
fl.append(it->second.filenames.get());
}
}
return fl;
}
TOPPASVertex::SUBSTREESTATUS TOPPASVertex::getSubtreeStatus() const
{
if (!this->isFinished())
{
return TV_UNFINISHED;
}
if (!this->isUpstreamFinished())
{
return TV_UNFINISHED_INBRANCH; // only looks for immediate predecessors!
}
for (ConstEdgeIterator it = outEdgesBegin(); it != outEdgesEnd(); ++it)
{
SUBSTREESTATUS status = (*it)->getTargetVertex()->getSubtreeStatus();
if (status != TV_ALLFINISHED)
{
return status;
}
}
return TV_ALLFINISHED;
}
const TOPPASVertex::RoundPackages& TOPPASVertex::getOutputFiles() const
{
return output_files_;
}
void TOPPASVertex::mousePressEvent(QGraphicsSceneMouseEvent* e)
{
if (!(e->modifiers() & Qt::ControlModifier))
{
emit clicked();
}
}
void TOPPASVertex::mouseReleaseEvent(QGraphicsSceneMouseEvent* e)
{
if (edge_being_created_)
{
emit finishHoveringEdge();
edge_being_created_ = false;
}
else if (e->modifiers() & Qt::ControlModifier)
{
QGraphicsItem::mouseReleaseEvent(e);
}
else
{
emit released();
// resize scene rect in case item has been moved outside
const QRectF& scene_rect = scene()->sceneRect();
const QRectF& items_bounding = scene()->itemsBoundingRect();
scene()->setSceneRect(scene_rect.united(items_bounding));
}
}
void TOPPASVertex::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* e)
{
e->ignore();
}
void TOPPASVertex::contextMenuEvent(QGraphicsSceneContextMenuEvent* e)
{
e->ignore();
}
void TOPPASVertex::mouseMoveEvent(QGraphicsSceneMouseEvent* e)
{
TOPPASScene* ts = qobject_cast<TOPPASScene*>(scene());
if (isSelected())
{
QPointF delta = e->pos() - e->lastPos();
emit itemDragged(delta.x(), delta.y());
}
else
{
ts->setActionMode(TOPPASScene::AM_NEW_EDGE);
moveNewEdgeTo_(e->pos());
}
}
void TOPPASVertex::moveNewEdgeTo_(const QPointF& pos)
{
if (!edge_being_created_)
{
emit newHoveringEdge(mapToScene(pos));
edge_being_created_ = true;
}
emit hoveringEdgePosChanged(mapToScene(pos));
}
TOPPASVertex::ConstEdgeIterator TOPPASVertex::outEdgesBegin() const
{
return out_edges_.begin();
}
TOPPASVertex::ConstEdgeIterator TOPPASVertex::outEdgesEnd() const
{
return out_edges_.end();
}
TOPPASVertex::ConstEdgeIterator TOPPASVertex::inEdgesBegin() const
{
return in_edges_.begin();
}
TOPPASVertex::ConstEdgeIterator TOPPASVertex::inEdgesEnd() const
{
return in_edges_.end();
}
void TOPPASVertex::addInEdge(TOPPASEdge* edge)
{
in_edges_.push_back(edge);
}
void TOPPASVertex::addOutEdge(TOPPASEdge* edge)
{
out_edges_.push_back(edge);
}
void TOPPASVertex::removeInEdge(TOPPASEdge* edge)
{
in_edges_.removeAll(edge);
}
void TOPPASVertex::removeOutEdge(TOPPASEdge* edge)
{
out_edges_.removeAll(edge);
}
TOPPASVertex::DFS_COLOR TOPPASVertex::getDFSColor()
{
return dfs_color_;
}
void TOPPASVertex::setDFSColor(DFS_COLOR color)
{
dfs_color_ = color;
}
Size TOPPASVertex::incomingEdgesCount()
{
return in_edges_.size();
}
Size TOPPASVertex::outgoingEdgesCount()
{
return out_edges_.size();
}
void TOPPASVertex::inEdgeHasChanged()
{
// (overridden behavior in output and tool vertices)
qobject_cast<TOPPASScene*>(scene())->setChanged(true);
emit somethingHasChanged();
}
void TOPPASVertex::outEdgeHasChanged()
{
// (overridden behavior in input and tool vertices)
qobject_cast<TOPPASScene*>(scene())->setChanged(true);
emit somethingHasChanged();
}
bool TOPPASVertex::isTopoSortMarked() const
{
return topo_sort_marked_;
}
void TOPPASVertex::setTopoSortMarked(bool b)
{
topo_sort_marked_ = b;
}
UInt TOPPASVertex::getTopoNr() const
{
return topo_nr_;
}
void TOPPASVertex::setTopoNr(UInt nr)
{
// (overridden in tool and output vertices)
topo_nr_ = nr;
}
String TOPPASVertex::get3CharsNumber_(UInt number) const
{
String num_str(number);
num_str.fillLeft('0', 3);
return num_str;
}
void TOPPASVertex::reset(bool /*reset_all_files*/)
{
__DEBUG_BEGIN_METHOD__
round_total_ = -1;
round_counter_ = 0;
finished_ = false;
reachable_ = true;
update(boundingRect());
__DEBUG_END_METHOD__
}
bool TOPPASVertex::isFinished() const
{
return finished_;
}
void TOPPASVertex::run()
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
bool TOPPASVertex::invertRecylingMode()
{
allow_output_recycling_ = !allow_output_recycling_;
emit parameterChanged(true); // using 'true' is very conservative but safe. One could override this in child classes.
return allow_output_recycling_;
}
bool TOPPASVertex::isRecyclingEnabled() const
{
return allow_output_recycling_;
}
void TOPPASVertex::setRecycling(const bool is_enabled)
{
if (allow_output_recycling_ == is_enabled) return; // nothing changed
invertRecylingMode();
}
bool TOPPASVertex::allInputsReady() const
{
__DEBUG_BEGIN_METHOD__
for (ConstEdgeIterator it = inEdgesBegin(); it != inEdgesEnd(); ++it)
{
TOPPASVertex* tv = qobject_cast<TOPPASVertex*>((*it)->getSourceVertex());
if (tv && !tv->isFinished())
{
// some (reachable) tool that we depend on has not finished execution yet --> do not start yet
__DEBUG_END_METHOD__
return false;
}
}
__DEBUG_END_METHOD__
return true;
}
void TOPPASVertex::markUnreachable()
{
reachable_ = false;
for (ConstEdgeIterator it = outEdgesBegin(); it != outEdgesEnd(); ++it)
{
TOPPASVertex* tv = (*it)->getTargetVertex();
if (tv->reachable_)
{
tv->markUnreachable();
}
}
}
bool TOPPASVertex::isReachable() const
{
return reachable_;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/EnhancedWorkspace.cpp | .cpp | 3,820 | 142 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/EnhancedWorkspace.h>
#include <OpenMS/VISUAL/EnhancedTabBarWidgetInterface.h>
#include <QtCore/QMimeData>
#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QDropEvent>
#include <QMdiSubWindow>
namespace OpenMS
{
EnhancedWorkspace::EnhancedWorkspace(QWidget* parent) :
QMdiArea(parent)
{
setAcceptDrops(true);
}
EnhancedWorkspace::~EnhancedWorkspace() = default;
QMdiSubWindow* EnhancedWorkspace::addSubWindow(QWidget* widget)
{
auto subwindow = QMdiArea::addSubWindow(widget);
if (subwindow)
{
subwindow->setSystemMenu(nullptr);
}
return subwindow;
}
void EnhancedWorkspace::tileHorizontal()
{
// primitive horizontal tiling
QList<QMdiSubWindow*> windows = this->subWindowList();
if (!windows.count())
{
return;
}
int heightForEach = this->height() / windows.count();
int y = 0;
for (int i = 0; i < int(windows.count()); ++i)
{
QMdiSubWindow* window = windows.at(i);
if (window->isMaximized() || window->isMinimized() || window->isFullScreen())
{
// prevent flicker
window->hide();
window->showNormal();
}
int preferredHeight = window->widget()->minimumHeight() + window->baseSize().height();
int actHeight = std::max(heightForEach, preferredHeight);
window->setGeometry(0, y, this->width(), actHeight);
y += actHeight;
window->setVisible(true);
window->show();
}
}
void EnhancedWorkspace::tileVertical()
{
// primitive vertical tiling
QList<QMdiSubWindow*> windows = this->subWindowList();
if (!windows.count())
{
return;
}
int widthForEach = this->width() / windows.count();
int y = 0;
for (int i = 0; i < int(windows.count()); ++i)
{
QMdiSubWindow* window = windows.at(i);
if (window->isMaximized() || window->isMinimized() || window->isFullScreen())
{
// prevent flicker
window->hide();
window->showNormal();
}
int preferredWidth = window->widget()->minimumWidth() + window->baseSize().width();
int actWidth = std::max(widthForEach, preferredWidth);
window->setGeometry(y, 0, actWidth, this->height());
y += actWidth;
window->setVisible(true);
window->show();
}
}
/// get the subwindow with the given id (for all subwindows which inherit from EnhancedTabBarWidgetInterface)
/// Returns nullptr if window is not present
EnhancedTabBarWidgetInterface* EnhancedWorkspace::getWidget(int id) const
{
for (const auto& sub_window : this->subWindowList())
{
EnhancedTabBarWidgetInterface* w = dynamic_cast<EnhancedTabBarWidgetInterface*>(sub_window->widget());
//cout << " Tab " << i << ": " << w->window_id << endl;
if (w != nullptr && w->getWindowId() == id)
{
return w;
}
}
return nullptr;
}
void EnhancedWorkspace::dragEnterEvent(QDragEnterEvent * event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
void EnhancedWorkspace::dragMoveEvent(QDragMoveEvent * event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
void EnhancedWorkspace::dropEvent(QDropEvent * event)
{
emit dropReceived(event->mimeData(), dynamic_cast<QWidget*>(event->source()), -1);
event->acceptProposedAction();
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TableView.cpp | .cpp | 11,174 | 360 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TableView.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/Qt5Port.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QFile>
#include <QFileDialog>
#include <QHeaderView>
#include <QMenu>
#include <QTextStream>
#include <iostream>
using namespace std;
///@improvement write the visibility-status of the columns in toppview.ini and read at start
namespace OpenMS
{
TableView::TableView(QWidget* parent) :
QTableWidget(parent)
{
this->setObjectName("table_widget");
this->setSortingEnabled(true);
this->setEditTriggers(QAbstractItemView::NoEditTriggers);
this->setSelectionBehavior(QAbstractItemView::SelectRows);
this->setShowGrid(false);
this->setSelectionMode(QAbstractItemView::SingleSelection);
this->horizontalHeader()->setSectionsMovable(true);
this->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this->horizontalHeader(), &QHeaderView::customContextMenuRequested, this, &TableView::headerContextMenu_);
this->verticalHeader()->setHidden(true); // hide vertical column
{
QTableWidgetItem* proto_item = new QTableWidgetItem();
proto_item->setTextAlignment(Qt::AlignCenter);
this->setItemPrototype(proto_item);
}
}
void TableView::headerContextMenu_(const QPoint& pos)
{
// create menu
QMenu context_menu(this);
// add actions which show/hide columns
for (int i = 0; i != columnCount(); ++i)
{
QTableWidgetItem* ti = horizontalHeaderItem(i);
if (ti == nullptr)
{
continue;
}
QAction* action = context_menu.addAction(ti->text(), [=, this]() {
// invert visibility upon clicking the item
setColumnHidden(i, !isColumnHidden(i));
});
action->setCheckable(true);
action->setChecked(!isColumnHidden(i));
}
context_menu.exec(mapToGlobal(pos));
}
void TableView::setMandatoryExportColumns(QStringList& cols)
{
mandatory_export_columns_ = cols;
}
void TableView::exportEntries()
{
QString filename = QFileDialog::getSaveFileName(this, "Save File", "", "tsv file (*.tsv)");
QFile f(filename);
if (!f.open(QIODevice::WriteOnly))
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String(filename));
}
QTextStream ts(&f);
QStringList str_list;
QStringList cols_to_export = (getHeaderNames(WidgetHeader::VISIBLE_ONLY, true) + mandatory_export_columns_);
cols_to_export.removeDuplicates();
QStringList all_header_names = getHeaderNames(WidgetHeader::WITH_INVISIBLE, true);
// write header
bool first{true};
for (int c = 0; c < columnCount(); ++c)
{
// columns marked for export
if (cols_to_export.indexOf(all_header_names[c]) != -1)
{
if (!first)
{
ts << "\t";
}
else
{
first = false;
}
ts << all_header_names[c];
}
}
ts << "\n";
// write entries
for (int r = 0; r < rowCount(); ++r)
{
for (int c = 0; c < columnCount(); ++c)
{
// only export columns we marked for export
if (cols_to_export.indexOf(all_header_names[c]) == -1)
{
continue;
}
QTableWidgetItem* ti = this->item(r, c);
if (ti == nullptr)
{
str_list << "";
std::cerr << "Warning: Empty table cell found at position: ["<< r << ' ' << c << "]\n";
}
else
{
if (ti->data(Qt::UserRole).isValid())
{
str_list << ti->data(Qt::UserRole).toString();
}
else if (ti->data(Qt::CheckStateRole).isValid()) // Note: item with check box also has a display role, so this test needs to come first
{
str_list << ti->data(Qt::CheckStateRole).toString();
}
else if (ti->data(Qt::DisplayRole).isValid())
{
str_list << ti->data(Qt::DisplayRole).toString();
}
else if (ti->data(Qt::DisplayRole).isValid())
{
str_list << ti->data(Qt::DisplayRole).toString();
}
else
{
str_list << "";
std::cerr << "Warning: table cell with unhandled role found at position: [" << r << ' ' << c << "]\n";
}
}
}
ts << str_list.join("\t") + "\n";
str_list.clear();
}
f.close();
}
void TableView::setHeaders(const QStringList& headers)
{
setColumnCount(headers.size());
setHorizontalHeaderLabels(headers);
}
void TableView::hideColumns(const QStringList& header_names)
{
auto hset = toQSet(header_names);
// add actions which show/hide columns
for (int i = 0; i != columnCount(); ++i)
{
QTableWidgetItem* ti = horizontalHeaderItem(i);
if (ti == nullptr)
{
continue;
}
if (hset.contains(ti->text()))
{
setColumnHidden(i, true);
hset.remove(ti->text());
}
}
if (!hset.empty())
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "header_names contains a column name which is unknown: " + String(hset.values().join(", ")));
}
}
void TableView::appendRow()
{
insertRow(rowCount());
}
QTableWidgetItem* TableView::setAtBottomRow(const QString& text, size_t column_index, const QColor& background, const QColor& foreground)
{
QTableWidgetItem* item = itemPrototype()->clone();
item->setText(text);
return setAtBottomRow(item, column_index, background, foreground);
}
QTableWidgetItem* TableView::setAtBottomRow(const char* text, size_t column_index, const QColor& background, const QColor& foreground)
{
QTableWidgetItem* item = itemPrototype()->clone();
item->setText(text);
return setAtBottomRow(item, column_index, background, foreground);
}
QTableWidgetItem* TableView::setAtBottomRow(const int i, size_t column_index, const QColor& background, const QColor& foreground)
{
QTableWidgetItem* item = itemPrototype()->clone();
item->setData(Qt::DisplayRole, i);
return setAtBottomRow(item, column_index, background, foreground);
}
QTableWidgetItem* TableView::setAtBottomRow(const double d, size_t column_index, const QColor& background, const QColor& foreground)
{
QTableWidgetItem* item = itemPrototype()->clone();
item->setData(Qt::DisplayRole, d);
return setAtBottomRow(item, column_index, background, foreground);
}
QTableWidgetItem* TableView::setAtBottomRow(const bool selected, size_t column_index, const QColor& background, const QColor& foreground)
{
QTableWidgetItem* item = itemPrototype()->clone();
item->setCheckState(selected ? Qt::Checked : Qt::Unchecked);
/// sorting of columns is done by the DisplayRole, not the checkstate. So we need different content.
updateCheckBoxItem(item);
return setAtBottomRow(item, column_index, background, foreground);
}
QTableWidgetItem* TableView::setAtBottomRow(QTableWidgetItem* item, size_t column_index, const QColor& background, const QColor& foreground)
{
item->setBackground(QBrush(background));
if (foreground.isValid())
{
item->setForeground(QBrush(foreground));
}
setItem(rowCount() - 1, (int)column_index, item);
return item;
}
void TableView::updateCheckBoxItem(QTableWidgetItem* item)
{
// check if this function is called on checkbox items only (either no DisplayRole set or the text is '' or ' ')
if (!item->data(Qt::DisplayRole).isValid() ||
(item->data(Qt::DisplayRole).typeId() == QMetaType::QString
&& (item->data(Qt::DisplayRole).toString().isEmpty() || item->data(Qt::DisplayRole).toString() == " ")
)
)
{
item->setText(item->checkState() == Qt::Checked ? " " : "");
}
else
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Called on non-checkbox item");
}
}
QStringList TableView::getHeaderNames(const WidgetHeader which, bool use_export_name)
{
QStringList header_labels;
for (int i = 0; i != columnCount(); ++i)
{
// do not export hidden columns
if (which == WidgetHeader::VISIBLE_ONLY && isColumnHidden(i))
{
continue;
}
if (use_export_name)
{
header_labels << getHeaderExportName(i);
}
else
{
header_labels << getHeaderName(i);
}
}
return header_labels;
}
void TableView::setHeaderExportName(const int header_column, const QString& export_name)
{
QTableWidgetItem* ti = horizontalHeaderItem(header_column);
if (ti == nullptr)
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Header item " + String(header_column) + " not found!");
}
ti->setData(Qt::UserRole, export_name);
}
QString TableView::getHeaderExportName(const int header_column)
{
QTableWidgetItem* ti = horizontalHeaderItem(header_column);
if (ti == nullptr)
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Header item " + String(header_column) + " not found!");
}
// prefer user role over display role
if (ti->data(Qt::UserRole).isValid())
{
return ti->data(Qt::UserRole).toString();
}
else if (ti->data(Qt::DisplayRole).isValid())
{
return ti->data(Qt::DisplayRole).toString();
}
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Header item " + String(header_column) + " has no data!");
}
QString TableView::getHeaderName(const int header_column)
{
QTableWidgetItem* ti = horizontalHeaderItem(header_column);
if (ti == nullptr)
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Header item " + String(header_column) + " not found!");
}
if (ti->data(Qt::DisplayRole).isValid())
{
return ti->data(Qt::DisplayRole).toString();
}
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Header item " + String(header_column) + " has no data!");
}
void TableView::resizeEvent(QResizeEvent* /*event*/)
{
this->resizeColumnsToContents();
int widgetWidth = this->viewport()->size().width();
int tableWidth = 0;
for (int i = 0; i < this->columnCount(); ++i)
{
tableWidth += this->horizontalHeader()->sectionSize(i);
} //sections already resized to fit all data
double scale = (double) widgetWidth / tableWidth;
if (scale > 1.)
{
for (int i = 0; i < this->columnCount(); ++i)
{
this->setColumnWidth(i, this->horizontalHeader()->sectionSize(i) * scale);
}
}
emit resized();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LogWindow.cpp | .cpp | 2,566 | 99 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LogWindow.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QContextMenuEvent>
#include <QMenu>
#include <QTextEdit>
using namespace std;
namespace OpenMS
{
LogWindow::LogWindow(QWidget* parent)
: QTextEdit(parent)
{
const auto help = "Log Window<BR>"
"<BR>Output from TOPP tools and other status information is shown here";
this->setWhatsThis(help);
this->setToolTip(help);
setReadOnly(true);
connect(this, SIGNAL(textChanged()), this, SLOT(trimText_()));
}
void LogWindow::contextMenuEvent(QContextMenuEvent* event)
{
QMenu context_menu;
context_menu.addAction("Clear", [&]() {
this->clear();
});
context_menu.exec(this->mapToGlobal(event->pos()));
}
void LogWindow::appendText(const QString& text)
{
moveCursor(QTextCursor::End, QTextCursor::MoveAnchor); // move cursor to end, since text is inserted at cursor
insertPlainText(text);
// show log window
qobject_cast<QWidget*>(this->parent())->show();
}
void LogWindow::appendNewHeader(const LogWindow::LogState state, const String& heading, const String& body)
{
String state_string;
switch (state)
{
case NOTICE: state_string = "NOTICE"; break;
case WARNING: state_string = "WARNING"; break;
case CRITICAL: state_string = "ERROR"; break;
}
// update log
append("==============================================================================");
append((DateTime::now().getTime() + " " + state_string + ": " + heading).toQString());
append(body.toQString());
//show log tool window
qobject_cast<QWidget*>(parent())->show();
}
void LogWindow::addNewline()
{
append("");
}
void LogWindow::trimText_()
{
if (max_length_ <= 0) return;
if (this->toPlainText().size() > max_length_)
{
this->setPlainText(this->toPlainText().right(max_length_ / 2));
//std::cerr << "cut text to " << this->toPlainText().size() << "\n";
}
}
int LogWindow::maxLength() const
{
return max_length_;
}
void LogWindow::setMaxLength(int max_length)
{
max_length_ = max_length;
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ColorSelector.cpp | .cpp | 1,716 | 77 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/ColorSelector.h>
#include <OpenMS/CONCEPT/Types.h>
//qt includes
#include <QPainter>
#include <QtWidgets/QColorDialog>
#include <QPaintEvent>
#include <QMouseEvent>
using namespace std;
namespace OpenMS
{
ColorSelector::ColorSelector(QWidget * parent) :
QWidget(parent),
color_(255, 255, 255)
{
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
}
QSize ColorSelector::sizeHint() const
{
return QSize(15, 15);
}
ColorSelector::~ColorSelector() = default;
void ColorSelector::paintEvent(QPaintEvent * /*e*/)
{
Int size = std::min(width(), height());
QPainter painter(this);
painter.setPen(QColor(0, 0, 0));
painter.drawRect(0, 0, size - 1, size - 1);
painter.setPen(QColor(255, 255, 255));
painter.drawRect(1, 1, size - 3, size - 3);
painter.fillRect(2, 2, size - 4, size - 4, color_);
}
void ColorSelector::mousePressEvent(QMouseEvent * e)
{
if (e->button() != Qt::LeftButton)
{
e->ignore();
return;
}
QColor tmp = QColorDialog::getColor(color_, this);
if (tmp.isValid())
{
color_ = tmp;
repaint();
}
}
const QColor & ColorSelector::getColor()
{
return color_;
}
void ColorSelector::setColor(const QColor & col)
{
color_ = col;
repaint();
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASSplitterVertex.cpp | .cpp | 3,919 | 127 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Johannes Junker, Chris Bielow, Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASSplitterVertex.h>
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <iostream>
namespace OpenMS
{
TOPPASSplitterVertex::TOPPASSplitterVertex(const TOPPASSplitterVertex& rhs) = default;
TOPPASSplitterVertex& TOPPASSplitterVertex::operator=(const TOPPASSplitterVertex& rhs) = default;
std::unique_ptr<TOPPASVertex> TOPPASSplitterVertex::clone() const
{
return std::make_unique<TOPPASSplitterVertex>(*this);
}
String TOPPASSplitterVertex::getName() const
{
return "SplitterVertex";
}
void TOPPASSplitterVertex::run()
{
// check if everything ready
if (!isUpstreamFinished())
{
return;
}
RoundPackages pkg;
String error_msg("");
bool success = buildRoundPackages(pkg, error_msg);
if (!success)
{
std::cerr << "Could not retrieve input files from upstream nodes...\n";
// emit mergeFailed((String("Splitter #") + this->getTopoNr() + " failed. " + error_msg).toQString());
return;
}
output_files_.clear();
round_counter_ = 0;
// do the virtual splitting (1 round of N files becomes N rounds of 1 file):
for (RoundPackages::iterator pkg_it = pkg.begin(); pkg_it != pkg.end();
++pkg_it)
{
// there can only be one upstream (input) node:
QStringList files = pkg_it->begin()->second.filenames.get();
for (QStringList::iterator file_it = files.begin();
file_it != files.end(); ++file_it)
{
RoundPackage new_pkg;
new_pkg[-1].filenames.push_back(*file_it);
output_files_.push_back(new_pkg);
++round_counter_;
}
}
round_total_ = round_counter_;
finished_ = true;
// call all children, proceed in pipeline
for (ConstEdgeIterator it = outEdgesBegin(); it != outEdgesEnd(); ++it)
{
TOPPASVertex* tv = (*it)->getTargetVertex();
debugOut_(String("Starting child ") + tv->getTopoNr());
tv->run();
}
}
void TOPPASSplitterVertex::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
TOPPASVertex::paint(painter, option, widget);
QString text = "Split";
QRectF text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), (int)(text_boundings.height() / 4.0), text);
if (round_total_ != -1) // draw round number
{
text = QString::number(round_counter_) + " / " + QString::number(round_total_);
text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), 31, text);
}
}
QRectF TOPPASSplitterVertex::boundingRect() const
{
return QRectF(-41, -41, 82, 82);
}
void TOPPASSplitterVertex::markUnreachable()
{
// only mark as unreachable if all inputs are unreachable. otherwise the dead inputs will just be ignored.
bool some_input_reachable_ = false;
for (ConstEdgeIterator it = inEdgesBegin(); it != inEdgesEnd(); ++it)
{
TOPPASVertex* tv = (*it)->getSourceVertex();
if (tv->isReachable())
{
some_input_reachable_ = true;
break;
}
}
if (!some_input_reachable_)
{
TOPPASVertex::markUnreachable();
}
}
void TOPPASSplitterVertex::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* /*e*/)
{
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Plot2DCanvas.cpp | .cpp | 54,737 | 1,559 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/FORMAT/FeatureXMLFile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/VISUAL/FileWatcher.h>
#include <OpenMS/VISUAL/ColorSelector.h>
#include <OpenMS/VISUAL/DIALOGS/FeatureEditDialog.h>
#include <OpenMS/VISUAL/DIALOGS/Plot2DPrefDialog.h>
#include <OpenMS/VISUAL/INTERFACES/IPeptideIds.h>
#include <OpenMS/VISUAL/LayerDataConsensus.h>
#include <OpenMS/VISUAL/LayerDataFeature.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/MultiGradientSelector.h>
#include <OpenMS/VISUAL/Painter2DBase.h>
#include <OpenMS/VISUAL/Plot2DCanvas.h>
#include <OpenMS/VISUAL/PlotWidget.h>
//STL
#include <algorithm>
//QT
#include <QMouseEvent>
#include <QPainter>
#include <QPolygon>
#include <QElapsedTimer>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMessageBox>
#define PEN_SIZE_MAX_LIMIT 100 // maximum size of a rectangle representing a point for raw peak data
#define PEN_SIZE_MIN_LIMIT 1 // minimum. This should not be changed without adapting the way dots are plotted
// (might lead to inconsistencies when switching between drawing modes of
// paintMaximumIntensities() vs. paintAllIntensities() )
// the two following constants describe the valid range of the 'canvas_coverage_min_' member (adaptable by the user)
#define CANVAS_COVERAGE_MIN_LIMITHIGH 0.5
#define CANVAS_COVERAGE_MIN_LIMITLOW 0.1
using namespace std;
namespace OpenMS
{
using namespace Internal;
Plot2DCanvas::Plot2DCanvas(const Param & preferences, QWidget * parent) :
PlotCanvas(preferences, parent),
pen_size_min_(1),
pen_size_max_(20),
canvas_coverage_min_(0.2)
{
//Parameter handling
defaults_.setValue("background_color", "#ffffff", "Background color.");
defaults_.setValue("interpolation_steps", 1000, "Number of interpolation steps for peak gradient pre-calculation.");
defaults_.setMinInt("interpolation_steps", 1);
defaults_.setMaxInt("interpolation_steps", 1000);
defaults_.setValue("dot:gradient", "Linear|0,#eeeeee;1,#ffea00;6,#ff0000;14,#aa00ff;23,#5500ff;100,#000000", "Multi-color gradient for peaks.");
defaults_.setValue("dot:feature_icon", "circle", "Icon used for features and consensus features.");
defaults_.setValidStrings("dot:feature_icon", {"diamond","square","circle","triangle"});
defaults_.setValue("dot:feature_icon_size", 4, "Icon size used for features and consensus features.");
defaults_.setMinInt("dot:feature_icon_size", 1);
defaults_.setMaxInt("dot:feature_icon_size", 999);
defaultsToParam_();
setName("Plot2DCanvas");
setParameters(preferences);
linear_gradient_.fromString(param_.getValue("dot:gradient"));
// connect preferences change to the right slot
connect(this, SIGNAL(preferencesChange()), this, SLOT(currentLayerParametersChanged_()));
}
Plot2DCanvas::~Plot2DCanvas() = default;
void Plot2DCanvas::highlightPeak_(QPainter & painter, const PeakIndex & peak)
{
if (!peak.isValid())
{
return;
}
//determine coordinates;
auto pos_xy = getCurrentLayer().peakIndexToXY(peak, unit_mapper_);
// paint highlighted peak
painter.save();
painter.setPen(QPen(Qt::red, 2));
auto p_px = dataToWidget_(pos_xy);
painter.drawEllipse(p_px.x() - 5, p_px.y() - 5, 10, 10);
//restore painter
painter.restore();
}
PeakIndex Plot2DCanvas::findNearestPeak_(const QPoint& pos)
{
// no layers => return invalid peak index
if (layers_.empty())
{
return PeakIndex();
}
// constructing area around the current mouse position
auto a = visible_area_;
a.setArea(VisibleArea::AreaXYType(widgetToData_(pos - QPoint(5, 5)), widgetToData_(pos + QPoint(5, 5))));
return getCurrentLayer().findHighestDataPoint(a.getAreaUnit());
}
double Plot2DCanvas::adaptPenScaling_(double ratio_data2pixel, double& pen_width) const
{
// is the coverage OK using current pen width?
bool has_low_pixel_coverage_withpen = ratio_data2pixel*pen_width < canvas_coverage_min_;
int merge_factor(1);
if (has_low_pixel_coverage_withpen)
{ // scale up the sparse dimension until we reach the desired coverage (this will lead to overlap in the crowded dimension)
double scale_factor = canvas_coverage_min_ / ratio_data2pixel;
// however, within bounds (no need to check the pen_size_min_, because we can only exceed here, not underestimate)
scale_factor = std::min(pen_size_max_, scale_factor);
// The difference between the original pen_width vs. this scale
// gives the number of peaks to merge in the crowded dimension
merge_factor = scale_factor / pen_width;
// set pen width to the new scale
pen_width = scale_factor;
}
return merge_factor;
}
void Plot2DCanvas::intensityModeChange_()
{
String gradient_str;
if (intensity_mode_ == IM_LOG)
{
gradient_str = MultiGradient::getDefaultGradientLogarithmicIntensityMode().toString();
}
else // linear
{
gradient_str = linear_gradient_.toString();
}
if (layers_.empty())
{
return;
}
layers_.getCurrentLayer().param.setValue("dot:gradient", gradient_str);
for (Size i = 0; i < layers_.getLayerCount(); ++i)
{
recalculateDotGradient_(i);
}
PlotCanvas::intensityModeChange_();
}
void Plot2DCanvas::recalculateDotGradient_(Size layer)
{
getLayer(layer).gradient.fromString(getLayer(layer).param.getValue("dot:gradient"));
if (intensity_mode_ == IM_LOG)
{
getLayer(layer).gradient.activatePrecalculationMode(0.0, std::log1p(overall_data_range_.getMaxIntensity()), param_.getValue("interpolation_steps"));
}
else
{
getLayer(layer).gradient.activatePrecalculationMode(0.0, overall_data_range_.getMaxIntensity(), param_.getValue("interpolation_steps"));
}
}
void Plot2DCanvas::recalculateCurrentLayerDotGradient()
{
recalculateDotGradient_(layers_.getCurrentLayerIndex());
}
void Plot2DCanvas::pickProjectionLayer()
{
// find the last (visible) peak layers
Size layer_count = 0;
Size last_layer = 0;
Size visible_layer_count = 0;
Size visible_last_layer = 0;
for (Size i = 0; i < getLayerCount(); ++i)
{
if (getLayer(i).type == LayerDataBase::DT_PEAK)
{
layer_count++;
last_layer = i;
if (getLayer(i).visible)
{
visible_layer_count++;
visible_last_layer = i;
}
}
if (getLayer(i).type == LayerDataBase::DT_CHROMATOGRAM)
{
//TODO CHROM
}
}
// try to find the right layer to project
const LayerDataBase* layer = nullptr;
//first choice: current layer
if (layer_count != 0 && getCurrentLayer().type == LayerDataBase::DT_PEAK)
{
layer = &(getCurrentLayer());
}
//second choice: the only peak layer
else if (layer_count == 1)
{
layer = &(getLayer(last_layer));
}
//third choice: the only visible peak layer
else if (visible_layer_count == 1)
{
layer = &(getLayer(visible_last_layer));
}
//no layer with peaks: disable projections
else
{
emit toggleProjections();
return;
}
emit showProjections(layer);
}
bool Plot2DCanvas::finishAdding_()
{
// deselect all peaks
selected_peak_.clear();
measurement_start_.clear();
auto& layer = getCurrentLayer();
layer.updateRanges(); // required for minIntensity() below and hasRange()
if (layer.getRange().hasRange() == HasRangeType::NONE)
{
popIncompleteLayer_("Cannot add a dataset that contains no data. Aborting!");
return false;
}
// overall values update
recalculateRanges_();
// pick dimensions to show (based on data)
update_buffer_ = true;
if (getLayerCount() == 1)
{
resetZoom(false); //no repaint as this is done in intensityModeChange_() anyway
}
else if (getLayerCount() == 2)
{
setIntensityMode(IM_PERCENTAGE);
}
intensityModeChange_();
emit layerActivated(this);
// warn if negative intensities are contained
if (getCurrentMinIntensity() < 0)
{
QMessageBox::warning(this, "Warning", "This dataset contains negative intensities. Use it at your own risk!");
}
return true;
}
void Plot2DCanvas::removeLayer(Size layer_index)
{
if (layer_index >= getLayerCount())
{
return;
}
// remove the data
layers_.removeLayer(layer_index);
// update visible area and boundaries
auto old_data_range = overall_data_range_;
recalculateRanges_();
// only reset zoom if data range has been changed
if (old_data_range != overall_data_range_)
{
resetZoom(false); // no repaint as this is done in intensityModeChange_() anyway
}
if (layers_.empty())
{
overall_data_range_.clearRanges();
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
return;
}
// unselect all peaks
selected_peak_.clear();
measurement_start_.clear();
intensityModeChange_();
emit layerActivated(this);
}
// change the current layer
void Plot2DCanvas::activateLayer(Size layer_index)
{
// unselect all peaks
selected_peak_.clear();
measurement_start_.clear();
layers_.setCurrentLayer(layer_index);
emit layerActivated(this);
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot2DCanvas::recalculateSnapFactor_()
{
snap_factors_ = vector<double>(getLayerCount(), 1.0);
if (intensity_mode_ == IM_SNAP)
{
for (Size i = 0; i < getLayerCount(); i++)
{
if (getLayer(i).visible)
{
auto local_max = -numeric_limits<Peak1D::IntensityType>::max();
if (auto* lp = dynamic_cast<LayerDataPeak*>(&getLayer(i)))
{
const MSExperiment& peak_data = lp->getPeakData()->getMSExperiment();
for (auto it = peak_data.areaBeginConst(visible_area_.getAreaUnit().getMinRT(), visible_area_.getAreaUnit().getMaxRT(),
visible_area_.getAreaUnit().getMinMZ(), visible_area_.getAreaUnit().getMaxMZ());
it != peak_data.areaEndConst();
++it)
{
PeakIndex pi = it.getPeakIndex();
if (it->getIntensity() > local_max && getLayer(i).filters.passes(peak_data[pi.spectrum], pi.peak))
{
local_max = it->getIntensity();
}
}
}
else if (auto* lp = dynamic_cast<LayerDataFeature*>(&getLayer(i))) // features
{
for (FeatureMapType::ConstIterator it = lp->getFeatureMap()->begin(); it != lp->getFeatureMap()->end();
++it)
{
if (visible_area_.getAreaUnit().containsRT(it->getRT()) &&
visible_area_.getAreaUnit().containsMZ(it->getMZ()) &&
getLayer(i).filters.passes(*it))
{
local_max = std::max(local_max, it->getIntensity());
}
}
}
else if (auto* lp = dynamic_cast<LayerDataConsensus*>(&getLayer(i))) // consensus
{
for (ConsensusMapType::ConstIterator it = lp->getConsensusMap()->begin(); it != lp->getConsensusMap()->end();
++it)
{
if (visible_area_.getAreaUnit().containsRT(it->getRT()) &&
visible_area_.getAreaUnit().containsMZ(it->getMZ()) &&
getLayer(i).filters.passes(*it) &&
it->getIntensity() > local_max)
{
local_max = it->getIntensity();
}
}
}
else if (getLayer(i).type == LayerDataBase::DT_CHROMATOGRAM) // chromatogram
{
//TODO CHROM
}
else if (getLayer(i).type == LayerDataBase::DT_IDENT) // identifications
{
//TODO IDENT
}
if (local_max > 0.0)
{
snap_factors_[i] = overall_data_range_.getMaxIntensity() / local_max;
}
}
}
}
}
void Plot2DCanvas::updateScrollbars_()
{
GenericArea ga(&unit_mapper_);
auto all = ga.setArea(overall_data_range_).getAreaXY();
const auto& vis = visible_area_.getAreaXY();
emit updateHScrollbar(all.minX(), vis.minX(), vis.maxX(), all.maxX());
emit updateVScrollbar(all.minY(), vis.minY(), vis.maxY(), all.maxY());
}
void Plot2DCanvas::horizontalScrollBarChange(int value)
{
auto new_area = visible_area_;
auto new_XY = new_area.getAreaXY();
auto X_width = new_XY.width();
new_XY.setMinX(value);
new_XY.setMaxX(value + X_width);
new_area.setArea(new_XY);
changeVisibleArea_(new_area);
}
void Plot2DCanvas::verticalScrollBarChange(int value)
{
// invert 'value' (since the VERTICAL(!) scrollbar's range is negative -- see PlotWidget::updateVScrollbar())
value *= -1;
auto new_area = visible_area_;
auto new_XY = new_area.getAreaXY();
auto Y_height = new_XY.height();
new_XY.setMinY(value);
new_XY.setMaxY(value + Y_height);
new_area.setArea(new_XY);
changeVisibleArea_(new_area);
}
void Plot2DCanvas::paintEvent(QPaintEvent * e)
{
//Only fill background if no layer is present
if (getLayerCount() == 0)
{
QPainter painter;
painter.begin(this);
painter.fillRect(0, 0, this->width(), this->height(), QColor(String(param_.getValue("background_color").toString()).toQString()));
painter.end();
e->accept();
return;
}
#ifdef DEBUG_TOPPVIEW
cout << "BEGIN " << OPENMS_PRETTY_FUNCTION << endl;
cout << " Visible area -- m/z: " << visible_area_.minX() << " - " << visible_area_.maxX() << " rt: " << visible_area_.minY() << " - " << visible_area_.maxY() << endl;
cout << " Overall area -- m/z: " << overall_data_range_.minPosition()[0] << " - " << overall_data_range_.maxPosition()[0] << " rt: " << overall_data_range_.minPosition()[1] << " - " << overall_data_range_.maxPosition()[1] << endl;
#endif
//timing
QElapsedTimer overall_timer;
if (show_timing_)
{
overall_timer.start();
if (update_buffer_)
{
cout << "Updating buffer:" << endl;
}
else
{
cout << "Copying buffer:" << endl;
}
}
QPainter painter;
if (update_buffer_)
{
update_buffer_ = false;
// recalculate snap factor
recalculateSnapFactor_();
buffer_.fill(QColor(String(param_.getValue("background_color").toString()).toQString()).rgb());
painter.begin(&buffer_);
QElapsedTimer layer_timer;
for (Size i = 0; i < getLayerCount(); i++)
{
// timing
if (show_timing_)
{
layer_timer.start();
}
if (getLayer(i).visible)
{
// update factors (snap and percentage)
percentage_factor_ = 1.0;
if (intensity_mode_ == IM_PERCENTAGE)
{
if (getLayer(i).getMaxIntensity() > 0)
{
percentage_factor_ = overall_data_range_.getMaxIntensity() / getLayer(i).getMaxIntensity();
}
}
getLayer(i).getPainter2D()->paint(&painter, this, i);
}
// timing
if (show_timing_)
{
cout << " -layer " << i << " time: " << layer_timer.elapsed() << " ms" << endl;
}
}
paintGridLines_(painter);
painter.end();
}
painter.begin(this);
// copy peak data from buffer
for (const auto& rect : e->region())
{
painter.drawImage(rect.topLeft(), buffer_, rect);
}
// draw measurement peak
if (action_mode_ == AM_MEASURE && measurement_start_.isValid())
{
painter.setPen(Qt::black);
QPoint line_begin;
// start of line
if (selected_peak_.isValid())
{
auto data_xy = getCurrentLayer().peakIndexToXY(selected_peak_, unit_mapper_);
line_begin = dataToWidget_(data_xy);
}
else
{
line_begin = last_mouse_pos_;
}
// end of line
auto data_xy = getCurrentLayer().peakIndexToXY(measurement_start_, unit_mapper_);
auto line_end = dataToWidget_(data_xy);
painter.drawLine(line_begin, line_end);
highlightPeak_(painter, measurement_start_);
}
// draw convex hulls or consensus feature elements
if (selected_peak_.isValid())
{
getCurrentLayer().getPainter2D()->highlightElement(&painter, this, selected_peak_);
}
if (action_mode_ == AM_MEASURE || action_mode_ == AM_TRANSLATE)
{
highlightPeak_(painter, selected_peak_);
}
// draw delta for measuring
if (action_mode_ == AM_MEASURE && measurement_start_.isValid())
{
drawDeltas_(painter, measurement_start_, selected_peak_);
}
else
{
drawCoordinates_(painter, selected_peak_);
}
painter.end();
if (show_timing_)
{
cout << " -overall time: " << overall_timer.elapsed() << " ms" << endl << endl;
}
}
void Plot2DCanvas::drawCoordinates_(QPainter & painter, const PeakIndex & peak)
{
if (!peak.isValid()) return;
const auto xy_point = getCurrentLayer().peakIndexToXY(peak, unit_mapper_);
QStringList lines;
lines << unit_mapper_.getDim(DIM::X).formattedValue(xy_point.getX()).toQString();
lines << unit_mapper_.getDim(DIM::Y).formattedValue(xy_point.getY()).toQString();
if (unit_mapper_.getDim(DIM::X).getUnit() != DIM_UNIT::INT && unit_mapper_.getDim(DIM::Y).getUnit() != DIM_UNIT::INT)
{ // if intensity is not mapped to X or Y, add it
// Note: it may be cleaner to hoist this function into the derived classes of Painter2D,
// if the logic here depends on the actual Layer type (currently, 'INT' should work fine for all).
DimMapper<2> int_mapper({DIM_UNIT::INT, DIM_UNIT::INT});
const auto int_point = getCurrentLayer().peakIndexToXY(peak, int_mapper);
lines << int_mapper.getDim(DIM::X).formattedValue(int_point.getX()).toQString();
}
drawText_(painter, lines);
}
void Plot2DCanvas::drawDeltas_(QPainter & painter, const PeakIndex & start, const PeakIndex & end)
{
if (!start.isValid())
{
return;
}
// mapper obtain intensity from a PeakIndex
DimMapper<2> intensity_mapper({DIM_UNIT::INT, DIM_UNIT::INT});
const auto peak_start = getCurrentLayer().peakIndexToXY(start, unit_mapper_);
const auto peak_start_int = getCurrentLayer().peakIndexToXY(start, intensity_mapper);
auto peak_end = decltype(peak_start) {}; // same as peak_start but without the const
auto peak_end_int = decltype(peak_start) {}; // same as peak_start but without the const
if (end.isValid())
{
peak_end = getCurrentLayer().peakIndexToXY(end, unit_mapper_);
peak_end_int = getCurrentLayer().peakIndexToXY(end, intensity_mapper);
}
else
{
peak_end = widgetToData_(last_mouse_pos_);
peak_end_int = decltype(peak_end_int) {};
}
auto dim_text = [](const DimBase& dim, double start_pos, double end_pos, bool ratio /*or difference*/) {
QString result;
if (ratio)
{
result = dim.formattedValue(end_pos / start_pos, " ratio ").toQString();
}
else
{
result = dim.formattedValue(end_pos - start_pos, " delta ").toQString();
if (dim.getUnit() == DIM_UNIT::MZ)
{
auto ppm = Math::getPPM(end_pos, start_pos);
result += " (" + QString::number(ppm, 'f', 1) + " ppm)";
}
}
return result;
};
QStringList lines;
lines << dim_text(unit_mapper_.getDim(DIM::X), peak_start.getX(), peak_end.getX(), false);
lines << dim_text(unit_mapper_.getDim(DIM::Y), peak_start.getY(), peak_end.getY(), false);
lines << dim_text(DimINT(), peak_start_int.getY(), peak_end_int.getY(), true); // ratio
drawText_(painter, lines);
}
void Plot2DCanvas::mousePressEvent(QMouseEvent * e)
{
last_mouse_pos_ = e->pos();
if (e->button() == Qt::LeftButton)
{
if (action_mode_ == AM_MEASURE)
{
if (selected_peak_.isValid())
{
measurement_start_ = selected_peak_;
}
else
{
measurement_start_.clear();
}
}
else if (action_mode_ == AM_ZOOM)
{
//translate (if not moving features)
if ( !(getCurrentLayer().type == LayerDataBase::DT_FEATURE) || !selected_peak_.isValid())
{
rubber_band_.setGeometry(QRect(e->pos(), QSize()));
rubber_band_.show();
}
}
}
}
void Plot2DCanvas::mouseMoveEvent(QMouseEvent* e)
{
grabKeyboard(); // (re-)grab keyboard after it has been released by unhandled key
QPoint pos = e->pos();
PointXYType data_pos = widgetToData_(pos);
emit sendCursorStatus(unit_mapper_.getDim(DIM::X).formattedValue(data_pos[0]),
unit_mapper_.getDim(DIM::Y).formattedValue(data_pos[1]));
PeakIndex near_peak = findNearestPeak_(pos);
//highlight current peak and display peak coordinates
if (action_mode_ == AM_MEASURE || (action_mode_ == AM_TRANSLATE && !(e->buttons() & Qt::LeftButton)))
{
//highlight peak
selected_peak_ = near_peak;
update_(OPENMS_PRETTY_FUNCTION);
//show meta data in status bar (if available)
if (selected_peak_.isValid())
{
String status;
auto* lf = dynamic_cast<LayerDataFeature*>(&getCurrentLayer());
auto* lc = dynamic_cast<LayerDataConsensus*>(&getCurrentLayer());
if (lf || lc)
{
//add meta info
const BaseFeature* f;
if (lf)
{
f = &selected_peak_.getFeature(*lf->getFeatureMap());
}
else
{
f = &selected_peak_.getFeature(*lc->getConsensusMap());
}
std::vector<String> keys;
f->getKeys(keys);
for (Size m = 0; m < keys.size(); ++m)
{
status += " " + keys[m] + ": ";
const DataValue& dv = f->getMetaValue(keys[m]);
if (dv.valueType() == DataValue::DOUBLE_VALUE)
{ // use less precision for large numbers, for better readability
int precision(2);
if ((double)dv < 10) precision = 5;
// ... and add 1k separators, e.g. '540,321.99'
status += QLocale::c().toString((double)dv, 'f', precision);
}
else
{
status += (String)dv;
}
}
}
else if (auto* lp = dynamic_cast<LayerDataPeak*>(&getCurrentLayer()))
{
//meta info
const ExperimentType::SpectrumType & s = selected_peak_.getSpectrum(lp->getPeakData()->getMSExperiment());
for (Size m = 0; m < s.getFloatDataArrays().size(); ++m)
{
if (selected_peak_.peak < s.getFloatDataArrays()[m].size())
{
status += s.getFloatDataArrays()[m].getName() + ": " + s.getFloatDataArrays()[m][selected_peak_.peak] + " ";
}
}
for (Size m = 0; m < s.getIntegerDataArrays().size(); ++m)
{
if (selected_peak_.peak < s.getIntegerDataArrays()[m].size())
{
status += s.getIntegerDataArrays()[m].getName() + ": " + s.getIntegerDataArrays()[m][selected_peak_.peak] + " ";
}
}
for (Size m = 0; m < s.getStringDataArrays().size(); ++m)
{
if (selected_peak_.peak < s.getStringDataArrays()[m].size())
{
status += s.getStringDataArrays()[m].getName() + ": " + s.getStringDataArrays()[m][selected_peak_.peak] + " ";
}
}
}
else if (getCurrentLayer().type == LayerDataBase::DT_CHROMATOGRAM) // chromatogram
{
//TODO CHROM
}
if (status != "")
{
emit sendStatusMessage(status, 0);
}
}
}
else if (action_mode_ == AM_ZOOM)
{
//Zoom mode => no peak should be selected
selected_peak_.clear();
update_(OPENMS_PRETTY_FUNCTION);
}
if (action_mode_ == AM_MEASURE)
{
last_mouse_pos_ = pos;
}
else if (action_mode_ == AM_ZOOM)
{
//if mouse button is held down, enlarge the selection
if (e->buttons() & Qt::LeftButton)
{
rubber_band_.setGeometry(QRect(last_mouse_pos_, pos).normalized());
rubber_band_.show(); //if the mouse button is pressed before the zoom key is pressed
update_(OPENMS_PRETTY_FUNCTION);
}
}
else if (action_mode_ == AM_TRANSLATE)
{
if (e->buttons() & Qt::LeftButton)
{
// move feature
auto* lf = dynamic_cast<LayerDataFeature*>(&getCurrentLayer());
if (getCurrentLayer().modifiable && lf && selected_peak_.isValid())
{
RangeType dr;
unit_mapper_.fromXY(widgetToData_(pos), dr);
// restrict the movement to the data range
dr.pushInto(overall_data_range_);
(*lf->getFeatureMap())[selected_peak_.peak].setRT(dr.getMinRT());
(*lf->getFeatureMap())[selected_peak_.peak].setMZ(dr.getMinMZ());
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
modificationStatus_(layers_.getCurrentLayerIndex(), true);
}
else // translate
{ // calculate data coordinates of shift
PointXYType old_data = widgetToData_(last_mouse_pos_);
PointXYType new_data = widgetToData_(pos);
// compute new area
auto new_visible_area = visible_area_;
new_visible_area.setArea(new_visible_area.getAreaXY() + (old_data - new_data));
// publish (bounds checking is done inside changeVisibleArea_)
changeVisibleArea_(new_visible_area);
last_mouse_pos_ = pos;
}
}
}
}
void Plot2DCanvas::mouseReleaseEvent(QMouseEvent * e)
{
if (e->button() == Qt::LeftButton)
{
if (action_mode_ == AM_MEASURE)
{
if (!selected_peak_.isValid())
{
measurement_start_.clear();
}
measurement_start_.clear();
update_(OPENMS_PRETTY_FUNCTION);
}
else if (action_mode_ == AM_ZOOM)
{
rubber_band_.hide();
QRect rect = rubber_band_.geometry();
if (rect.width() != 0 && rect.height() != 0)
{
auto new_area = visible_area_.cloneWith(AreaXYType(widgetToData_(rect.topLeft()), widgetToData_(rect.bottomRight())));
changeVisibleArea_(new_area, true, true);
}
}
}
}
void Plot2DCanvas::contextMenuEvent(QContextMenuEvent * e)
{
// abort if there are no layers
if (layers_.empty())
{
return;
}
const LayerDataBase& layer = getCurrentLayer();
QMenu* context_menu = new QMenu(this);
QAction* a = nullptr;
QAction* result = nullptr;
//Display name and warn if current layer invisible
String layer_name = String("Layer: ") + layer.getName();
if (!layer.visible)
{
layer_name += " (invisible)";
}
context_menu->addAction(layer_name.toQString())->setEnabled(false);
context_menu->addSeparator();
context_menu->addAction("Layer meta data", [&]() { showMetaData(true); });
QMenu * settings_menu = new QMenu("Settings");
settings_menu->addAction("Show/hide grid lines");
settings_menu->addAction("Show/hide axis legends");
context_menu->addSeparator();
context_menu->addAction("Switch to 3D view", [&]() { emit showCurrentPeaksAs3D(); });
const RangeType e_units = [&](){ // mouse position in units
RangeType r;
unit_mapper_.fromXY(widgetToData_(e->pos()), r);
return r;
}();
// a small 10x10 pixel area around the current mouse position
auto check_area = visible_area_.cloneWith({widgetToData_(e->pos() - QPoint(10, 10)), widgetToData_(e->pos() + QPoint(10, 10))}).getAreaUnit();
//-------------------PEAKS----------------------------------
if (auto* lp = dynamic_cast<const LayerDataPeak*>(&layer))
{
//add settings
settings_menu->addSeparator();
settings_menu->addAction("Show/hide projections");
settings_menu->addAction("Show/hide MS/MS precursors");
auto& exp = lp->getPeakData()->getMSExperiment();
// in a IM-frame (IM vs. m/z), the RT is empty in `e_units`, and showing neighbouring RT scans is not possible (this layer only has this IM frame)
// --> skip entries for RT neighbours.
if (!e_units.RangeRT::isEmpty())
{
// add surrounding survey scans
// find nearest survey scan
SignedSize size = exp.size();
Int current = exp.RTBegin(e_units.getMinRT()) - exp.begin();
if (current == size) // if the user clicked right of the last MS1 scan
{
current = std::max(SignedSize {0}, size - 1); // we want the rightmost valid scan index
}
SignedSize i = 0;
while (current + i < size || current - i >= 0)
{
if (current + i < size && exp[current + i].getMSLevel() == 1)
{
current += i;
break;
}
if (current - i >= 0 && exp[current - i].getMSLevel() == 1)
{
current -= i;
break;
}
++i;
}
// search for four scans in both directions
vector<Int> indices;
indices.push_back(current);
i = 1;
while (current - i >= 0 && indices.size() < 5)
{
if (exp[current - i].getMSLevel() == 1) { indices.push_back(current - i); }
++i;
}
i = 1;
while (current + i < size && indices.size() < 9)
{
if (exp[current + i].getMSLevel() == 1) { indices.push_back(current + i); }
++i;
}
sort(indices.rbegin(), indices.rend());
QMenu* ms1_scans = context_menu->addMenu("Survey scan in 1D");
QMenu* ms1_meta = context_menu->addMenu("Survey scan meta data");
context_menu->addSeparator();
for (auto idx : indices)
{
if (idx == current) { ms1_scans->addSeparator(); }
ms1_scans->addAction(QString("RT: ") + QString::number(exp[idx].getRT()),
[=, this]() { emit showSpectrumAsNew1D(idx); });
if (idx == current) { ms1_scans->addSeparator(); }
if (idx == current) { ms1_meta->addSeparator(); }
ms1_meta->addAction(QString("RT: ") + QString::number(exp[idx].getRT()),
[=, this]() { showMetaData(true, idx); });
if (idx == current) { ms1_meta->addSeparator(); }
}
// add surrounding fragment scans
// - We first attempt to look at the position where the user clicked
// - Next we look within the +/- 5 scans around that position
// - Next we look within the whole visible area
QMenu* msn_scans = new QMenu("fragment scan in 1D");
QMenu* msn_meta = new QMenu("fragment scan meta data");
bool item_added = collectFragmentScansInArea_(check_area, msn_scans, msn_meta);
if (!item_added)
{
// Now simply go for the 5 closest points in RT and check whether there
// are any scans.
// NOTE: that if we go for the visible area, we run the
// risk of iterating through *all* the scans.
check_area.RangeMZ::extend((RangeMZ)visible_area_.getAreaUnit());
const auto& exp = lp->getPeakData()->getMSExperiment();
const auto& specs = exp.getSpectra();
check_area.RangeRT::operator=(RangeRT(specs[indices.back()].getRT(), specs[indices.front()].getRT()));
item_added = collectFragmentScansInArea_(check_area, msn_scans, msn_meta);
if (! item_added)
{ // OK, now lets search the whole visible area (may be large!)
item_added = collectFragmentScansInArea_(visible_area_.getAreaUnit(), msn_scans, msn_meta);
}
}
if (item_added)
{
context_menu->addMenu(msn_scans);
context_menu->addMenu(msn_meta);
context_menu->addSeparator();
}
auto it_closest_MS = lp->getPeakData()->getMSExperiment().getClosestSpectrumInRT(e_units.getMinRT());
if (it_closest_MS->containsIMData())
{
context_menu->addAction(
("Switch to ion mobility view (MSLevel: " + String(it_closest_MS->getMSLevel()) + ";RT: " + String(it_closest_MS->getRT(), false) + ")")
.c_str(),
[=, this]() { emit showCurrentPeaksAsIonMobility(*it_closest_MS); });
}
} // end of hasRT
finishContextMenu_(context_menu, settings_menu);
context_menu->exec(mapToGlobal(e->pos()));
}
//-------------------FEATURES----------------------------------
else if (auto* lf = dynamic_cast<const LayerDataFeature*>(&layer))
{
// add settings
settings_menu->addSeparator();
settings_menu->addAction("Show/hide convex hull");
settings_menu->addAction("Show/hide trace convex hulls");
settings_menu->addAction("Show/hide numbers/labels");
settings_menu->addAction("Show/hide unassigned peptide hits");
// search for nearby features
QMenu* meta = new QMenu("Feature meta data");
const FeatureMapType& features = *lf->getFeatureMap();
// feature meta data menu
for (auto it = features.cbegin(); it != features.cend(); ++it)
{
if (check_area.containsMZ(it->getMZ()) && check_area.containsRT(it->getRT()))
{
a = meta->addAction(QString("RT: ") + QString::number(it->getRT()) + " m/z:" + QString::number(it->getMZ())
+ " charge:" + QString::number(it->getCharge()));
a->setData((int)(it - features.begin()));
}
}
if (! meta->actions().empty())
{
context_menu->addMenu(meta);
context_menu->addSeparator();
}
// add modifiable flag
settings_menu->addSeparator();
settings_menu->addAction("Toggle edit/view mode", [&]() { getCurrentLayer().modifiable = ! getCurrentLayer().modifiable; });
finishContextMenu_(context_menu, settings_menu);
// evaluate menu
if ((result = context_menu->exec(mapToGlobal(e->pos()))))
{
if (result->text().left(3) == "RT:")
{
showMetaData(true, result->data().toInt());
}
}
}
//-------------------CONSENSUS FEATURES----------------------------------
else if (auto* lc = dynamic_cast<const LayerDataConsensus*>(&layer))
{
// add settings
settings_menu->addSeparator();
settings_menu->addAction("Show/hide elements", [&]() { setLayerFlag(LayerDataBase::C_ELEMENTS, ! getLayerFlag(LayerDataBase::C_ELEMENTS)); });
// search for nearby features
QMenu* consens_meta = new QMenu("Consensus meta data");
const ConsensusMapType& features = *lc->getConsensusMap();
// consensus feature meta data menu
for (auto it = features.cbegin(); it != features.cend(); ++it)
{
if (check_area.containsMZ(it->getMZ()) && check_area.containsRT(it->getRT()))
{
a = consens_meta->addAction(QString("RT: ") + QString::number(it->getRT()) + " m/z:" + QString::number(it->getMZ()) + " charge:" + QString::number(it->getCharge()));
a->setData((int)(it - features.begin()));
}
}
if (!consens_meta->actions().empty())
{
context_menu->addMenu(consens_meta);
context_menu->addSeparator();
}
finishContextMenu_(context_menu, settings_menu);
if ((result = context_menu->exec(mapToGlobal(e->pos()))))
{
if (result->text().left(3) == "RT:")
{
showMetaData(true, result->data().toInt());
}
}
}
//------------------CHROMATOGRAMS----------------------------------
else if (auto* lc = dynamic_cast<const LayerDataChrom*>(&layer))
{
settings_menu->addSeparator();
settings_menu->addAction("Show/hide projections");
settings_menu->addAction("Show/hide MS/MS precursors");
const PeakMap& exp = lc->getChromatogramData()->getMSExperiment();
constexpr int CHROMATOGRAM_SHOW_MZ_RANGE = 10;
auto search_area = e_units;
search_area.RangeMZ::extendLeftRight(CHROMATOGRAM_SHOW_MZ_RANGE);
// collect all precursor that fall into the mz rt window
typedef std::set<Precursor, Precursor::MZLess> PCSetType;
PCSetType precursor_in_rt_mz_window;
for (auto iter = exp.getChromatograms().cbegin(); iter != exp.getChromatograms().cend(); ++iter)
{
if (search_area.containsMZ(iter->getPrecursor().getMZ()) &&
RangeBase{iter->front().getRT(), iter->back().getRT()}.contains(search_area.getRangeForDim(MSDim::MZ)))
{
precursor_in_rt_mz_window.insert(iter->getPrecursor());
}
}
// determine product chromatograms for each precursor
map<Precursor, vector<Size>, Precursor::MZLess> map_precursor_to_chrom_idx;
for (PCSetType::const_iterator pit = precursor_in_rt_mz_window.begin(); pit != precursor_in_rt_mz_window.end(); ++pit)
{
for (vector<MSChromatogram >::const_iterator iter = exp.getChromatograms().begin(); iter != exp.getChromatograms().end(); ++iter)
{
if (iter->getPrecursor() == *pit)
{
map_precursor_to_chrom_idx[*pit].push_back(iter - exp.getChromatograms().begin());
}
}
}
QMenu* msn_chromatogram = nullptr;
QMenu* msn_chromatogram_meta = nullptr;
if (!map_precursor_to_chrom_idx.empty())
{
msn_chromatogram = context_menu->addMenu("Chromatogram");
msn_chromatogram_meta = context_menu->addMenu("Chromatogram meta data");
context_menu->addSeparator();
for (auto mit = map_precursor_to_chrom_idx.cbegin(); mit != map_precursor_to_chrom_idx.cend(); ++mit)
{
// Show the peptide sequence if available, otherwise show the m/z and charge only
QString precursor_string = QString("Precursor m/z: (") + String(mit->first.getCharge()).toQString() + ") " + QString::number(mit->first.getMZ());
if (mit->first.metaValueExists("peptide_sequence"))
{
precursor_string = QString::number(mit->first.getMZ()) + " : " + String(mit->first.getMetaValue("peptide_sequence")).toQString() + " (" + QString::number(mit->first.getCharge()) + "+)";
}
QMenu * msn_precursor = msn_chromatogram->addMenu(precursor_string); // new entry for every precursor
// Show all: iterate over all chromatograms corresponding to the current precursor and add action containing all chromatograms
a = msn_precursor->addAction(QString("Show all"));
QList<QVariant> chroms_idx;
for (auto vit = mit->second.cbegin(); vit != mit->second.cend(); ++vit)
{
chroms_idx.push_back((unsigned int)*vit);
}
a->setData(chroms_idx);
// Show single chromatogram: iterate over all chromatograms corresponding to the current precursor and add action for the single chromatogram
for (auto vit = mit->second.cbegin(); vit != mit->second.cend(); ++vit)
{
a = msn_precursor->addAction(QString("Chromatogram m/z: ") + QString::number(exp.getChromatograms()[*vit].getMZ())); // Precursor => Chromatogram MZ
a->setData((int)(*vit));
}
}
}
finishContextMenu_(context_menu, settings_menu);
// show context menu and evaluate result
if ((result = context_menu->exec(mapToGlobal(e->pos()))))
{
if (result->parent()->parent() == msn_chromatogram) // clicked on chromatogram entry (level 2)
{
if (result->text() == "Show all")
{
std::vector<int> chrom_indices;
for (const auto& var : result->data().toList())
{
chrom_indices.push_back(var.toInt());
cout << "chrom_indices: " << var.toInt() << std::endl;
}
emit showChromatogramsAsNew1D(chrom_indices);
}
else // Show single chromatogram
{
//cout << "Chromatogram result " << result->data().toInt() << endl;
emit showSpectrumAsNew1D(result->data().toInt());
}
}
else if (result->parent() == msn_chromatogram_meta)
{
showMetaData(true, result->data().toInt());
}
}
}
// common actions of peaks and features
if (result)
{
if (result->text() == "Preferences")
{
showCurrentLayerPreferences();
}
else if (result->text() == "Show/hide grid lines")
{
showGridLines(!gridLinesShown());
}
else if (result->text() == "Show/hide axis legends")
{
emit changeLegendVisibility();
}
else if (result->text() == "Layer" || result->text() == "Visible layer data")
{
saveCurrentLayer(result->text() == "Visible layer data");
}
else if (result->text() == "As image")
{
spectrum_widget_->saveAsImage();
}
else if (result->text() == "Show/hide projections")
{
emit toggleProjections();
}
else if (result->text() == "Show/hide MS/MS precursors")
{
setLayerFlag(LayerDataBase::P_PRECURSORS, !getLayerFlag(LayerDataBase::P_PRECURSORS));
}
else if (result->text() == "Show/hide convex hull")
{
setLayerFlag(LayerDataBase::F_HULL, !getLayerFlag(LayerDataBase::F_HULL));
}
else if (result->text() == "Show/hide trace convex hulls")
{
setLayerFlag(LayerDataBase::F_HULLS, !getLayerFlag(LayerDataBase::F_HULLS));
}
else if (result->text() == "Show/hide unassigned peptide hits")
{
setLayerFlag(LayerDataBase::F_UNASSIGNED, !getLayerFlag(LayerDataBase::F_UNASSIGNED));
}
else if (result->text() == "Show/hide numbers/labels")
{
if (layer.label == LayerDataBase::L_NONE)
{
getCurrentLayer().label = LayerDataBase::L_META_LABEL;
}
else
{
getCurrentLayer().label = LayerDataBase::L_NONE;
}
}
}
e->accept();
}
void Plot2DCanvas::finishContextMenu_(QMenu* context_menu, QMenu* settings_menu)
{
// finish settings menu
settings_menu->addSeparator();
settings_menu->addAction("Preferences");
// create save menu
QMenu* save_menu = new QMenu("Save");
save_menu->addAction("Layer");
save_menu->addAction("Visible layer data");
save_menu->addAction("As image");
//add settings menu
context_menu->addMenu(save_menu);
context_menu->addMenu(settings_menu);
//add external context menu
if (context_add_)
{
context_menu->addSeparator();
context_menu->addMenu(context_add_);
}
}
void Plot2DCanvas::showCurrentLayerPreferences()
{
Internal::Plot2DPrefDialog dlg(this);
LayerDataBase& layer = getCurrentLayer();
ColorSelector * bg_color = dlg.findChild<ColorSelector *>("bg_color");
MultiGradientSelector * gradient = dlg.findChild<MultiGradientSelector *>("gradient");
QComboBox * feature_icon = dlg.findChild<QComboBox *>("feature_icon");
QSpinBox * feature_icon_size = dlg.findChild<QSpinBox *>("feature_icon_size");
bg_color->setColor(QColor(String(param_.getValue("background_color").toString()).toQString()));
gradient->gradient().fromString(layer.param.getValue("dot:gradient"));
feature_icon->setCurrentIndex(feature_icon->findText(String(layer.param.getValue("dot:feature_icon").toString()).toQString()));
feature_icon_size->setValue((int)layer.param.getValue("dot:feature_icon_size"));
if (dlg.exec())
{
param_.setValue("background_color", bg_color->getColor().name().toStdString());
layer.param.setValue("dot:feature_icon", feature_icon->currentText().toStdString());
layer.param.setValue("dot:feature_icon_size", feature_icon_size->value());
layer.param.setValue("dot:gradient", gradient->gradient().toString());
emit preferencesChange();
}
}
void Plot2DCanvas::currentLayerParametersChanged_()
{
recalculateDotGradient_(getCurrentLayerIndex());
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot2DCanvas::updateLayer(Size i)
{
//update nearest peak
selected_peak_.clear();
recalculateRanges_();
resetZoom(false); //no repaint as this is done in intensityModeChange_() anyway
intensityModeChange_();
modificationStatus_(i, false);
}
void Plot2DCanvas::translateVisibleArea_(double x_axis_rel, double y_axis_rel)
{
auto xy = visible_area_.getAreaXY();
const auto shift = xy.diagonal() * AreaXYType::PositionType{x_axis_rel, y_axis_rel};
// publish (bounds checking is done inside changeVisibleArea_)
changeVisibleArea_(visible_area_.cloneWith(xy + shift));
}
void Plot2DCanvas::translateLeft_(Qt::KeyboardModifiers /*m*/)
{
translateVisibleArea_( -0.05, 0.0 );
}
void Plot2DCanvas::translateRight_(Qt::KeyboardModifiers /*m*/)
{
translateVisibleArea_( 0.05, 0.0 );
}
void Plot2DCanvas::translateForward_()
{
translateVisibleArea_( 0.0, 0.05 );
}
void Plot2DCanvas::translateBackward_()
{
translateVisibleArea_(0.0, -0.05);
}
void Plot2DCanvas::keyPressEvent(QKeyEvent * e)
{
// CTRL+ALT (exactly, not e.g. CTRL+ALT+KEYPAD<X>|SHIFT...)
// note that Qt::KeypadModifier is also a modifier which gets activated when any keypad key is pressed
if (e->modifiers() == (Qt::ControlModifier | Qt::AltModifier))
{
String status_changed;
// +Home (MacOSX small keyboard: Fn+ArrowLeft) => increase point size
if ((e->key() == Qt::Key_Home) && (pen_size_max_ < PEN_SIZE_MAX_LIMIT))
{
++pen_size_max_;
status_changed = "Max. dot size increased to '" + String(pen_size_max_) + "'";
}
// +End (MacOSX small keyboard: Fn+ArrowRight) => decrease point size
else if ((e->key() == Qt::Key_End) && (pen_size_max_ > PEN_SIZE_MIN_LIMIT))
{
--pen_size_max_;
status_changed = "Max. dot size decreased to '" + String(pen_size_max_) + "'";
}
// +PageUp => increase min. coverage threshold
else if (e->key() == Qt::Key_PageUp && canvas_coverage_min_ < CANVAS_COVERAGE_MIN_LIMITHIGH)
{
canvas_coverage_min_ += 0.05; // 5% steps
status_changed = "Min. coverage threshold increased to '" + String(canvas_coverage_min_) + "'";
}
// +PageDown => decrease min. coverage threshold
else if (e->key() == Qt::Key_PageDown && canvas_coverage_min_ > CANVAS_COVERAGE_MIN_LIMITLOW)
{
canvas_coverage_min_ -= 0.05; // 5% steps
status_changed = "Min. coverage threshold decreased to '" + String(canvas_coverage_min_) + "'";
}
if (!status_changed.empty())
{
emit sendStatusMessage(status_changed, 0);
update_buffer_ = true; // full repaint
update_(OPENMS_PRETTY_FUNCTION); // schedule repaint
return;
}
}
// Delete features
LayerDataBase& layer = getCurrentLayer();
auto* lf = dynamic_cast<LayerDataFeature*>(&layer);
if (e->key() == Qt::Key_Delete && getCurrentLayer().modifiable && lf && selected_peak_.isValid())
{
lf->getFeatureMap()->erase(lf->getFeatureMap()->begin() + selected_peak_.peak);
selected_peak_.clear();
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
modificationStatus_(getCurrentLayerIndex(), true);
return;
}
// call parent class
PlotCanvas::keyPressEvent(e);
}
void Plot2DCanvas::keyReleaseEvent(QKeyEvent * e)
{
//zoom if in zoom mode and a valid rectangle is selected
if (action_mode_ == AM_ZOOM && rubber_band_.isVisible())
{
rubber_band_.hide();
QRect rect = rubber_band_.geometry();
if (rect.width() != 0 && rect.height() != 0)
{
AreaXYType area(widgetToData_(rect.topLeft()), widgetToData_(rect.bottomRight()));
changeVisibleArea_(visible_area_.cloneWith(area), true, true);
}
}
else if (action_mode_ == AM_MEASURE)
{
measurement_start_.clear();
update_(OPENMS_PRETTY_FUNCTION);
}
// do the normal stuff
PlotCanvas::keyReleaseEvent(e);
}
void Plot2DCanvas::mouseDoubleClickEvent(QMouseEvent * e)
{
LayerDataBase& current_layer = getCurrentLayer();
auto* lf = dynamic_cast<LayerDataFeature*>(¤t_layer);
if (current_layer.modifiable && lf)
{
Feature tmp;
if (selected_peak_.isValid()) //edit existing feature
{
FeatureEditDialog dialog(this);
dialog.setFeature((*lf->getFeatureMap())[selected_peak_.peak]);
if (dialog.exec())
{
tmp = dialog.getFeature();
(*lf->getFeatureMap())[selected_peak_.peak] = tmp;
}
}
else //create new feature
{
tmp.setRT(widgetToData_(e->pos())[1]);
tmp.setMZ(widgetToData_(e->pos())[0]);
FeatureEditDialog dialog(this);
dialog.setFeature(tmp);
if (dialog.exec())
{
tmp = dialog.getFeature();
lf->getFeatureMap()->push_back(tmp);
}
}
// update gradient if the min/max intensity changes
if (!lf->getFeatureMap()->getRange().containsIntensity(tmp.getIntensity()))
{
lf->getFeatureMap()->updateRanges();
recalculateRanges_();
intensityModeChange_();
}
else // just repaint to show the changes
{
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
modificationStatus_(getCurrentLayerIndex(), true);
}
}
void Plot2DCanvas::mergeIntoLayer(Size i, const FeatureMapSharedPtrType& map)
{
auto& layer = dynamic_cast<LayerDataFeature&>(layers_.getLayer(i));
//reserve enough space
layer.getFeatureMap()->reserve(layer.getFeatureMap()->size() + map->size());
//add features
for (Size j = 0; j < map->size(); ++j)
{
layer.getFeatureMap()->push_back((*map)[j]);
}
// update the layer and overall ranges (if necessary)
auto old_range = layer.getFeatureMap()->getRange();
layer.getFeatureMap()->updateRanges();
if (!old_range.containsIntensity(layer.getFeatureMap()->getRangeForDim(MSDim::INT)))
{
intensityModeChange_();
}
// clear intensity range and compare the remaining dimensions
old_range.RangeIntensity::clear();
if (!old_range.containsAll(layer.getFeatureMap()->getRange()))
{
recalculateRanges_();
resetZoom(true);
}
}
void Plot2DCanvas::mergeIntoLayer(Size i, const ConsensusMapSharedPtrType& map)
{
auto& layer = dynamic_cast<LayerDataConsensus&>(layers_.getLayer(i));
OPENMS_PRECONDITION(layer.type == LayerDataBase::DT_CONSENSUS, "Plot2DCanvas::mergeIntoLayer(i, map) non-consensus-feature layer selected");
//reserve enough space
layer.getConsensusMap()->reserve(layer.getConsensusMap()->size() + map->size());
//add features
for (Size j = 0; j < map->size(); ++j)
{
layer.getConsensusMap()->push_back((*map)[j]);
}
// update the layer and overall ranges (if necessary)
auto old_range = layer.getConsensusMap()->getRange();
layer.getConsensusMap()->updateRanges();
if (!old_range.containsIntensity(layer.getConsensusMap()->getRangeForDim(MSDim::INT)))
{
intensityModeChange_();
}
// clear intensity range and compare the remaining dimensions
old_range.RangeIntensity::clear();
if (!old_range.containsAll(layer.getConsensusMap()->getRange()))
{
recalculateRanges_();
resetZoom(true);
}
}
void Plot2DCanvas::mergeIntoLayer(Size i, PeptideIdentificationList & peptides)
{
LayerDataBase& layer = layers_.getLayer(i);
OPENMS_PRECONDITION(layer.type == LayerDataBase::DT_IDENT, "Plot2DCanvas::mergeIntoLayer(i, peptides) non-identification layer selected");
auto& layer_peptides = dynamic_cast<IPeptideIds*>(&layer)->getPeptideIds();
// reserve enough space
layer_peptides.reserve(layer_peptides.size() + peptides.size());
// insert peptides
layer_peptides.insert(layer_peptides.end(), peptides.begin(),
peptides.end());
// update the layer and overall ranges
recalculateRanges_();
resetZoom(true);
}
bool Plot2DCanvas::collectFragmentScansInArea_(const RangeType& range, QMenu* msn_scans, QMenu* msn_meta)
{
auto& layer = dynamic_cast<LayerDataPeak&>(getCurrentLayer());
bool item_added = false;
const MSExperiment& peak_data = layer.getPeakData()->getMSExperiment();
const auto last_RT = peak_data.RTEnd(range.getMaxRT());
for (auto it = peak_data.RTBegin(range.getMinRT());
it != last_RT; ++it)
{
if (it->getPrecursors().empty()) continue;
double mz = it->getPrecursors()[0].getMZ();
if (it->getMSLevel() > 1 && range.containsMZ(mz))
{
msn_scans->addAction(QString("RT: ") + QString::number(it->getRT()) + " mz: " + QString::number(mz),
[=, this]() { emit showSpectrumAsNew1D(it - peak_data.begin()); });
msn_meta->addAction(QString("RT: ") + QString::number(it->getRT()) + " mz: " + QString::number(mz),
[=, this]() { showMetaData(true, it - peak_data.begin()); });
item_added = true;
}
}
return item_added;
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/OutputDirectory.cpp | .cpp | 2,339 | 88 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/OutputDirectory.h>
#include <ui_OutputDirectory.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QCompleter>
#include <QFileSystemModel>
namespace OpenMS
{
OutputDirectory::OutputDirectory(QWidget* parent)
: QWidget(parent),
ui_(new Ui::OutputDirectoryTemplate)
{
ui_->setupUi(this);
QCompleter* completer = new QCompleter(this);
QFileSystemModel* dir_model = new QFileSystemModel(completer);
dir_model->setFilter(QDir::AllDirs);
completer->setModel(dir_model);
ui_->line_edit->setCompleter(completer);
connect(ui_->browse_button, &QPushButton::clicked, this, &OutputDirectory::showFileDialog);
connect(ui_->line_edit, &QLineEdit::textChanged, this, &OutputDirectory::textEditChanged_);
}
OutputDirectory::~OutputDirectory()
{
delete ui_;
}
void OutputDirectory::setDirectory(const QString& dir)
{
ui_->line_edit->setText(dir);
emit directoryChanged(dir);
}
QString OutputDirectory::getDirectory() const
{
return ui_->line_edit->text();
}
void OutputDirectory::showFileDialog()
{
QString dir = File::exists(File::path(getDirectory())) ? File::path(getDirectory()).toQString() : "";
QString selected_dir = QFileDialog::getExistingDirectory(this, tr("Select output directory"), dir);
if (!selected_dir.isEmpty())
{
setDirectory(selected_dir); // emits directoryChanged()
}
}
void OutputDirectory::textEditChanged_(const QString& /*new_text*/)
{
emit directoryChanged(getDirectory());
}
bool OutputDirectory::dirNameValid() const
{
if (!QFileInfo(getDirectory()).isDir())
{
return false;
}
QString file_name = getDirectory();
if (!file_name.endsWith(QDir::separator()))
{
file_name += QDir::separator();
}
file_name += "test_file";
return File::writable(file_name);
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Plot1DCanvas.cpp | .cpp | 51,044 | 1,574 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm, Timo Sachsenberg, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/Plot1DCanvas.h>
// OpenMS
#include <OpenMS/VISUAL/PlotWidget.h>
#include <OpenMS/VISUAL/Plot1DWidget.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/DIALOGS/Plot1DPrefDialog.h>
#include <OpenMS/VISUAL/ColorSelector.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotations1DContainer.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DTextItem.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DDistanceItem.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/COMPARISON/SpectrumAlignmentScore.h>
#include <OpenMS/COMPARISON/SpectrumAlignment.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/LayerData1DChrom.h>
// Qt
#include <QElapsedTimer>
#include <QMouseEvent>
#include <QPainter>
#include <QtWidgets/QInputDialog>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMessageBox>
#include <utility>
#include <boost/make_shared.hpp>
using namespace std;
namespace OpenMS
{
using namespace Math;
using namespace Internal;
/// returns an MSExp with a single spec (converted from @p exp_sptr's chromatograms at index @p index (or ondisc_sptr, if that should be empty)
Plot1DCanvas::ExperimentSharedPtrType prepareChromatogram(Size index, const Plot1DCanvas::ExperimentSharedPtrType& exp_sptr, const Plot1DCanvas::ODExperimentSharedPtrType& ondisc_sptr)
{
// create a managed pointer fill it with a spectrum containing the chromatographic data
auto chrom_exp_sptr = std::make_shared<AnnotatedMSRun>();
chrom_exp_sptr->getMSExperiment().setMetaValue("is_chromatogram", "true"); //this is a hack to store that we have chromatogram data
LayerDataBase::ExperimentType::SpectrumType spectrum;
// retrieve chromatogram (either from in-memory or on-disc representation)
MSChromatogram current_chrom = exp_sptr->getMSExperiment().getChromatograms()[index];
if (current_chrom.empty())
{
current_chrom = ondisc_sptr->getChromatogram(index);
}
// fill "dummy" spectrum with chromatogram data
for (const ChromatogramPeak& cpeak : current_chrom)
{
spectrum.emplace_back(cpeak.getRT(), cpeak.getIntensity());
}
spectrum.getFloatDataArrays() = current_chrom.getFloatDataArrays();
spectrum.getIntegerDataArrays() = current_chrom.getIntegerDataArrays();
spectrum.getStringDataArrays() = current_chrom.getStringDataArrays();
// Add at least one data point to the chromatogram, otherwise
// "addPeakLayer" will fail and a segfault occurs later
if (current_chrom.empty())
{
spectrum.emplace_back(-1, 0);
}
chrom_exp_sptr->getMSExperiment().addSpectrum(std::move(spectrum));
// store peptide_sequence if available
if (current_chrom.getPrecursor().metaValueExists("peptide_sequence"))
{
chrom_exp_sptr->getMSExperiment().setMetaValue("peptide_sequence", current_chrom.getPrecursor().getMetaValue("peptide_sequence"));
}
return chrom_exp_sptr;
}
Plot1DCanvas::Plot1DCanvas(const Param& preferences, const DIM gravity_axis, QWidget* parent) :
PlotCanvas(preferences, parent),
gr_(gravity_axis)
{
// for now, default to mz x int
unit_mapper_ = DimMapper<2>({DIM_UNIT::MZ, DIM_UNIT::INT});
//Parameter handling
defaults_.setValue("highlighted_peak_color", "#ff0000", "Highlighted peak color.");
defaults_.setValue("icon_color", "#000000", "Peak icon color.");
defaults_.setValue("peak_color", "#0000ff", "Peak color.");
defaults_.setValue("annotation_color", "#000055", "Annotation color.");
defaults_.setValue("background_color", "#ffffff", "Background color.");
defaultsToParam_();
setName("Plot1DCanvas");
setParameters(preferences);
// connect preferences change to the right slot
connect(this, SIGNAL(preferencesChange()), this, SLOT(currentLayerParamtersChanged_()));
}
Plot1DCanvas::~Plot1DCanvas() = default;
const LayerData1DBase& Plot1DCanvas::getLayer(Size index) const
{
return dynamic_cast<const LayerData1DBase&>(layers_.getLayer(index));
}
LayerData1DBase& Plot1DCanvas::getLayer(Size index)
{
return dynamic_cast<LayerData1DBase&>(layers_.getLayer(index));
}
const LayerData1DBase& Plot1DCanvas::getCurrentLayer() const
{
return dynamic_cast<const LayerData1DBase&>(layers_.getCurrentLayer());
}
LayerData1DBase& Plot1DCanvas::getCurrentLayer()
{
return dynamic_cast<LayerData1DBase&>(layers_.getCurrentLayer());
}
const DimBase& Plot1DCanvas::getGravityDim() const
{
return unit_mapper_.getDim(getGravitator().getGravityAxis());
}
const DimBase& Plot1DCanvas::getNonGravityDim() const
{
return unit_mapper_.getDim(getGravitator().swap().getGravityAxis());
}
bool Plot1DCanvas::addChromLayer(ExperimentSharedPtrType chrom_exp_sptr,
ODExperimentSharedPtrType ondisc_sptr,
OSWDataSharedPtrType chrom_annotation,
const int index,
const String& filename,
const String& basename,
const String& basename_extra)
{
// we do not want addChromLayer to trigger repaint, since we have not set the chromatogram data!
this->blockSignals(true);
RAIICleanup clean([&]()
{
this->blockSignals(false);
});
// add chromatogram data as peak spectrum
if (!PlotCanvas::addChromLayer(std::move(chrom_exp_sptr), std::move(ondisc_sptr), filename))
{
return false;
}
auto& ld = dynamic_cast<LayerData1DChrom&>(getCurrentLayer());
ld.setName(basename);
ld.setNameSuffix(basename_extra);
ld.getChromatogramAnnotation() = std::move(chrom_annotation); // copy over shared-ptr to OSW-sql data (if available)
ld.setCurrentIndex(index); // use this chrom for visualization
recalculateRanges_(); // needed here, since 'setCurrentIndex()' changes the current Chromatogram
setDrawMode(Plot1DCanvas::DM_CONNECTEDLINES);
//setIntensityMode(Plot1DCanvas::IM_NONE);
// extend the currently visible area, so the new data is visible
//auto va = visible_area_.getAreaUnit();
return true;
}
void Plot1DCanvas::activateLayer(Size layer_index)
{
layers_.setCurrentLayer(layer_index);
// no peak is selected
selected_peak_.clear();
emit layerActivated(this);
}
void Plot1DCanvas::changeVisibleArea1D_(const UnitRange& new_area, bool repaint, bool add_to_stack)
{
auto corrected = correctGravityAxisOfVisibleArea_(new_area);
PlotCanvas::changeVisibleArea_(visible_area_.cloneWith(corrected), repaint, add_to_stack);
}
void Plot1DCanvas::changeVisibleArea_(const AreaXYType& new_area, bool repaint, bool add_to_stack)
{
changeVisibleArea1D_(visible_area_.cloneWith(new_area).getAreaUnit(), repaint, add_to_stack);
}
void Plot1DCanvas::changeVisibleArea_(const UnitRange& new_area, bool repaint, bool add_to_stack)
{
changeVisibleArea1D_(new_area, repaint, add_to_stack);
}
void Plot1DCanvas::changeVisibleArea_(VisibleArea new_area, bool repaint, bool add_to_stack)
{
changeVisibleArea1D_(new_area.getAreaUnit(), repaint, add_to_stack);
}
void Plot1DCanvas::dataToWidget(const DPosition<2>& xy_point, QPoint& point, bool flipped)
{
Plot1DCanvas::dataToWidget(xy_point.getX(), xy_point.getY(), point, flipped);
}
void Plot1DCanvas::dataToWidget(const DPosition<2>& xy_point, DPosition<2>& point, bool flipped)
{
QPoint p;
Plot1DCanvas::dataToWidget(xy_point.getX(), xy_point.getY(), p, flipped);
point.setX(p.x());
point.setY(p.y());
}
void Plot1DCanvas::dataToWidget(double x, double y, QPoint& point, bool flipped)
{
QPoint tmp;
// adapting gravity dimension is required for percentage mode
if (gr_.getGravityAxis() == DIM::Y) y *= percentage_factor_;
else if (gr_.getGravityAxis() == DIM::X) x *= percentage_factor_;
dataToWidget_(x, y, tmp);
point.setX(tmp.x());
point.setY(tmp.y());
if (mirror_mode_)
{
double alignment_shrink_factor = 1.0;
if (height() > 10)
{
alignment_shrink_factor = (double)(height() - 10) / (double)height();
}
if (flipped)
{
if (!show_alignment_)
{
point.setY(height() - (int)(tmp.y() / 2.0));
}
else // show_alignment_
{
point.setY(height() - (int)((tmp.y() * alignment_shrink_factor) / 2.0));
}
}
else // !flipped
{
if (!show_alignment_)
{
point.setY((int)(tmp.y() / 2.0));
}
else // show_alignment_
{
point.setY((int)((tmp.y() * alignment_shrink_factor) / 2.0));
}
}
}
}
PointXYType Plot1DCanvas::widgetToData(const QPoint& pos)
{
return widgetToData(pos.x(), pos.y());
}
PointXYType Plot1DCanvas::widgetToData(double x, double y)
{
double actual_y;
if (mirror_mode_)
{
double alignment_shrink_factor = 1.0;
if (height() > 10)
{
alignment_shrink_factor = (double)(height() - 10) / (double)height();
}
if (y > height() / 2.0)
{
if (!show_alignment_)
{
actual_y = (height() - y) * 2;
}
else
{
actual_y = (height() - y) * 2 / alignment_shrink_factor;
}
}
else // y <= height()/2
{
if (!show_alignment_)
{
actual_y = y * 2;
}
else
{
actual_y = y * 2 / alignment_shrink_factor;
}
}
}
else
{
actual_y = y;
}
PointXYType p = PlotCanvas::widgetToData_(x, actual_y);
// adapting gravity dimension is required for percentage mode
if (gr_.getGravityAxis() == DIM::Y) p.setY(p.getY() / (percentage_factor_));
else if (gr_.getGravityAxis() == DIM::X) p.setX(p.getX() / (percentage_factor_));
return p;
}
//////////////////////////////////////////////////////////////////////////////////
// Qt events
void Plot1DCanvas::mousePressEvent(QMouseEvent* e)
{
// get mouse position in widget coordinates
last_mouse_pos_ = e->pos();
if (e->button() == Qt::LeftButton)
{
// selection/deselection of annotation items
Annotation1DItem* item = getCurrentLayer().getCurrentAnnotations().getItemAt(last_mouse_pos_);
if (item)
{
if (!(e->modifiers() & Qt::ControlModifier))
{
// edit via double-click
if (e->type() == QEvent::MouseButtonDblClick)
{
item->editText();
}
else if (!item->isSelected())
{
// the item becomes the only selected item
getCurrentLayer().getCurrentAnnotations().deselectAll();
item->setSelected(true);
}
// an item was clicked -> can be moved on the canvas
moving_annotations_ = true;
}
else
{
// ctrl pressed -> allow selection/deselection of multiple items, do not deselect others
item->setSelected(!item->isSelected());
}
// if item is a distance item: show distance of selected item in status bar
Annotation1DDistanceItem * distance_item = dynamic_cast<Annotation1DDistanceItem *>(item);
if (distance_item)
{
emit sendStatusMessage(String("Measured: d") + getNonGravityDim().getDimNameShort() + "= " + distance_item->getDistance(), 0);
}
}
else
{
// no item was under the cursor
getCurrentLayer().getCurrentAnnotations().deselectAll();
}
if (action_mode_ == AM_ZOOM)
{
rubber_band_.setGeometry(QRect(e->pos(), QSize()));
rubber_band_.show();
}
else if (action_mode_ == AM_MEASURE)
{
if (selected_peak_.isValid())
{
measurement_start_ = selected_peak_;
auto peak_xy = getCurrentLayer().peakIndexToXY(measurement_start_, unit_mapper_);
recalculatePercentageFactor_(getCurrentLayerIndex());
dataToWidget(peak_xy, measurement_start_point_px_, getCurrentLayer().flipped);
// use intensity (usually) of mouse, not of the peak
measurement_start_point_px_ = gr_.gravitateTo(measurement_start_point_px_, last_mouse_pos_);
}
else
{
measurement_start_.clear();
}
}
}
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot1DCanvas::mouseMoveEvent(QMouseEvent* e)
{
// mouse position relative to the diagram widget
QPoint p = e->pos();
PointXYType data_pos = widgetToData(p);
emit sendCursorStatus(unit_mapper_.getDim(DIM::X).formattedValue(data_pos[0]),
unit_mapper_.getDim(DIM::Y).formattedValue(data_pos[1]));
PeakIndex near_peak = findPeakAtPosition_(p);
if (e->buttons() & Qt::LeftButton)
{
bool move = moving_annotations_;
if (mirror_mode_ && (getCurrentLayer().flipped ^ (p.y() > height() / 2)))
{
move = false;
}
if (move)
{
recalculatePercentageFactor_(getCurrentLayerIndex());
PointXYType delta = widgetToData(p) - widgetToData(last_mouse_pos_);
Annotations1DContainer& ann_1d = getCurrentLayer().getCurrentAnnotations();
for (Annotations1DContainer::Iterator it = ann_1d.begin(); it != ann_1d.end(); ++it)
{
if ((*it)->isSelected())
{
(*it)->move(delta, gr_, unit_mapper_);
}
}
update_(OPENMS_PRETTY_FUNCTION);
last_mouse_pos_ = p;
}
else if (action_mode_ == AM_TRANSLATE)
{
// translation in data metric
const double shift = widgetToData(last_mouse_pos_).getX() - widgetToData(p).getX();
auto new_va = visible_area_.cloneWith(visible_area_.getAreaXY() + PointXYType(shift, 0)).getAreaUnit();
// change data area
changeVisibleArea_(new_va);
last_mouse_pos_ = p;
}
else if (action_mode_ == AM_MEASURE)
{
if (near_peak.peak != measurement_start_.peak)
{
selected_peak_ = near_peak;
last_mouse_pos_ = p;
update_(OPENMS_PRETTY_FUNCTION);
}
}
else if (action_mode_ == AM_ZOOM)
{
const auto pixel_area = canvasPixelArea();
auto r_start = gr_.gravitateMin(last_mouse_pos_, pixel_area);
auto r_end = gr_.gravitateMax(p, pixel_area);
rubber_band_.setGeometry(QRect(r_start, r_end).normalized());
rubber_band_.show(); // if the mouse button is pressed before the zoom key is pressed
update_(OPENMS_PRETTY_FUNCTION);
}
}
else if (!e->buttons()) // no buttons pressed
{
selected_peak_ = near_peak;
update_(OPENMS_PRETTY_FUNCTION);
}
// show coordinates of data arrays
if (selected_peak_.isValid())
{
emit sendStatusMessage(getCurrentLayer().getDataArrayDescription(selected_peak_), 0);
}
}
void Plot1DCanvas::mouseReleaseEvent(QMouseEvent* e)
{
if (e->button() == Qt::LeftButton)
{
if (action_mode_ == AM_ZOOM)
{
rubber_band_.hide();
QRect rect = rubber_band_.geometry();
if (rect.width() != 0)
{
AreaXYType area(widgetToData(rect.topLeft()), widgetToData(rect.bottomRight()));
changeVisibleArea_(area, true, true);
}
}
else if (action_mode_ == AM_MEASURE)
{
if (selected_peak_.isValid() && measurement_start_.isValid() && selected_peak_.peak != measurement_start_.peak)
{
auto start_xy = getCurrentLayer().peakIndexToXY(measurement_start_, unit_mapper_);
auto end_xy = getCurrentLayer().peakIndexToXY(selected_peak_, unit_mapper_);
// line should be horizontal at the mouse position --> adapt gravity coordinates
auto mouse_xy = widgetToData(e->pos());
start_xy = gr_.gravitateTo(start_xy, mouse_xy);
end_xy = gr_.gravitateTo(end_xy, mouse_xy);
recalculatePercentageFactor_(getCurrentLayerIndex());
// draw line for measured distance between two peaks and annotate with distance in m/z -- use 4 digits to resolve 13C distances between isotopes
auto* item = new Annotation1DDistanceItem("", start_xy, end_xy);
item->setText(QString::number(item->getDistance(), 'f', getNonGravityDim().valuePrecision()));
getCurrentLayer().getCurrentAnnotations().push_front(item);
}
}
moving_annotations_ = false;
measurement_start_.clear();
update_(OPENMS_PRETTY_FUNCTION);
}
}
void Plot1DCanvas::keyPressEvent(QKeyEvent* e)
{
// Delete pressed => delete selected annotations from the current layer
if (e->key() == Qt::Key_Delete)
{
e->accept();
auto peak_layer = dynamic_cast<LayerData1DPeak*>(&getCurrentLayer());
if (peak_layer) peak_layer->removePeakAnnotationsFromPeptideHit(getCurrentLayer().getCurrentAnnotations().getSelectedItems());
getCurrentLayer().getCurrentAnnotations().removeSelectedItems();
update_(OPENMS_PRETTY_FUNCTION);
}
// 'b' pressed && in zoom mode (Ctrl pressed) => select all annotation items
else if ((e->modifiers() & Qt::ControlModifier) && (e->key() == Qt::Key_B))
{
e->accept();
getCurrentLayer().getCurrentAnnotations().selectAll();
update_(OPENMS_PRETTY_FUNCTION);
}
else
{
PlotCanvas::keyPressEvent(e);
}
}
PeakIndex Plot1DCanvas::findPeakAtPosition_(QPoint p)
{
//no layers => return invalid peak index
if (layers_.empty())
{
return PeakIndex();
}
// mirror mode and p not on same half as active layer => return invalid peak index
if (mirror_mode_ && (getCurrentLayer().flipped ^ (p.y() > height() / 2)))
{
return PeakIndex();
}
recalculatePercentageFactor_(getCurrentLayerIndex());
RangeAllType search_area = unit_mapper_.fromXY(widgetToData(p - QPoint(2, 2)));
search_area.extend(unit_mapper_.fromXY(widgetToData(p + QPoint(2, 2))));
return getCurrentLayer().findClosestDataPoint(search_area);
}
//////////////////////////////////////////////////////////////////////////////////
// SLOTS
void Plot1DCanvas::removeLayer(Size layer_index)
{
// remove settings
layers_.removeLayer(layer_index);
draw_modes_.erase(draw_modes_.begin() + layer_index);
peak_penstyle_.erase(peak_penstyle_.begin() + layer_index);
// update nearest peak
selected_peak_.clear();
// abort if there are no layers anymore
if (layers_.empty())
{
overall_data_range_.clearRanges();
update_(OPENMS_PRETTY_FUNCTION);
return;
}
if (!flippedLayersExist())
{
setMirrorModeActive(false);
}
// update range area
recalculateRanges_();
zoomClear_();
changeVisibleArea_(overall_data_range_, true, true);
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot1DCanvas::setDrawMode(DrawModes mode)
{
//no layers
if (layers_.empty())
{
return;
}
if (draw_modes_[getCurrentLayerIndex()] != mode)
{
draw_modes_[getCurrentLayerIndex()] = mode;
update_(OPENMS_PRETTY_FUNCTION);
}
}
Plot1DCanvas::DrawModes Plot1DCanvas::getDrawMode() const
{
//no layers
if (layers_.empty())
{
return DM_PEAKS;
}
return draw_modes_[getCurrentLayerIndex()];
}
void Plot1DCanvas::paintEvent(QPaintEvent* e)
{
QPainter painter(this);
paint(&painter, e);
painter.end();
}
void Plot1DCanvas::paint(QPainter* painter, QPaintEvent* e)
{
QElapsedTimer timer;
timer.start();
// clear
painter->fillRect(0, 0, this->width(), this->height(),
QColor(String(param_.getValue("background_color").toString()).toQString()));
// we are done if no layer is present
if (getLayerCount() == 0)
{
e->accept();
return;
}
// gridlines
paintGridLines_(*painter);
// paint each layer
for (Size i = 0; i < getLayerCount(); ++i)
{
recalculatePercentageFactor_(i);
auto paint_1d = getLayer(i).getPainter1D();
paint_1d->paint(painter, this, (int)i);
}
if (show_alignment_)
{
drawAlignment_(*painter);
}
if (mirror_mode_)
{
painter->save();
if (!show_alignment_)
{
// draw x-axis
painter->setPen(Qt::black);
painter->drawLine(0, height() / 2, width(), height() / 2);
}
else
{
// two x-axes:
painter->setPen(Qt::black);
painter->drawLine(0, height() / 2 + 5, width(), height() / 2 + 5);
painter->drawLine(0, height() / 2 - 5, width(), height() / 2 - 5);
}
painter->restore();
}
// draw measuring line when in measure mode and valid measurement start peak selected
if (action_mode_ == AM_MEASURE && measurement_start_.isValid())
{
// use start-point + mouse position of non-gravity axis
QPoint measurement_end_point_px = gr_.swap().gravitateTo(measurement_start_point_px_, last_mouse_pos_);
auto ps = widgetToData(measurement_start_point_px_);
auto pe = widgetToData(measurement_end_point_px);
Annotation1DDistanceItem(QString::number(gr_.swap().gravityDiff(ps, pe), 'f', 4), ps, pe).draw(this, *painter, false);
}
// draw highlighted measurement start peak and selected peak
bool with_elongation = (action_mode_ == AM_MEASURE);
drawHighlightedPeak_(getCurrentLayerIndex(), measurement_start_, *painter, with_elongation);
drawHighlightedPeak_(getCurrentLayerIndex(), selected_peak_, *painter, with_elongation);
//draw delta for measuring
if (action_mode_ == AM_MEASURE && measurement_start_.isValid())
{
drawDeltas_(*painter, measurement_start_, selected_peak_);
}
else
{
drawCoordinates_(*painter, selected_peak_);
}
// draw text box (supporting HTML) on the right side of the canvas
if (!text_box_content_.isEmpty())
{
painter->save();
double w = text_box_content_.size().width();
double h = text_box_content_.size().height();
//draw text
painter->setPen(Qt::black);
painter->translate(width() - w - 2, 3);
painter->fillRect(static_cast<int>(width() - w - 2),
3,
static_cast<int>(w),
static_cast<int>(h),
QColor(255, 255, 255, 200));
text_box_content_.drawContents(painter);
painter->restore();
}
if (show_timing_)
{
cout << "paint event took " << timer.elapsed() << " ms" << endl;
}
}
void Plot1DCanvas::drawHighlightedPeak_(Size layer_index, const PeakIndex& peak, QPainter& painter, bool draw_elongation)
{
if (!peak.isValid()) return;
const auto sel_xy = getLayer(layer_index).peakIndexToXY(peak, unit_mapper_);
painter.setPen(QPen(QColor(String(param_.getValue("highlighted_peak_color").toString()).toQString()), 2));
recalculatePercentageFactor_(layer_index);
QPoint begin;
dataToWidget(sel_xy, begin, getLayer(layer_index).flipped);
// paint the cross-hair only for currently selected peaks of the current layer
if (layer_index == getCurrentLayerIndex() && (peak == measurement_start_ || peak == selected_peak_))
{
Painter1DBase::drawCross(begin, &painter, 8);
}
// draw elongation as dashed line (while in measure mode and for all existing distance annotations)
if (draw_elongation)
{
QPoint top_end = (getLayer(layer_index).flipped) ? gr_.gravitateMax(begin, canvasPixelArea()) : gr_.gravitateMin(begin, canvasPixelArea());
Painter1DBase::drawDashedLine(begin, top_end, &painter, String(param_.getValue("highlighted_peak_color").toString()).toQString());
}
}
bool Plot1DCanvas::finishAdding_()
{
/* const MSSpectrum& spectrum = getCurrentLayer().getCurrentSpectrum();
// Abort if no data points are contained (note that all data could be on disk)
if (spectrum.empty())
{
popIncompleteLayer_("Cannot add a dataset that contains no survey scans. Aborting!");
return false;
}
*/
// add new draw mode and style (default: peaks)
draw_modes_.push_back(DM_PEAKS);
peak_penstyle_.push_back(Qt::SolidLine);
// Change peak color if this is not the first layer
switch (getCurrentLayerIndex() % 5)
{
case 0:
getCurrentLayer().param.setValue("peak_color", "#0000ff");
getCurrentLayer().param.setValue("annotation_color", "#005500");
break;
case 1:
getCurrentLayer().param.setValue("peak_color", "#00cc00");
getCurrentLayer().param.setValue("annotation_color", "#005500");
break;
case 2:
getCurrentLayer().param.setValue("peak_color", "#cc0000");
getCurrentLayer().param.setValue("annotation_color", "#550055");
break;
case 3:
getCurrentLayer().param.setValue("peak_color", "#00cccc");
getCurrentLayer().param.setValue("annotation_color", "#005555");
break;
case 4:
getCurrentLayer().param.setValue("peak_color", "#ffaa00");
getCurrentLayer().param.setValue("annotation_color", "#550000");
break;
}
// update nearest peak
selected_peak_.clear();
// update ranges
getCurrentLayer().updateRanges();
recalculateRanges_();
resetZoom(false); // no repaint as this is done in setIntensityMode() anyway
// warn if negative intensities are contained
if (getCurrentMinIntensity() < 0.0f)
{
QMessageBox::warning(this, "Warning", "This dataset contains negative intensities. Use it at your own risk!");
}
if (getLayerCount() == 2)
{
setIntensityMode(IM_PERCENTAGE);
}
emit layerActivated(this);
return true;
}
void Plot1DCanvas::drawCoordinates_(QPainter& painter, const PeakIndex& peak)
{
if (!peak.isValid())
{
return;
}
const auto xy_point = getCurrentLayer().peakIndexToXY(peak, unit_mapper_);
QStringList lines;
lines << unit_mapper_.getDim(DIM::X).formattedValue(xy_point.getX()).toQString();
lines << unit_mapper_.getDim(DIM::Y).formattedValue(xy_point.getY()).toQString();
drawText_(painter, lines);
}
void Plot1DCanvas::drawDeltas_(QPainter& painter, const PeakIndex& start, const PeakIndex& end)
{
if (!start.isValid())
{
return;
}
const auto peak_start = getCurrentLayer().peakIndexToXY(start, unit_mapper_);
auto peak_end = decltype(peak_start){}; // same as peak_start but without the const
if (end.isValid())
{
peak_end = getCurrentLayer().peakIndexToXY(end, unit_mapper_);
}
else
{
peak_end = widgetToData_(last_mouse_pos_);
peak_end = gr_.gravitateNAN(peak_end); // we do not care about the gravity dimension (usually intensity)
}
auto dim_text = [](const DimBase& dim, double start_pos, double end_pos, bool ratio /*or difference*/)
{
QString result;
if (ratio)
{
result = dim.formattedValue(end_pos / start_pos, " ratio ").toQString();
}
else
{
result = dim.formattedValue(end_pos - start_pos, " delta ").toQString();
if (dim.getUnit() == DIM_UNIT::MZ)
{
auto ppm = Math::getPPM(end_pos, start_pos);
result += " (" + QString::number(ppm, 'f', 1) + " ppm)";
}
}
return result;
};
QStringList lines;
lines << dim_text(unit_mapper_.getDim(DIM::X), peak_start.getX(), peak_end.getX(), gr_.getGravityAxis() == DIM::X);
lines << dim_text(unit_mapper_.getDim(DIM::Y), peak_start.getY(), peak_end.getY(), gr_.getGravityAxis() == DIM::Y);
drawText_(painter, lines);
}
void Plot1DCanvas::recalculatePercentageFactor_(Size layer_index)
{
if (intensity_mode_ == IM_PERCENTAGE)
{
// maximum value (usually intensity) in whole layer
const auto max_data_gravity = unit_mapper_.mapRange(getLayer(layer_index).getRange1D()).maxPosition()[(int)gr_.getGravityAxis()];
percentage_factor_ = 100 / max_data_gravity;
}
else
{
percentage_factor_ = 1.0;
}
}
void Plot1DCanvas::updateScrollbars_()
{
auto xy_overall_area = visible_area_.cloneWith(overall_data_range_1d_).getAreaXY();
emit updateHScrollbar(xy_overall_area.minPosition()[0], visible_area_.getAreaXY().minPosition()[0], visible_area_.getAreaXY().maxPosition()[0], xy_overall_area.maxPosition()[0]);
emit updateVScrollbar(1, 1, 1, 1);
}
void Plot1DCanvas::horizontalScrollBarChange(int value)
{
auto new_area = visible_area_.getAreaXY();
float shift = value - new_area.center().getX();
new_area += decltype(new_area)::PositionType(shift, 0);
changeVisibleArea_(new_area);
}
void Plot1DCanvas::showCurrentLayerPreferences()
{
Internal::Plot1DPrefDialog dlg(this);
LayerDataBase& layer = getCurrentLayer();
ColorSelector* peak_color = dlg.findChild<ColorSelector*>("peak_color");
ColorSelector* icon_color = dlg.findChild<ColorSelector*>("icon_color");
ColorSelector* annotation_color = dlg.findChild<ColorSelector*>("annotation_color");
ColorSelector* bg_color = dlg.findChild<ColorSelector*>("bg_color");
ColorSelector* selected_color = dlg.findChild<ColorSelector*>("selected_color");
peak_color->setColor(QColor(String(layer.param.getValue("peak_color").toString()).toQString()));
icon_color->setColor(QColor(String(layer.param.getValue("icon_color").toString()).toQString()));
annotation_color->setColor(QColor(String(layer.param.getValue("annotation_color").toString()).toQString()));
bg_color->setColor(QColor(String(param_.getValue("background_color").toString()).toQString()));
selected_color->setColor(QColor(String(param_.getValue("highlighted_peak_color").toString()).toQString()));
if (dlg.exec())
{
layer.param.setValue("peak_color", peak_color->getColor().name().toStdString());
layer.param.setValue("icon_color", icon_color->getColor().name().toStdString());
layer.param.setValue("annotation_color", annotation_color->getColor().name().toStdString());
param_.setValue("background_color", bg_color->getColor().name().toStdString());
param_.setValue("highlighted_peak_color", selected_color->getColor().name().toStdString());
emit preferencesChange();
}
}
void Plot1DCanvas::currentLayerParamtersChanged_()
{
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot1DCanvas::contextMenuEvent(QContextMenuEvent* e)
{
if (layers_.empty()) { return; }
QMenu* context_menu = new QMenu(this);
Annotations1DContainer& annots_1d = getCurrentLayer().getCurrentAnnotations();
Annotation1DItem* annot_item = annots_1d.getItemAt(e->pos());
bool need_repaint = false; /// will get updated by context menu actions
if (annot_item)
{
annots_1d.deselectAll();
annots_1d.selectItemAt(e->pos());
update_(OPENMS_PRETTY_FUNCTION);
context_menu->addMenu(getCurrentLayer()
.getContextMenuAnnotation(annot_item, need_repaint));
}
else // !annot_item
{
//Display name and warn if current layer invisible
String layer_name = String("Layer: ") + getCurrentLayer().getName();
if (!getCurrentLayer().visible)
{
layer_name += " (invisible)";
}
context_menu->addAction(layer_name.toQString())->setEnabled(false);
context_menu->addSeparator();
context_menu->addAction("Add label", [&]() {
addUserLabelAnnotation_(e->pos());
})->setEnabled(!(mirror_mode_ && (getCurrentLayer().flipped ^ (e->pos().y() > height() / 2))));
PeakIndex near_peak = findPeakAtPosition_(e->pos());
context_menu->addAction("Add peak annotation", [&]() {
addUserPeakAnnotation_(near_peak);
})->setEnabled(near_peak.isValid());
context_menu->addAction((String("Add peak annotation ") + String(getNonGravityDim().getDimNameShort())).toQString(), [&]() {
const auto xy_point = getCurrentLayer().peakIndexToXY(near_peak, unit_mapper_);
QString label = getNonGravityDim().formattedValue(gr_.swap().gravityValue(xy_point)).toQString();
addPeakAnnotation(near_peak, label, String(getCurrentLayer().param.getValue("peak_color").toString()).toQString());
})->setEnabled(near_peak.isValid());
context_menu->addSeparator();
context_menu->addAction("Reset alignment", [&]() {
resetAlignment();
})->setEnabled(show_alignment_);
context_menu->addSeparator();
context_menu->addAction("Layer meta data", [&]() {
showMetaData(true);
});
QMenu* save_menu = new QMenu("Save");
save_menu->addAction("Layer", [&]() {
saveCurrentLayer(false);
});
save_menu->addAction("Visible layer data", [&]() {
saveCurrentLayer(true);
});
save_menu->addAction("As image", [&]() {
spectrum_widget_->saveAsImage();
});
QMenu* settings_menu = new QMenu("Settings");
settings_menu->addAction("Show/hide grid lines", [&]() {
showGridLines(!gridLinesShown());
});
settings_menu->addAction("Show/hide axis legends", [&]() {
emit changeLegendVisibility();
});
settings_menu->addAction("Style: Stick <--> Area", [&]() {
if (getDrawMode() != DM_PEAKS)
{
setDrawMode(DM_PEAKS);
}
else
{
setDrawMode(DM_CONNECTEDLINES);
}
});
settings_menu->addAction("Intensity: Absolute <--> Percent", [&]() {
if (getIntensityMode() != IM_PERCENTAGE)
{
setIntensityMode(IM_PERCENTAGE);
}
else
{
setIntensityMode(IM_SNAP);
}
});
settings_menu->addAction("Show/hide ion ladder in ID view", [&]() {
setIonLadderVisible(!isIonLadderVisible());
});
settings_menu->addAction("Show/hide automated m/z annotations", [&]() {
setDrawInterestingMZs(!draw_interesting_MZs_);
});
settings_menu->addSeparator();
settings_menu->addAction("Preferences", [&]() {
showCurrentLayerPreferences();
});
context_menu->addMenu(save_menu);
context_menu->addMenu(settings_menu);
// only add to context menu if there is a MS1 map
auto* peak_layer = dynamic_cast<LayerData1DPeak*>(&getCurrentLayer());
if (peak_layer)
{
if (peak_layer->getPeakData()->getMSExperiment().containsScanOfLevel(1))
{
context_menu->addAction("Switch to 2D view", [&]() {
emit showCurrentPeaksAs2D();
});
context_menu->addAction("Switch to 3D view", [&]() {
emit showCurrentPeaksAs3D();
});
}
if (peak_layer->getCurrentSpectrum().containsIMData())
{
context_menu->addAction("Switch to ion mobility view", [&]() {
emit showCurrentPeaksAsIonMobility(peak_layer->getCurrentSpectrum());
});
}
if (peak_layer->isDIAData())
{
auto l = dynamic_cast<const LayerData1DPeak*>(&getCurrentLayer());
context_menu->addAction("Switch to DIA-MS view", [&]() {
emit showCurrentPeaksAsDIA(l->getCurrentSpectrum().getPrecursors()[0], l->getPeakData()->getMSExperiment());
});
}
}
// add external context menu
if (context_add_)
{
context_menu->addSeparator();
context_menu->addMenu(context_add_);
}
}
// evaluate menu
context_menu->exec(mapToGlobal(e->pos()));
// .. and repaint, depending on action taken
if (need_repaint)
{
update_(OPENMS_PRETTY_FUNCTION);
}
e->accept();
}
void Plot1DCanvas::setTextBox(const QString& html)
{
text_box_content_.setHtml(html);
}
void Plot1DCanvas::addUserLabelAnnotation_(const QPoint& screen_position)
{
bool ok;
QString text = QInputDialog::getText(this, "Add label", "Enter text:", QLineEdit::Normal, "", &ok);
if (ok && !text.isEmpty())
{
addLabelAnnotation_(screen_position, text);
}
}
void Plot1DCanvas::addLabelAnnotation_(const QPoint& screen_position, const QString& text)
{
recalculatePercentageFactor_(getCurrentLayerIndex());
PointXYType position = widgetToData(screen_position);
auto item = new Annotation1DTextItem(position, text);
getCurrentLayer().getCurrentAnnotations().push_front(item);
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot1DCanvas::addUserPeakAnnotation_(PeakIndex near_peak)
{
bool ok;
QString text = QInputDialog::getText(this, "Add peak annotation", "Enter text:", QLineEdit::Normal, "", &ok);
if (ok && !text.isEmpty())
{
addPeakAnnotation(near_peak, text, QColor(String(getCurrentLayer().param.getValue("peak_color").toString()).toQString()));
}
}
Annotation1DItem* Plot1DCanvas::addPeakAnnotation(const PeakIndex& peak_index, const QString& text, const QColor& color)
{
auto item = getCurrentLayer().addPeakAnnotation(peak_index, text, color);
update_(OPENMS_PRETTY_FUNCTION);
return item;
}
bool Plot1DCanvas::flippedLayersExist()
{
for (Size i = 0; i < getLayerCount(); ++i)
{
if (getLayer(i).flipped)
{
return true;
}
}
return false;
}
void Plot1DCanvas::updateLayer(Size i)
{
//update nearest peak
selected_peak_.clear();
//update ranges
recalculateRanges_();
resetZoom();
modificationStatus_(i, false);
}
void Plot1DCanvas::zoom_(int x, int y, bool zoom_in)
{
if (!zoom_in)
{
zoomBack_();
}
else
{ // only zoom the non-gravity axis
constexpr PointXYType::CoordinateType zoom_factor = 0.8; // i.e. we crop 20% in total (from left + right, depending on where user clicked)
// we want to zoom into (x,y), which is in pixel units, hence we need to know the relative position of (x,y) in the widget
double rel_pos = gr_.getGravityAxis() == DIM::Y ? (PointXYType::CoordinateType)x / width() : (PointXYType::CoordinateType)(height() - y) / height();
auto new_area = visible_area_.getAreaXY();
if (gr_.getGravityAxis() == DIM::X) new_area.swapDimensions(); // temporarily swap X<>Y if gravity acts on X
auto zoomed = Math::zoomIn(new_area.minX(), new_area.maxX(), zoom_factor, rel_pos);
new_area.setMinX(zoomed.first);
new_area.setMaxX(zoomed.second);
if (gr_.getGravityAxis() == DIM::X) new_area.swapDimensions(); // swap back
if (new_area != visible_area_.getAreaXY())
{
zoomAdd_(visible_area_.cloneWith(new_area));
changeVisibleArea_(*zoom_pos_);
}
}
}
/// Go forward in zoom history
void Plot1DCanvas::zoomForward_()
{
// if at end of zoom level then simply add a new zoom
if (zoom_pos_ == zoom_stack_.end() || (zoom_pos_ + 1) == zoom_stack_.end())
{
const auto a = canvasPixelArea();
zoom_(a.center().getX(), a.center().getY(), true); // calls changeVisibleArea_
return;
}
// goto next zoom level
++zoom_pos_;
changeVisibleArea_(*zoom_pos_);
}
void Plot1DCanvas::translateLeft_(Qt::KeyboardModifiers /*m*/)
{
auto xy = visible_area_.getAreaXY();
// -5% shift in X
xy -= decltype(xy)::PositionType(0.05 * xy.width(), 0);
changeVisibleArea_(xy);
}
void Plot1DCanvas::translateRight_(Qt::KeyboardModifiers /*m*/)
{
auto xy = visible_area_.getAreaXY();
// +5% shift in X
xy += decltype(xy)::PositionType(0.05 * xy.width(), 0);
changeVisibleArea_(xy);
}
void Plot1DCanvas::translateForward_()
{
auto xy = visible_area_.getAreaXY();
// +5% shift in Y
xy += decltype(xy)::PositionType(0, 0.05 * xy.height());
changeVisibleArea_(xy);
}
void Plot1DCanvas::translateBackward_()
{
auto xy = visible_area_.getAreaXY();
// -5% shift in Y
xy -= decltype(xy)::PositionType(0, 0.05 * xy.height());
changeVisibleArea_(xy);
}
/// Returns whether this widget is currently in mirror mode
bool Plot1DCanvas::mirrorModeActive() const
{
return mirror_mode_;
}
/// Sets whether this widget is currently in mirror mode
void Plot1DCanvas::setMirrorModeActive(bool b)
{
mirror_mode_ = b;
qobject_cast<Plot1DWidget*>(spectrum_widget_)->toggleMirrorView(b);
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot1DCanvas::paintGridLines_(QPainter& painter)
{
if (!show_grid_ || !spectrum_widget_)
{
return;
}
QPen p1(QColor(130, 130, 130));
p1.setStyle(Qt::DashLine);
QPen p2(QColor(170, 170, 170));
p2.setStyle(Qt::DotLine);
painter.save();
unsigned int xl, xh, yl, yh; //width/height of the diagram area, x, y coordinates of lo/hi x,y values
xl = 0;
xh = width();
yl = height();
yh = 0;
// drawing of grid lines and associated text
for (Size j = 0; j != spectrum_widget_->xAxis()->gridLines().size(); j++)
{
// style definitions
switch (j)
{
case 0: // style settings for big intervals
painter.setPen(p1);
break;
case 1: // style settings for small intervals
painter.setPen(p2);
break;
default:
std::cout << "empty vertical grid line vector error!" << std::endl;
painter.setPen(QPen(QColor(0, 0, 0)));
break;
}
for (const auto& line : spectrum_widget_->xAxis()->gridLines()[j])
{
int x = static_cast<int>(Math::intervalTransformation(line, spectrum_widget_->xAxis()->getAxisMinimum(), spectrum_widget_->xAxis()->getAxisMaximum(), xl, xh));
painter.drawLine(x, yl, x, yh);
}
}
for (Size j = 0; j != spectrum_widget_->yAxis()->gridLines().size(); j++)
{
// style definitions
switch (j)
{
case 0: // style settings for big intervals
painter.setPen(p1);
break;
case 1: // style settings for small intervals
painter.setPen(p2);
break;
default:
std::cout << "empty vertical grid line vector error!" << std::endl;
painter.setPen(QPen(QColor(0, 0, 0)));
break;
}
for (const auto& line : spectrum_widget_->yAxis()->gridLines()[j])
{
int y = static_cast<int>(Math::intervalTransformation(line, spectrum_widget_->yAxis()->getAxisMinimum(), spectrum_widget_->yAxis()->getAxisMaximum(), yl, yh));
if (!mirror_mode_)
{
painter.drawLine(xl, y, xh, y);
}
else
{
if (!show_alignment_)
{
painter.drawLine(xl, y / 2, xh, y / 2);
painter.drawLine(xl, yl - y / 2, xh, yl - y / 2);
}
else
{
double alignment_shrink_factor = 1.0;
if (height() > 10)
{
alignment_shrink_factor = (double)(height() - 10) / (double)height();
}
painter.drawLine(xl, (int)((double)(y) * alignment_shrink_factor / 2.0), xh, (int)((double)(y) * alignment_shrink_factor / 2.0));
painter.drawLine(xl, yl - (int)((double)(y) * alignment_shrink_factor / 2.0), xh, yl - (int)((double)(y) * alignment_shrink_factor / 2.0));
}
}
}
}
painter.restore();
}
void Plot1DCanvas::performAlignment(Size layer_index_1, Size layer_index_2, const Param& param)
{
alignment_layer_1_ = layer_index_1;
alignment_layer_2_ = layer_index_2;
aligned_peaks_mz_delta_.clear();
aligned_peaks_indices_.clear();
if (layer_index_1 >= getLayerCount() || layer_index_2 >= getLayerCount())
{
return;
}
auto ptr_layer_1 = dynamic_cast<const LayerData1DPeak*>(&getLayer(layer_index_1));
auto ptr_layer_2 = dynamic_cast<const LayerData1DPeak*>(&getLayer(layer_index_2));
if (ptr_layer_1 == nullptr || ptr_layer_2 == nullptr)
{
return;
}
const ExperimentType::SpectrumType& spectrum_1 = ptr_layer_1->getCurrentSpectrum();
const ExperimentType::SpectrumType& spectrum_2 = ptr_layer_2->getCurrentSpectrum();
SpectrumAlignment aligner;
aligner.setParameters(param);
aligner.getSpectrumAlignment(aligned_peaks_indices_, spectrum_1, spectrum_2);
for (Size i = 0; i < aligned_peaks_indices_.size(); ++i)
{
double line_begin_mz = spectrum_1[aligned_peaks_indices_[i].first].getMZ();
double line_end_mz = spectrum_2[aligned_peaks_indices_[i].second].getMZ();
aligned_peaks_mz_delta_.emplace_back(line_begin_mz, line_end_mz);
}
show_alignment_ = true;
update_(OPENMS_PRETTY_FUNCTION);
SpectrumAlignmentScore scorer;
scorer.setParameters(param);
alignment_score_ = scorer(spectrum_1, spectrum_2);
}
void Plot1DCanvas::resetAlignment()
{
aligned_peaks_indices_.clear();
aligned_peaks_mz_delta_.clear();
qobject_cast<Plot1DWidget*>(spectrum_widget_)->resetAlignment();
show_alignment_ = false;
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot1DCanvas::drawAlignment_(QPainter& painter)
{
painter.save();
//draw peak-connecting lines between the two spectra
painter.setPen(Qt::red);
QPoint begin_p, end_p;
if (mirror_mode_)
{
double dummy = 0.0;
for (Size i = 0; i < getAlignmentSize(); ++i)
{
dataToWidget(aligned_peaks_mz_delta_[i].first, dummy, begin_p);
dataToWidget(aligned_peaks_mz_delta_[i].second, dummy, end_p);
painter.drawLine(begin_p.x(), height() / 2 - 5, end_p.x(), height() / 2 + 5);
}
}
else
{
auto ptr_layer_1 = dynamic_cast<const LayerData1DPeak*>(&getLayer(alignment_layer_1_));
if (ptr_layer_1 == nullptr)
{
return;
}
const ExperimentType::SpectrumType& spectrum_1 = ptr_layer_1->getCurrentSpectrum();
recalculatePercentageFactor_(alignment_layer_1_);
for (Size i = 0; i < getAlignmentSize(); ++i)
{
dataToWidget(spectrum_1[aligned_peaks_indices_[i].first].getMZ(), 0, begin_p, false);
dataToWidget(spectrum_1[aligned_peaks_indices_[i].first].getMZ(), spectrum_1[aligned_peaks_indices_[i].first].getIntensity(), end_p, false);
painter.drawLine(begin_p.x(), begin_p.y(), end_p.x(), end_p.y());
}
}
painter.restore();
}
Size Plot1DCanvas::getAlignmentSize()
{
return aligned_peaks_mz_delta_.size();
}
double Plot1DCanvas::getAlignmentScore() const
{
return alignment_score_;
}
void Plot1DCanvas::intensityModeChange_()
{
changeVisibleArea_(visible_area_, false, false); // updates y-axis
ensureAnnotationsWithinDataRange_();
// update axes (e.g. make it Log-scale)
if (spectrum_widget_)
{
spectrum_widget_->updateAxes();
}
update_(OPENMS_PRETTY_FUNCTION);
}
RangeAllType Plot1DCanvas::correctGravityAxisOfVisibleArea_(UnitRange area)
{
// depending on intensity mode, the y-axis either shows
// The maximum range (normal & log)
// or the local maximum (snap mode)
// or [0, 100] (percentage mode)
if (intensity_mode_ == PlotCanvas::IntensityModes::IM_SNAP)
{ // find the range of the current data (as determined by x-axis)
area.clear(getGravityDim().getUnit()); // delete gravity (e.g. intensity), only keep the non-gravity range (e.g. m/z)
for (Size i = 0; i < getLayerCount(); ++i)
{
area.extend(getLayer(i).getRangeForArea(area));
}
auto& intensity = getGravityDim().map(area); // make sure y-axis spans [0, max * TOP_MARGIN]
intensity.setMin(0); // make sure we start at 0
intensity.extend(intensity.getMax() * TOP_MARGIN);
}
else if (intensity_mode_ == PlotCanvas::IntensityModes::IM_PERCENTAGE)
{
auto& intensity = getGravityDim().map(area);
intensity = RangeBase(0, 100 * TOP_MARGIN);
}
else
{ // use y-range of all layers
auto& intensity = getGravityDim().map(area);
intensity = getGravityDim().map(overall_data_range_1d_);
intensity.setMin(0); // make sure we start at 0
}
return area;
}
void Plot1DCanvas::ensureAnnotationsWithinDataRange_()
{
for (Size i = 0; i < getLayerCount(); ++i)
{
recalculatePercentageFactor_(i);
Annotations1DContainer& ann_1d = getLayer(i).getCurrentAnnotations();
for (Annotations1DContainer::Iterator it = ann_1d.begin(); it != ann_1d.end(); ++it)
{
(*it)->ensureWithinDataRange(this, i);
}
}
}
void Plot1DCanvas::flipLayer(Size index)
{
if (index < getLayerCount())
{
getLayer(index).flipped = !getLayer(index).flipped;
}
}
void Plot1DCanvas::activateSpectrum(Size index, bool repaint)
{
// clear selected peak, so we do not accidentally access an invalid index next time when moving the mouse
selected_peak_.clear();
if (getCurrentLayer().hasIndex(index))
{
getCurrentLayer().setCurrentIndex(index);
recalculateRanges_(); // adapt overall_range_(1d)_
changeVisibleArea_(visible_area_, repaint, false); // updates y-axis based on new spectrum
}
}
void Plot1DCanvas::setCurrentLayerPeakPenStyle(Qt::PenStyle ps)
{
// no layers
if (layers_.empty())
{
return;
}
if (peak_penstyle_[getCurrentLayerIndex()] != ps)
{
peak_penstyle_[getCurrentLayerIndex()] = ps;
update_(OPENMS_PRETTY_FUNCTION);
}
}
std::vector<std::pair<Size, Size> > Plot1DCanvas::getAlignedPeaksIndices()
{
return aligned_peaks_indices_;
}
void Plot1DCanvas::setIonLadderVisible(bool show)
{
if (ion_ladder_visible_ != show)
{
ion_ladder_visible_ = show;
update_(OPENMS_PRETTY_FUNCTION);
}
}
void Plot1DCanvas::setDrawInterestingMZs(bool enable)
{
if (draw_interesting_MZs_ != enable)
{
draw_interesting_MZs_ = enable;
update_(OPENMS_PRETTY_FUNCTION);
}
}
bool Plot1DCanvas::isIonLadderVisible() const
{
return ion_ladder_visible_;
}
bool Plot1DCanvas::isDrawInterestingMZs() const
{
return draw_interesting_MZs_;
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/InputFile.cpp | .cpp | 2,677 | 115 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/InputFile.h>
#include <ui_InputFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QCompleter>
#include <QFileSystemModel>
#include <QDragEnterEvent>
#include <QMimeData>
namespace OpenMS
{
InputFile::InputFile(QWidget* parent)
: QWidget(parent),
file_format_filter_(),
ui_(new Ui::InputFileTemplate)
{
ui_->setupUi(this);
QCompleter* completer = new QCompleter(this);
completer->setModel(new QFileSystemModel(completer));
ui_->line_edit->setCompleter(completer);
connect(ui_->browse_button, SIGNAL(clicked()), this, SLOT(showFileDialog()));
}
InputFile::~InputFile()
{
delete ui_;
}
void InputFile::dragEnterEvent(QDragEnterEvent* e)
{
// file dropped from a window manager come as single URL
if (e->mimeData()->urls().size() == 1)
{
e->acceptProposedAction();
}
}
void InputFile::dropEvent(QDropEvent* e)
{
QStringList files;
for (const QUrl& url : e->mimeData()->urls())
{
setFilename(url.toLocalFile());
break;
}
}
void InputFile::dragMoveEvent(QDragMoveEvent* p_event)
{
// TODO allow filtering?
//if (!p_event->mimeData()->hasFormat(MY_MIMETYPE))
//{
// p_event->ignore();
// return;
//}
p_event->accept();
}
void InputFile::setFilename(const QString& filename)
{
ui_->line_edit->setText(filename);
emit updatedFile(filename);
setCWD(File::path(filename).toQString());
}
QString InputFile::getFilename() const
{
return ui_->line_edit->text();
}
void InputFile::setFileFormatFilter(const QString& fff)
{
file_format_filter_ = fff;
}
const QString& InputFile::getCWD() const
{
return cwd_;
}
void InputFile::setCWD(const QString& cwd, bool force)
{
if (force || cwd_.isEmpty())
{
cwd_ = cwd;
emit updatedCWD(cwd_);
}
}
void InputFile::showFileDialog()
{
QFileInfo fi(getFilename()); // get path from current file as starting directory for selection
QString file_name = QFileDialog::getOpenFileName(this, tr("Specify input file"), cwd_, file_format_filter_);
if (!file_name.isEmpty())
{
setFilename(file_name);
}
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Painter1DBase.cpp | .cpp | 15,865 | 445 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerData1DChrom.h>
#include <OpenMS/VISUAL/LayerData1DIonMobility.h>
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/Painter1DBase.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DItem.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DDistanceItem.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotations1DContainer.h>
#include <OpenMS/VISUAL/Plot1DCanvas.h>
// preprocessing and filtering for automated m/z annotations
#include <OpenMS/PROCESSING/DEISOTOPING/Deisotoper.h>
#include <OpenMS/PROCESSING/FILTERING/ThresholdMower.h>
#include <OpenMS/PROCESSING/FILTERING/NLargest.h>
#include <OpenMS/PROCESSING/FILTERING/WindowMower.h>
#include <QPainter>
#include <QPen>
using namespace std;
namespace OpenMS
{
void Painter1DBase::drawAnnotations_(const LayerData1DBase* layer, QPainter& painter, Plot1DCanvas* canvas) const
{
const QColor col {QColor(String(layer->param.getValue("annotation_color").toString()).toQString())};
// 0: default pen; 1: selected pen
const QPen pen[2] = {col, col.lighter()};
for (const auto& c : layer->getCurrentAnnotations())
{
painter.setPen(pen[c->isSelected()]);
c->draw(canvas, painter, layer->flipped);
}
}
// ###############################
// ###### 1D Peak
// ###############################
Painter1DPeak::Painter1DPeak(const LayerData1DPeak* parent) : layer_(parent)
{
}
void Painter1DPeak::paint(QPainter* painter, Plot1DCanvas* canvas, int layer_index)
{
if (!layer_->visible)
{
return;
}
const auto& spectrum = layer_->getCurrentSpectrum();
// get default peak color
QPen pen(QColor(String(layer_->param.getValue("peak_color").toString()).toQString()), 1);
pen.setStyle(canvas->peak_penstyle_[layer_index]);
painter->setPen(pen);
// draw dashed elongations for pairs of peaks annotated with a distance
const QColor color = String(canvas->param_.getValue("highlighted_peak_color").toString()).toQString();
for (auto& it : layer_->getCurrentAnnotations())
{
const auto distance_item = dynamic_cast<Annotation1DDistanceItem*>(it);
if (!distance_item) continue;
auto draw_line_ = [&](const PointXYType& p) {
QPoint from;
canvas->dataToWidget(p, from, layer_->flipped);
from = canvas->getGravitator().gravitateZero(from);
QPoint to = canvas->getGravitator().gravitateMax(from, canvas->canvasPixelArea());
drawDashedLine(from, to, painter, color);
};
draw_line_(distance_item->getStartPoint());
draw_line_(distance_item->getEndPoint());
}
const auto v_begin = spectrum.MZBegin(canvas->visible_area_.getAreaUnit().getMinMZ());
const auto v_end = spectrum.MZEnd(canvas->visible_area_.getAreaUnit().getMaxMZ());
QPoint begin, end;
switch (canvas->draw_modes_[layer_index])
{
case Plot1DCanvas::DrawModes::DM_PEAKS:
{
//---------------------DRAWING PEAKS---------------------
for (auto it = v_begin; it != v_end; ++it)
{
if (!layer_->filters.passes(spectrum, it - spectrum.begin())) continue;
// use peak colors stored in the layer, if available
if (layer_->peak_colors_1d.size() == spectrum.size())
{
// find correct peak index
const Size peak_index = std::distance(spectrum.cbegin(), it);
pen.setColor(layer_->peak_colors_1d[peak_index]);
painter->setPen(pen);
}
else if (!layer_->peak_colors_1d.empty())
{ // Warn if non-empty peak color array present but size doesn't match number of peaks
// This indicates a bug but we gracefully just issue a warning
OPENMS_LOG_ERROR << "Peak color array size (" << layer_->peak_colors_1d.size() << ") doesn't match number of peaks (" << spectrum.size() << ") in spectrum." << endl;
}
// draw stick
auto p_xy = canvas->getMapper().map(*it);
canvas->dataToWidget(p_xy, end, layer_->flipped);
canvas->dataToWidget(canvas->getGravitator().gravitateZero(p_xy), begin, layer_->flipped);
painter->drawLine(begin, end);
}
break;
}
case Plot1DCanvas::DrawModes::DM_CONNECTEDLINES:
{
//---------------------DRAWING CONNECTED LINES---------------------
QPainterPath path;
// connect peaks in visible area;
// clipping on left and right side
auto v_begin_cl = v_begin;
if (v_begin_cl != spectrum.cbegin() && v_begin_cl != spectrum.cend())
--v_begin_cl;
auto v_end_cl = v_end;
if (v_end_cl != spectrum.cbegin() && v_end_cl != spectrum.cend())
++v_end_cl;
bool first_point = true;
for (auto it = v_begin_cl; it != v_end_cl; ++it)
{
if (!layer_->filters.passes(spectrum, it - spectrum.begin())) continue;
canvas->dataToWidget(canvas->getMapper().map(*it), begin, layer_->flipped);
// connect lines
if (first_point)
{
path.moveTo(begin);
first_point = false;
}
else
{
path.lineTo(begin);
}
}
painter->drawPath(path);
break;
}
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
// annotate interesting m/z's
if (canvas->draw_interesting_MZs_)
{
drawMZAtInterestingPeaks_(*painter, canvas, v_begin, v_end);
}
// draw all annotation items
drawAnnotations_(layer_, *painter, canvas);
}
void Painter1DPeak::drawMZAtInterestingPeaks_(QPainter& painter, Plot1DCanvas* canvas, MSSpectrum::ConstIterator v_begin, MSSpectrum::ConstIterator v_end) const
{
if (v_begin == v_end)
{
return;
}
// find interesting peaks
// copy visible peaks into spec
MSSpectrum spec;
for (auto it(v_begin); it != v_end; ++it)
{
spec.push_back(*it);
}
// calculate distance between first and last peak
--v_end;
double visible_range = v_end->getMZ() - v_begin->getMZ();
// remove 0 intensities
ThresholdMower threshold_mower_filter;
threshold_mower_filter.filterPeakSpectrum(spec);
// deisotope so we don't consider higher isotopic peaks
Deisotoper::deisotopeAndSingleCharge(spec,
100, // tolerance
true, // ppm
1, 6, // min / max charge
false, // keep only deisotoped
3, 10, // min / max isopeaks
false, // don't convert fragment m/z to mono-charge
true); // annotate charge in integer data array
// filter for local high-intensity peaks
WindowMower window_mower_filter;
Param filter_param = window_mower_filter.getParameters();
double window_size = visible_range / 10.0;
filter_param.setValue("windowsize", window_size, "The size of the sliding window along the m/z axis.");
filter_param.setValue("peakcount", 2, "The number of peaks that should be kept.");
filter_param.setValue("movetype", "slide", "Whether sliding window (one peak steps) or jumping window (window size steps) should be used.");
window_mower_filter.setParameters(filter_param);
window_mower_filter.filterPeakSpectrum(spec);
// maximum number of annotated m/z's in visible area
NLargest(10).filterPeakSpectrum(spec);
spec.sortByPosition(); // n-largest changes order
for (size_t i = 0; i < spec.size(); ++i)
{
auto mz(spec[i].getMZ());
auto intensity(spec[i].getIntensity());
QString label = String::number(mz, 4).toQString();
if (!spec.getIntegerDataArrays().empty() && spec.getIntegerDataArrays()[0].size() == spec.size())
{
int charge = spec.getIntegerDataArrays()[0][i];
// TODO: handle negative mode
// here we explicitly also annotate singly charged ions to distinguish them from unknown charge (0)
if (charge != 0)
{
label += charge == 1 ? "<sup>+</sup>" : "<sup>" + QString::number(charge) + "+</sup>";
}
}
Annotation1DPeakItem item(Peak1D{mz, intensity}, label, Qt::darkGray);
item.setSelected(false);
item.draw(canvas, painter, layer_->flipped);
}
}
// ###############################
// ###### 1D Chrom
// ###############################
Painter1DChrom::Painter1DChrom(const LayerData1DChrom* parent) : layer_(parent)
{
}
void Painter1DChrom::paint(QPainter* painter, Plot1DCanvas* canvas, int layer_index)
{
if (!layer_->visible)
{
return;
}
const auto& data = layer_->getCurrentChrom();
// get default peak color
QPen pen(QColor(String(layer_->param.getValue("peak_color").toString()).toQString()), 1);
pen.setStyle(canvas->peak_penstyle_[layer_index]);
painter->setPen(pen);
const auto v_begin = data.RTBegin(canvas->visible_area_.getAreaUnit().getMinRT());
const auto v_end = data.RTEnd(canvas->visible_area_.getAreaUnit().getMaxRT());
QPoint begin, end;
switch (canvas->draw_modes_[layer_index])
{
case Plot1DCanvas::DrawModes::DM_PEAKS: {
//---------------------DRAWING PEAKS---------------------
for (auto it = v_begin; it != v_end; ++it)
{
if (!layer_->filters.passes(data, it - data.begin()))
continue;
// use peak colors stored in the layer, if available
if (layer_->peak_colors_1d.size() == data.size())
{
// find correct peak index
const Size peak_index = std::distance(data.begin(), it);
pen.setColor(layer_->peak_colors_1d[peak_index]);
painter->setPen(pen);
}
else if (!layer_->peak_colors_1d.empty())
{ // Warn if non-empty peak color array present but size doesn't match number of peaks
// This indicates a bug but we gracefully just issue a warning
OPENMS_LOG_ERROR << "Peak color array size (" << layer_->peak_colors_1d.size() << ") doesn't match number of peaks (" << data.size() << ") in chromatogram." << endl;
}
// draw stick
auto p_xy = canvas->getMapper().map(*it);
canvas->dataToWidget(p_xy, end, layer_->flipped);
canvas->dataToWidget(canvas->getGravitator().gravitateZero(p_xy), begin, layer_->flipped);
painter->drawLine(begin, end);
}
break;
}
case Plot1DCanvas::DrawModes::DM_CONNECTEDLINES: {
//---------------------DRAWING CONNECTED LINES---------------------
QPainterPath path;
// connect peaks in visible area;
// clipping on left and right side
auto v_begin_cl = v_begin;
if (v_begin_cl != data.cbegin() && v_begin_cl != data.cend())
--v_begin_cl;
auto v_end_cl = v_end;
if (v_end_cl != data.cbegin() && v_end_cl != data.cend())
++v_end_cl;
bool first_point = true;
for (auto it = v_begin_cl; it != v_end_cl; ++it)
{
if (!layer_->filters.passes(data, it - data.begin())) continue;
canvas->dataToWidget(canvas->getMapper().map(*it), begin, layer_->flipped);
// connect lines
if (first_point)
{
path.moveTo(begin);
first_point = false;
}
else
{
path.lineTo(begin);
}
}
painter->drawPath(path);
break;
}
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
// draw all annotation items
drawAnnotations_(layer_, *painter, canvas);
}
// ###############################
// ###### 1D Mobilogram
// ###############################
Painter1DIonMobility::Painter1DIonMobility(const LayerData1DIonMobility* parent) : layer_(parent)
{
}
void Painter1DIonMobility::paint(QPainter* painter, Plot1DCanvas* canvas, int layer_index)
{
if (!layer_->visible)
{
return;
}
const auto& data = layer_->getCurrentMobilogram();
// get default peak color
QPen pen(QColor(String(layer_->param.getValue("peak_color").toString()).toQString()), 1);
pen.setStyle(canvas->peak_penstyle_[layer_index]);
painter->setPen(pen);
const auto v_begin = data.MBBegin(canvas->visible_area_.getAreaUnit().getMinMobility());
const auto v_end = data.MBEnd(canvas->visible_area_.getAreaUnit().getMaxMobility());
QPoint begin, end;
switch (canvas->draw_modes_[layer_index])
{
case Plot1DCanvas::DrawModes::DM_PEAKS: {
//---------------------DRAWING PEAKS---------------------
for (auto it = v_begin; it != v_end; ++it)
{
//if (!layer_->filters.passes(data, it - data.begin()))
// continue;
// use peak colors stored in the layer, if available
if (layer_->peak_colors_1d.size() == data.size())
{
// find correct peak index
const Size peak_index = std::distance(data.begin(), it);
pen.setColor(layer_->peak_colors_1d[peak_index]);
painter->setPen(pen);
}
else if (!layer_->peak_colors_1d.empty())
{ // Warn if non-empty peak color array present but size doesn't match number of peaks
// This indicates a bug but we gracefully just issue a warning
OPENMS_LOG_ERROR << "Peak color array size (" << layer_->peak_colors_1d.size() << ") doesn't match number of peaks (" << data.size() << ") in chromatogram." << endl;
}
// draw stick
auto p_xy = canvas->getMapper().map(*it);
canvas->dataToWidget(p_xy, end, layer_->flipped);
canvas->dataToWidget(canvas->getGravitator().gravitateZero(p_xy), begin, layer_->flipped);
painter->drawLine(begin, end);
}
break;
}
case Plot1DCanvas::DrawModes::DM_CONNECTEDLINES: {
//---------------------DRAWING CONNECTED LINES---------------------
QPainterPath path;
// connect peaks in visible area;
// clipping on left and right side
auto v_begin_cl = v_begin;
if (v_begin_cl != data.cbegin() && v_begin_cl != data.cend())
--v_begin_cl;
auto v_end_cl = v_end;
if (v_end_cl != data.cbegin() && v_end_cl != data.cend())
++v_end_cl;
bool first_point = true;
for (auto it = v_begin_cl; it != v_end_cl; ++it)
{
if (!layer_->filters.passes(data, it - data.begin())) continue;
canvas->dataToWidget(canvas->getMapper().map(*it), begin, layer_->flipped);
// connect lines
if (first_point)
{
path.moveTo(begin);
first_point = false;
}
else
{
path.lineTo(begin);
}
}
painter->drawPath(path);
break;
}
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
// draw all annotation items
drawAnnotations_(layer_, *painter, canvas);
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASMergerVertex.cpp | .cpp | 4,300 | 134 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASMergerVertex.h>
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <iostream>
namespace OpenMS
{
TOPPASMergerVertex::TOPPASMergerVertex(bool round_based) :
round_based_mode_(round_based)
{
}
std::unique_ptr<TOPPASVertex> TOPPASMergerVertex::clone() const
{
return std::make_unique<TOPPASMergerVertex>(*this);
}
String TOPPASMergerVertex::getName() const
{
return "MergerVertex";
}
void TOPPASMergerVertex::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
TOPPASVertex::paint(painter, option, widget);
QString text = round_based_mode_ ? "Merge" : "Collect";
QRectF text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), (int)(text_boundings.height() / 4.0), text);
if (round_total_ != -1) // draw round number
{
text = QString::number(round_counter_) + " / " + QString::number(round_total_);
text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), 31, text);
}
}
QRectF TOPPASMergerVertex::boundingRect() const
{
return QRectF(-41, -41, 82, 82);
}
bool TOPPASMergerVertex::roundBasedMode() const
{
return round_based_mode_;
}
void TOPPASMergerVertex::markUnreachable()
{
//only mark as unreachable if all inputs are unreachable. otherwise the dead inputs will just be ignored.
bool some_input_reachable_ = false;
for (ConstEdgeIterator it = inEdgesBegin(); it != inEdgesEnd(); ++it)
{
TOPPASVertex* tv = (*it)->getSourceVertex();
if (tv->isReachable())
{
some_input_reachable_ = true;
break;
}
}
if (!some_input_reachable_)
{
TOPPASVertex::markUnreachable();
}
}
void TOPPASMergerVertex::run()
{
//check if everything ready
if (!isUpstreamFinished())
{
return;
}
RoundPackages pkg;
String error_msg("");
bool success = buildRoundPackages(pkg, error_msg);
if (!success)
{
std::cerr << "Could not retrieve input files from upstream nodes...\n";
emit mergeFailed((String("Merger #") + this->getTopoNr() + " failed. " + error_msg).toQString());
return;
}
/// update round status
Size input_rounds = pkg.size();
round_total_ = (round_based_mode_ ? (int) input_rounds : 1); // for round based: take number of rounds from previous tool(s) - should all be equal
round_counter_ = 0; // once round_counter_ reaches round_total_, we are done
// clear output file list
output_files_.clear();
output_files_.resize(round_total_); // #rounds
// Do the virtual merging (nothing more than reorganizing filenames)
for (Size round = 0; round < input_rounds; ++round)
{
QStringList files;
// warning: ite->first (i.e. target-in param could be -1,-2,... etc to cover all incoming edges (they all have -1 theoretically - see buildRoundPackages())
for (RoundPackageConstIt ite = pkg[round].begin();
ite != pkg[round].end(); ++ite)
{
files.append(ite->second.filenames.get()); // concat filenames from all incoming edges
}
Size round_index = (round_based_mode_ ? round : 0);
output_files_[round_index][-1].filenames.append(files); // concat over all rounds (if required)
}
round_counter_ = round_total_;
finished_ = true;
// call all children, proceed in pipeline
for (ConstEdgeIterator it = outEdgesBegin(); it != outEdgesEnd(); ++it)
{
TOPPASVertex* tv = (*it)->getTargetVertex();
debugOut_(String("Starting child ") + tv->getTopoNr());
tv->run();
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/PlotWidget.cpp | .cpp | 10,186 | 310 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/PlotWidget.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/DIALOGS/HistogramDialog.h>
#include <OpenMS/VISUAL/DIALOGS/LayerStatisticsDialog.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <QCloseEvent>
#include <QtCore/QMimeData>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QScrollBar>
#include <QScrollBar>
using namespace std;
namespace OpenMS
{
using namespace Math;
const char PlotWidget::RT_AXIS_TITLE[] = "Time [s]";
const char PlotWidget::MZ_AXIS_TITLE[] = "m/z";
const char PlotWidget::INTENSITY_AXIS_TITLE[] = "Intensity";
const char PlotWidget::IM_MS_AXIS_TITLE[] = "Ion Mobility [ms]";
const char PlotWidget::IM_ONEKZERO_AXIS_TITLE[] = "Ion Mobility [1/K0]";
PlotWidget::PlotWidget(const Param& /*preferences*/, QWidget* parent) :
QWidget(parent),
canvas_(nullptr)
{
setAttribute(Qt::WA_DeleteOnClose);
grid_ = new QGridLayout(this);
grid_->setSpacing(0);
grid_->setContentsMargins(1, 1, 1, 1);
// axes
y_axis_ = new AxisWidget(AxisPainter::LEFT, "", this);
x_axis_ = new AxisWidget(AxisPainter::BOTTOM, "", this);
// scrollbars
x_scrollbar_ = new QScrollBar(Qt::Horizontal, this); // left is small value, right is high value
y_scrollbar_ = new QScrollBar(Qt::Vertical, this); // top is low value, bottom is high value (however, our coordinate system is inverse for the y-Axis!)
// We achieve the desired behavior by setting negative min/max ranges within the scrollbar when updateVScrollbar() is called.
// Thus, y_scrollbar_->valueChanged() will report negative values (which you need to multiply by -1 to get the correct value).
// Remember this when implementing verticalScrollBarChange() in your canvas class (currently only used in Plot2DCanvas)
// Do NOT use the build-in functions to invert a scrollbar, since implementation can be incomplete depending on style and platform
// y_scrollbar_->setInvertedAppearance(true);
// y_scrollbar_->setInvertedControls(true);
setMinimumSize(250, 250); //Canvas (200) + AxisWidget (30) + ScrollBar (20)
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
setAcceptDrops(true);
}
void PlotWidget::setCanvas_(PlotCanvas* canvas, UInt row, UInt col)
{
canvas_ = canvas;
setFocusProxy(canvas_);
grid_->addWidget(canvas_, row, col);
grid_->addWidget(y_axis_, row, col - 1);
grid_->addWidget(x_axis_, row + 1, col);
connect(canvas_, &PlotCanvas::visibleAreaChanged, this, &PlotWidget::updateAxes);
connect(canvas_, &PlotCanvas::recalculateAxes, this, &PlotWidget::updateAxes);
connect(canvas_, &PlotCanvas::changeLegendVisibility, this, &PlotWidget::changeLegendVisibility);
grid_->addWidget(y_scrollbar_, row, col - 2);
grid_->addWidget(x_scrollbar_, row + 2, col);
x_scrollbar_->hide();
y_scrollbar_->hide();
connect(canvas_, &PlotCanvas::updateHScrollbar, this, &PlotWidget::updateHScrollbar);
connect(canvas_, &PlotCanvas::updateVScrollbar, this, &PlotWidget::updateVScrollbar);
connect(x_scrollbar_, &QScrollBar::valueChanged, canvas_, &PlotCanvas::horizontalScrollBarChange);
connect(y_scrollbar_, &QScrollBar::valueChanged, canvas_, &PlotCanvas::verticalScrollBarChange);
connect(canvas_, &PlotCanvas::sendStatusMessage, this, &PlotWidget::sendStatusMessage);
connect(canvas_, &PlotCanvas::sendCursorStatus, this, &PlotWidget::sendCursorStatus);
canvas_->setPlotWidget(this);
}
PlotWidget::~PlotWidget() = default;
Int PlotWidget::getActionMode() const
{
return canvas_->getActionMode();
}
void PlotWidget::setIntensityMode(PlotCanvas::IntensityModes mode)
{
if (canvas_->getIntensityMode() != mode)
{
canvas_->setIntensityMode(mode);
}
}
void PlotWidget::showStatistics()
{
LayerStatisticsDialog lsd(this, canvas_->getCurrentLayer().getStats());
lsd.exec();
}
void PlotWidget::showIntensityDistribution(const Histogram<>& dist)
{
HistogramDialog dw(dist);
dw.setLegend(PlotWidget::INTENSITY_AXIS_TITLE);
dw.setLogMode(true);
if (dw.exec() == QDialog::Accepted)
{
DataFilters filters;
if (dw.getLeftSplitter() > dist.minBound())
{
DataFilters::DataFilter filter;
filter.value = dw.getLeftSplitter();
filter.field = DataFilters::INTENSITY;
filter.op = DataFilters::GREATER_EQUAL;
filters.add(filter);
}
if (dw.getRightSplitter() < dist.maxBound())
{
DataFilters::DataFilter filter;
filter.value = dw.getRightSplitter();
filter.field = DataFilters::INTENSITY;
filter.op = DataFilters::LESS_EQUAL;
filters.add(filter);
}
canvas_->setFilters(filters);
}
}
void PlotWidget::showMetaDistribution(const String& name, const Histogram<>& dist)
{
HistogramDialog dw(dist);
dw.setLegend(name);
if (dw.exec() == QDialog::Accepted)
{
DataFilters filters;
if (dw.getLeftSplitter() > dist.minBound())
{
DataFilters::DataFilter filter;
filter.value = dw.getLeftSplitter();
filter.field = DataFilters::META_DATA;
filter.meta_name = name;
filter.op = DataFilters::GREATER_EQUAL;
filter.value_is_numerical = true;
filters.add(filter);
}
if (dw.getRightSplitter() < dist.maxBound())
{
DataFilters::DataFilter filter;
filter.value = dw.getRightSplitter();
filter.field = DataFilters::META_DATA;
filter.meta_name = name;
filter.op = DataFilters::LESS_EQUAL;
filter.value_is_numerical = true;
filters.add(filter);
}
canvas_->setFilters(filters);
}
}
void PlotWidget::showLegend(bool show)
{
y_axis_->showLegend(show);
x_axis_->showLegend(show);
update();
}
void PlotWidget::saveAsImage()
{
QString file_name = QFileDialog::getSaveFileName(this, "Save File", "", "Images (*.bmp *.png *.jpg *.gif)");
QString old_stylesheet = this->styleSheet();
// Make the whole widget (including the usually natively styled AxisWidgets) white
this->setStyleSheet("background: white");
bool x_visible = x_scrollbar_->isVisible();
bool y_visible = y_scrollbar_->isVisible();
x_scrollbar_->hide();
y_scrollbar_->hide();
QPixmap pixmap = this->grab();
x_scrollbar_->setVisible(x_visible);
y_scrollbar_->setVisible(y_visible);
pixmap.save(file_name);
this->setStyleSheet(old_stylesheet);
}
void PlotWidget::updateAxes()
{
recalculateAxes_();
}
void PlotWidget::intensityModeChange_()
{
}
bool PlotWidget::isLegendShown() const
{
// Both are shown or hidden, so we simply return the state of the x-axis
return x_axis_->isLegendShown();
}
void PlotWidget::hideAxes()
{
y_axis_->hide();
x_axis_->hide();
}
void updateScrollbar(QScrollBar* scroll, float f_min, float disp_min, float disp_max, float f_max)
{
if ((disp_min == f_min && disp_max == f_max) || (disp_min < f_min && disp_max > f_max))
{
scroll->hide();
}
else
{
// block signals as this causes repainting due to rounding (QScrollBar works with int ...)
auto local_min = min(f_min, disp_min);
auto local_max = max(f_max, disp_max);
auto vis_span = disp_max - disp_min;
scroll->blockSignals(true);
//scroll->setMinimum(static_cast<int>(local_min));
//scroll->setMaximum(static_cast<int>(std::ceil(local_max - disp_max + disp_min)));
scroll->setRange(int(local_min), int(std::ceil(local_max - vis_span)));
scroll->setValue(int(disp_min)); // emits valueChanged, which will call this function here unless signal is blocked
scroll->setPageStep(vis_span);
scroll->blockSignals(false);
scroll->show();
}
}
void PlotWidget::updateHScrollbar(float f_min, float disp_min, float disp_max, float f_max)
{
updateScrollbar(x_scrollbar_, f_min, disp_min, disp_max, f_max);
}
void PlotWidget::updateVScrollbar(float f_min, float disp_min, float disp_max, float f_max)
{
updateScrollbar(y_scrollbar_, f_min, disp_min, disp_max, f_max);
}
void PlotWidget::changeLegendVisibility()
{
showLegend(!isLegendShown());
}
void PlotWidget::closeEvent(QCloseEvent* e)
{
for (UInt l = 0; l < canvas()->getLayerCount(); ++l)
{
//modified => ask if it should be saved
const LayerDataBase& layer = canvas()->getLayer(l);
if (layer.modified)
{
QMessageBox::StandardButton result = QMessageBox::question(this, "Save?", (String("Do you want to save your changes to layer '") + layer.getName() + "'?").toQString(), QMessageBox::Ok | QMessageBox::Discard);
if (result == QMessageBox::Ok)
{
canvas()->activateLayer(l);
canvas()->saveCurrentLayer(false);
}
}
}
e->accept();
}
void PlotWidget::dragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
void PlotWidget::dragMoveEvent(QDragMoveEvent* event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
void PlotWidget::dropEvent(QDropEvent* event)
{
emit dropReceived(event->mimeData(), dynamic_cast<QWidget*>(event->source()), this->getWindowId());
event->acceptProposedAction();
}
void PlotWidget::paintEvent(QPaintEvent * /*event*/)
{
QStyleOption opt;
opt.initFrom(this);
QPainter p(this);
// apply style options and draw the widget using current stylesheets
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerDataIdent.cpp | .cpp | 1,802 | 56 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerDataIdent.h>
#include <OpenMS/KERNEL/DimMapper.h>
#include <OpenMS/VISUAL/Painter2DBase.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
using namespace std;
namespace OpenMS
{
std::unique_ptr<Painter2DBase> LayerDataIdent::getPainter2D() const
{
return make_unique<Painter2DIdent>(this);
}
std::unique_ptr<LayerStoreData> LayerDataIdent::storeVisibleData(const RangeAllType& visible_range, const DataFilters& layer_filters) const
{
auto ret = make_unique<LayerStoreDataIdentVisible>();
ret->storeVisibleIdent(peptides_, visible_range, layer_filters);
return ret;
}
std::unique_ptr<LayerStoreData> LayerDataIdent::storeFullData() const
{
auto ret = make_unique<LayerStoreDataIdentAll>();
ret->storeFullIdent(peptides_);
return ret;
}
LayerDataDefs::ProjectionData LayerDataIdent::getProjection(const DIM_UNIT /*unit_x*/, const DIM_UNIT /*unit_y*/, const RangeAllType& /*area*/) const
{ // currently only a stub
ProjectionData proj;
return proj;
}
PointXYType LayerDataIdent::peakIndexToXY(const PeakIndex& /*peak*/, const DimMapper<2>& /*mapper*/) const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
std::unique_ptr<LayerStatistics> LayerDataIdent::getStats() const
{
return make_unique<LayerStatisticsIdent>(peptides_);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerData1DPeak.cpp | .cpp | 9,865 | 307 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/Painter1DBase.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
#include <QMenu>
using namespace std;
namespace OpenMS
{
std::unique_ptr<LayerStoreData> LayerData1DPeak::storeVisibleData(const RangeAllType& visible_range, const DataFilters& layer_filters) const
{
auto ret = std::make_unique<LayerStoreDataPeakMapVisible>();
ret->storeVisibleSpectrum(getCurrentSpectrum(), visible_range, layer_filters);
return ret;
}
std::unique_ptr<LayerStoreData> LayerData1DPeak::storeFullData() const
{
return LayerDataPeak::storeFullData(); // just forward
}
QMenu* LayerData1DPeak::getContextMenuAnnotation(Annotation1DItem* annot_item, bool& need_repaint)
{
auto* context_menu = new QMenu("Peak1D", nullptr);
context_menu->addAction("Edit", [annot_item, &need_repaint, this]() { // this capture is tricky! Copy 'annot_item' since its a local variable and will be out of scope when the menu is evaluated!
annot_item->editText();
synchronizePeakAnnotations();
need_repaint = true;
});
context_menu->addAction("Delete", [annot_item, &need_repaint, this]() { // this capture is tricky! Copy 'annot_item' since its a local variable and will be out of scope when the menu is evaluated!
vector<Annotation1DItem*> as;
as.push_back(annot_item);
removePeakAnnotationsFromPeptideHit(as);
getCurrentAnnotations().removeSelectedItems();
need_repaint = true;
});
return context_menu;
}
PeakIndex LayerData1DPeak::findClosestDataPoint(const RangeAllType& area) const
{
Peak1D peak_lt(area.getMinMZ(), area.getMinIntensity()), peak_rb(area.getMaxMZ(), area.getMaxIntensity());
// reference to the current data
const auto& spectrum = getCurrentSpectrum();
const Size spectrum_index = getCurrentIndex();
// get iterator on first peak with lower position than interval_start
auto left_it = lower_bound(spectrum.begin(), spectrum.end(), peak_lt, PeakType::PositionLess());
// get iterator on first peak with higher position than interval_end
auto right_it = lower_bound(left_it, spectrum.end(), peak_rb, PeakType::PositionLess());
if (left_it == right_it) // both are equal => no peak falls into this interval
{
return PeakIndex();
}
if (left_it == right_it - 1)
{
return PeakIndex(spectrum_index, left_it - spectrum.begin());
}
auto nearest_it = left_it;
const auto center_intensity = (peak_lt.getIntensity() + peak_rb.getIntensity()) * 0.5;
for (auto it = left_it; it != right_it; ++it)
{
if (abs(center_intensity - it->getIntensity()) < abs(center_intensity - nearest_it->getIntensity()))
{
nearest_it = it;
}
}
return PeakIndex(spectrum_index, nearest_it - spectrum.begin());
}
std::unique_ptr<Painter1DBase> LayerData1DPeak::getPainter1D() const
{
return make_unique<Painter1DPeak>(this);
}
Annotation1DItem* LayerData1DPeak::addPeakAnnotation(const PeakIndex& peak_index, const QString& text, const QColor& color)
{
auto peak = getCurrentSpectrum()[peak_index.peak];
auto* item = new Annotation1DPeakItem<decltype(peak)>(peak, text, color);
item->setSelected(false);
getCurrentAnnotations().push_front(item);
return item;
}
void LayerData1DPeak::synchronizePeakAnnotations()
{
#ifdef DEBUG_IDENTIFICATION_VIEW
std::cout << "synchronizePeakAnnotations." << std::endl;
#endif
// Return if no valid peak layer attached
if (getPeakData() == nullptr
|| getPeakData()->getMSExperiment().empty()
|| type != LayerDataBase::DT_PEAK)
{
return;
}
// no ID selected
if (peptide_id_index == -1 || peptide_hit_index == -1)
{
return;
}
// get mutable access to the spectrum
MSSpectrum& spectrum = getPeakDataMuteable()->getMSExperiment().getSpectrum(current_idx_);
int ms_level = spectrum.getMSLevel();
if (ms_level != 2)
return;
// store user fragment annotations
PeptideIdentificationList& pep_ids = getPeakDataMuteable()->getPeptideIdentifications();
vector<ProteinIdentification>& prot_ids = getPeakDataMuteable()->getProteinIdentifications();
if (!pep_ids.empty())
{
#ifdef DEBUG_IDENTIFICATION_VIEW
std::cout << "PeptideIdentifications found in the current spectrum." << std::endl;
#endif
vector<PeptideHit>& hits = pep_ids[peptide_id_index].getHits();
if (!hits.empty())
{
PeptideHit& hit = hits[peptide_hit_index];
updatePeptideHitAnnotations_(hit);
}
else
{ // no hits? add empty hit
PeptideHit hit;
updatePeptideHitAnnotations_(hit);
hits.push_back(hit);
}
}
else
{
std::cout << "No PeptideIdentifications found in the current spectrum." << std::endl;
// copy user annotations to fragment annotation vector
const Annotations1DContainer& las = getAnnotations(current_idx_);
// no annotations so we don't need to synchronize
bool has_peak_annotation(false);
for (auto& a : las)
{
// only store peak annotations
auto pa = dynamic_cast<Annotation1DPeakItem<Peak1D>*>(a);
if (pa != nullptr)
{
has_peak_annotation = true;
break;
}
}
if (has_peak_annotation == false)
{
return;
}
PeptideIdentification pep_id;
pep_id.setIdentifier("Unknown");
// create a dummy ProteinIdentification for all ID-less PeakAnnotations
if (prot_ids.empty() || prot_ids.back().getIdentifier() != String("Unknown"))
{
ProteinIdentification prot_id;
prot_id.setIdentifier("Unknown");
prot_ids.push_back(prot_id);
}
PeptideHit hit;
if (spectrum.getPrecursors().empty() == false)
{
pep_id.setMZ(spectrum.getPrecursors()[0].getMZ());
hit.setCharge(spectrum.getPrecursors()[0].getCharge());
}
pep_id.setRT(spectrum.getRT());
updatePeptideHitAnnotations_(hit);
std::vector<PeptideHit> hits;
hits.push_back(hit);
pep_id.setHits(hits);
pep_ids.push_back(pep_id);
}
}
void LayerData1DPeak::removePeakAnnotationsFromPeptideHit(const std::vector<Annotation1DItem*>& selected_annotations)
{
// Return if no valid peak layer attached
if (getPeakData() == nullptr || getPeakData()->getMSExperiment().empty() || type != LayerDataBase::DT_PEAK)
{
return;
}
// no ID selected
if (peptide_id_index == -1 || peptide_hit_index == -1)
{
return;
}
// get mutable access to the spectrum
MSSpectrum& spectrum = getPeakDataMuteable()->getMSExperiment().getSpectrum(current_idx_);
int ms_level = spectrum.getMSLevel();
// wrong MS level
if (ms_level < 2)
{
return;
}
// extract PeptideIdentification and PeptideHit if possible.
// that this function returns prematurely is unlikely,
// since we are deleting existing annotations,
// that have to be somewhere, but better make sure
PeptideIdentification& pep_ids = getPeakDataMuteable()->getPeptideIdentifications()[peptide_id_index];
PeptideHit& hit = pep_ids.getHits()[peptide_hit_index];
vector<PeptideHit::PeakAnnotation> fas = hit.getPeakAnnotations();
if (fas.empty())
{
return;
}
// all requirements fulfilled, PH in hit and annotations in selected_annotations
vector<PeptideHit::PeakAnnotation> to_remove;
// collect annotations, that have to be removed
for (auto const& tmp_a : fas)
{
for (auto const& it : selected_annotations)
{
using ItemType = Peak1D;
auto pa = dynamic_cast<Annotation1DPeakItem<ItemType>*>(it);
// only search for peak annotations
if (pa == nullptr)
{
continue;
}
if (fabs(tmp_a.mz - pa->getPeakPosition().getMZ()) < 1e-6)
{
if (String(pa->getText()).hasPrefix(tmp_a.annotation))
{
to_remove.push_back(tmp_a);
}
}
}
}
// remove the collected annotations from the PeptideHit annotations
for (auto const& tmp_a : to_remove)
{
fas.erase(std::remove(fas.begin(), fas.end(), tmp_a), fas.end());
}
if (!to_remove.empty())
{
hit.setPeakAnnotations(fas);
}
}
void LayerData1DPeak::updatePeptideHitAnnotations_(PeptideHit& hit)
{
// copy user annotations to fragment annotation vector
const Annotations1DContainer& las = getCurrentAnnotations();
// initialize with an empty vector
vector<PeptideHit::PeakAnnotation> fas;
// do not change PeptideHit annotations, if there are no annotations on the spectrum
bool annotations_changed(false);
// for each annotation item on the canvas
for (auto& a : las)
{
// only store peak annotations (skip general labels and distance annotations)
auto pa = dynamic_cast<Annotation1DPeakItem<Peak1D>*>(a);
if (pa == nullptr)
{
continue;
}
fas.push_back(pa->toPeakAnnotation());
annotations_changed = true;
}
if (annotations_changed)
{
hit.setPeakAnnotations(fas);
}
}
}// namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerDataPeak.cpp | .cpp | 9,686 | 304 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/ANALYSIS/ID/IDMapper.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
#include <OpenMS/VISUAL/LayerData1DIonMobility.h>
#include <OpenMS/VISUAL/LayerData1DChrom.h>
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/Painter2DBase.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
using namespace std;
namespace OpenMS
{
LayerDataPeak::LayerDataPeak() : LayerDataBase(LayerDataBase::DT_PEAK)
{
flags.set(LayerDataBase::P_PRECURSORS);
}
/*LayerDataPeak::LayerDataPeak(const LayerDataPeak& ld)
: LayerDataBase(static_cast<const LayerDataBase&>(ld)),
peak_map_(ld.peak_map_),
on_disc_peaks_(ld.on_disc_peaks_)
{
} */
std::unique_ptr<Painter2DBase> LayerDataPeak::getPainter2D() const
{
return make_unique<Painter2DPeak>(this);
}
std::unique_ptr<LayerData1DBase> LayerDataPeak::to1DLayer() const
{
return make_unique<LayerData1DPeak>(*this);
}
std::unique_ptr<LayerStoreData> LayerDataPeak::storeVisibleData(const RangeAllType& visible_range, const DataFilters& layer_filters) const
{
auto ret = make_unique<LayerStoreDataPeakMapVisible>();
ret->storeVisibleExperiment(peak_map_->getMSExperiment(), visible_range, layer_filters);
return ret;
}
std::unique_ptr<LayerStoreData> LayerDataPeak::storeFullData() const
{
auto ret = make_unique<LayerStoreDataPeakMapAll>();
ret->storeFullExperiment(peak_map_->getMSExperiment());
return ret;
}
LayerDataPeak::ProjectionData LayerDataPeak::getProjection(const DIM_UNIT unit_x, const DIM_UNIT unit_y, const RangeAllType& area) const
{
ProjectionData result;
// create projection data
map<float, float> rt;
map<float, float> mobility;
map<int, float> mzint;
map<int, float> mzsum;
auto& peak_count = result.stats.number_of_datapoints;
auto& intensity_max = result.stats.max_intensity;
auto& total_intensity_sum = result.stats.sum_intensity;
// divide visible range into 100 bins (much faster than using a constant, e.g. 0.05, leading to many peaks for large maps without more information)
float mz_range = area.RangeMZ::getSpan();
float mult = 100.0f / (std::isnan(mz_range) ? 1 : mz_range);
MSSpectrum projection_mz;
Mobilogram projection_im;
MSChromatogram projection_rt;
const auto& exp = getPeakData()->getMSExperiment();
auto lvls = exp.getMSLevels(); // use for smallest MS level in the data (IM frames may have all level 1, or all level 2)
for (auto i = exp.areaBeginConst(area, lvls[0]); i != exp.areaEndConst(); ++i)
{
PeakIndex pi = i.getPeakIndex();
if (filters.passes(exp[pi.spectrum], pi.peak))
{
// summary stats
++peak_count;
total_intensity_sum += i->getIntensity();
intensity_max = max(intensity_max, i->getIntensity());
// binning for m/z
auto intensity = i->getIntensity();
mzint[int(i->getMZ() * mult)] += intensity;
// ... to later obtain an intensity weighted average m/z value
mzsum[int(i->getMZ() * mult)] += i->getMZ() * intensity;
// binning in RT (one value per scan)
rt[i.getRT()] += i->getIntensity();
// binning in IM (one value per scan)
mobility[i.getDriftTime()] += i->getIntensity();
}
}
projection_mz.resize(mzint.size() + 2);
// write to spectra/chrom
try
{ // may throw if m/z is not in area
projection_mz[0].setMZ(area.getMinMZ());
projection_mz[0].setIntensity(0.0);
projection_mz.back().setMZ(area.getMaxMZ());
projection_mz.back().setIntensity(0.0);
}
catch (...) { }
projection_im.resize(mobility.size() + 2);
try
{ // may throw if IM is not in area
projection_im[0].setMobility(area.getMinMobility());
projection_im[0].setIntensity(0.0);
projection_im.back().setMobility(area.getMaxMobility());
projection_im.back().setIntensity(0.0);
}
catch (...)
{
}
projection_rt.resize(rt.size() + 2);
try
{ // may throw if RT is not in area
projection_rt[0].setRT(area.getMinRT());
projection_rt[0].setIntensity(0.0);
projection_rt.back().setRT(area.getMaxRT());
projection_rt.back().setIntensity(0.0);
}
catch (...)
{
}
Size i = 1;
auto intit = mzint.begin();
for (auto it = mzsum.cbegin(); it != mzsum.cend(); ++it)
{
auto intensity = intit->second;
projection_mz[i].setMZ(it->second / intensity);
projection_mz[i].setIntensity(intensity);
++intit;
++i;
}
i = 1;
for (auto it = mobility.cbegin(); it != mobility.cend(); ++it)
{
projection_im[i].setMobility(it->first);
projection_im[i].setIntensity(it->second);
++i;
}
i = 1;
for (auto it = rt.cbegin(); it != rt.cend(); ++it)
{
projection_rt[i].setRT(it->first);
projection_rt[i].setIntensity(it->second);
++i;
}
// create final datastructure
// projection for m/z
auto ptr_mz = make_unique<LayerData1DPeak>();
{
MSExperiment exp_mz;
exp_mz.addSpectrum(std::move(projection_mz));
ptr_mz->setPeakData(ExperimentSharedPtrType(new ExperimentType(std::move(exp_mz))));
}
// projection for mobility
auto ptr_im = make_unique<LayerData1DIonMobility>();
{
ptr_im->setMobilityData(projection_im);
}
// projection for RT
auto ptr_rt = make_unique<LayerData1DChrom>();
{
MSExperiment exp_rt;
exp_rt.addChromatogram(std::move(projection_rt));
ptr_rt->setChromData(ExperimentSharedPtrType(new ExperimentType(std::move(exp_rt))));
}
auto assign_axis = [&](auto unit, auto& layer) {
switch (unit)
{
case DIM_UNIT::MZ:
layer = std::move(ptr_mz);
break;
case DIM_UNIT::RT:
layer = std::move(ptr_rt);
break;
case DIM_UNIT::FAIMS_CV:
case DIM_UNIT::IM_MS:
case DIM_UNIT::IM_VSSC:
layer = std::move(ptr_im);
break;
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
};
assign_axis(unit_x, result.projection_ontoX);
assign_axis(unit_y, result.projection_ontoY);
return result;
}
PeakIndex LayerDataPeak::findHighestDataPoint(const RangeAllType& area) const
{
using IntType = MSExperiment::ConstAreaIterator::PeakType::IntensityType;
auto max_int = numeric_limits<IntType>::lowest();
PeakIndex max_pi;
const auto& map = getPeakData()->getMSExperiment();
// for IM data, use whatever is there. For RT/mz data, use MSlevel 1
const UInt MS_LEVEL = (! map.empty() && map.isIMFrame()) ? map[0].getMSLevel() : 1;
for (auto i = map.areaBeginConst(area, MS_LEVEL); i != map.areaEndConst(); ++i)
{
PeakIndex pi = i.getPeakIndex();
if (i->getIntensity() > max_int && filters.passes((map)[pi.spectrum], pi.peak))
{
max_int = i->getIntensity();
max_pi = pi;
}
}
return max_pi;
}
PointXYType LayerDataPeak::peakIndexToXY(const PeakIndex& peak, const DimMapper<2>& mapper) const
{
const auto& spec = getSpectrum(peak.spectrum);
return mapper.map(spec, peak.peak);
}
String LayerDataPeak::getDataArrayDescription(const PeakIndex& peak_index)
{
String status;
const ExperimentType::SpectrumType& s = getSpectrum(peak_index.spectrum);
for (Size m = 0; m < s.getFloatDataArrays().size(); ++m)
{
if (peak_index.peak < s.getFloatDataArrays()[m].size())
{
status += s.getFloatDataArrays()[m].getName() + ": " + s.getFloatDataArrays()[m][peak_index.peak] + " ";
}
}
for (Size m = 0; m < s.getIntegerDataArrays().size(); ++m)
{
if (peak_index.peak < s.getIntegerDataArrays()[m].size())
{
status += s.getIntegerDataArrays()[m].getName() + ": " + s.getIntegerDataArrays()[m][peak_index.peak] + " ";
}
}
for (Size m = 0; m < s.getStringDataArrays().size(); ++m)
{
if (peak_index.peak < s.getStringDataArrays()[m].size())
{
status += s.getStringDataArrays()[m].getName() + ": " + s.getStringDataArrays()[m][peak_index.peak] + " ";
}
}
return status;
}
std::unique_ptr<LayerStatistics> LayerDataPeak::getStats() const
{
return make_unique<LayerStatisticsPeakMap>(peak_map_->getMSExperiment());
}
bool LayerDataPeak::annotate(const PeptideIdentificationList& identifications, const vector<ProteinIdentification>& protein_identifications)
{
IDMapper mapper;
Param p = mapper.getDefaults();
p.setValue("rt_tolerance", 0.1, "RT tolerance (in seconds) for the matching");
p.setValue("mz_tolerance", 1.0, "m/z tolerance (in ppm or Da) for the matching");
p.setValue("mz_measure", "Da", "unit of 'mz_tolerance' (ppm or Da)");
mapper.setParameters(p);
mapper.annotate(*getPeakDataMuteable(), identifications, protein_identifications, true);
return true;
}
const LayerDataBase::ConstExperimentSharedPtrType LayerDataPeak::getPeakData() const
{
return std::static_pointer_cast<const ExperimentType>(peak_map_);
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerListView.cpp | .cpp | 6,145 | 193 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerListView.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/VISUAL/Plot1DCanvas.h>
#include <OpenMS/VISUAL/Plot2DCanvas.h>
#include <OpenMS/VISUAL/Plot3DCanvas.h>
#include <OpenMS/VISUAL/Plot1DWidget.h>
#include <OpenMS/VISUAL/Plot2DWidget.h>
#include <OpenMS/VISUAL/Plot3DWidget.h>
#include <QtWidgets/QListWidgetItem>
using namespace std;
namespace OpenMS
{
LayerListView::LayerListView(QWidget* parent)
: QListWidget(parent)
{
const auto help = "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.";
this->setWhatsThis(help);
this->setToolTip(help);
setDragEnabled(true);
connect(this, &LayerListView::currentRowChanged, this, &LayerListView::currentRowChangedAction_);
connect(this, &LayerListView::itemChanged, this, &LayerListView::itemChangedAction_);
connect(this, &QListWidget::itemDoubleClicked, this, &LayerListView::itemDoubleClickedAction_);
}
void LayerListView::update(PlotWidget* active_widget)
{
// reset items
this->clear();
spectrum_widget_ = active_widget;
// during program exit, this could be called after PlotWidgets are gone
if (spectrum_widget_ == nullptr)
{
return;
}
PlotCanvas* cc = spectrum_widget_->canvas();
if (cc == nullptr)
{
return;
}
// determine if this is a 1D view (for text color)
bool is_1d_view = (dynamic_cast<Plot1DCanvas*>(cc) != nullptr);
this->blockSignals(true);
RAIICleanup cl([&]() { this->blockSignals(false); });
for (Size i = 0; i < cc->getLayerCount(); ++i)
{
const LayerDataBase& layer = cc->getLayer(i);
// add item
QListWidgetItem* item = new QListWidgetItem(this);
QString name = layer.getDecoratedName().toQString();
item->setText(name);
item->setToolTip(layer.filename.toQString());
if (is_1d_view)
{
QPixmap icon(7, 7);
icon.fill(QColor(String(layer.param.getValue("peak_color").toString()).toQString()));
item->setIcon(icon);
}
else
{ // 2D/3D map view
switch (layer.type)
{
case LayerDataBase::DT_PEAK:
item->setIcon(QIcon(":/peaks.png"));
break;
case LayerDataBase::DT_FEATURE:
item->setIcon(QIcon(":/convexhull.png"));
break;
case LayerDataBase::DT_CONSENSUS:
item->setIcon(QIcon(":/elements.png"));
break;
default:
break;
}
}
item->setCheckState(layer.visible ? Qt::Checked : Qt::Unchecked);
// highlight active item
if (i == cc->getCurrentLayerIndex())
{
this->setCurrentItem(item);
}
}
}
void LayerListView::currentRowChangedAction_(int i)
{
// after adding a layer, i is -1. TODO: check if this is the correct behaviour
if (i != -1)
{
spectrum_widget_->canvas()->activateLayer(i); // emits layerActivated in TOPPView
}
}
void LayerListView::itemChangedAction_(QListWidgetItem* item)
{
int layer = this->row(item);
bool visible = spectrum_widget_->canvas()->getLayer(layer).visible;
if (item->checkState() == Qt::Unchecked && visible)
{
spectrum_widget_->canvas()->changeVisibility(layer, false);
emit layerDataChanged();
}
else if (item->checkState() == Qt::Checked && !visible)
{
spectrum_widget_->canvas()->changeVisibility(layer, true);
emit layerDataChanged();
}
}
void LayerListView::contextMenuEvent(QContextMenuEvent* event)
{
QListWidgetItem* item = this->itemAt(event->pos());
if (!item)
{
return;
}
int layer_idx = this->row(item);
QMenu* context_menu = new QMenu(this);
context_menu->addAction("Rename", [&]() {
QString name = QInputDialog::getText(this, "Rename layer", "Name:", QLineEdit::Normal, spectrum_widget_->canvas()->getLayerName(layer_idx).toQString());
if (name != "")
{
spectrum_widget_->canvas()->setLayerName(layer_idx, name);
emit layerDataChanged();
}});
context_menu->addAction("Delete", [&]() {
spectrum_widget_->canvas()->removeLayer(layer_idx);
emit layerDataChanged();
});
auto widget1D = qobject_cast<Plot1DWidget*>(spectrum_widget_);
if (widget1D != nullptr)
{
if (widget1D->canvas()->getLayer(layer_idx).flipped)
{
context_menu->addAction("Flip upwards (1D)", [&]() {
widget1D->canvas()->flipLayer(layer_idx);
widget1D->canvas()->setMirrorModeActive(widget1D->canvas()->flippedLayersExist());
});
emit layerDataChanged();
}
else
{
context_menu->addAction("Flip downwards (1D)", [&]() {
widget1D->canvas()->flipLayer(layer_idx);
widget1D->canvas()->setMirrorModeActive(true);
});
emit layerDataChanged();
}
}
context_menu->addSeparator();
context_menu->addAction("Preferences", [&]() {
spectrum_widget_->canvas()->showCurrentLayerPreferences();
});
context_menu->exec(this->mapToGlobal(event->pos()));
}
void LayerListView::itemDoubleClickedAction_(QListWidgetItem* /*item*/)
{
spectrum_widget_->canvas()->showCurrentLayerPreferences();
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/PlotCanvas.cpp | .cpp | 27,919 | 950 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimator.h>
#include <OpenMS/VISUAL/FileWatcher.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/LayerData1DChrom.h>
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/LayerDataChrom.h>
#include <OpenMS/VISUAL/LayerDataConsensus.h>
#include <OpenMS/VISUAL/LayerDataFeature.h>
#include <OpenMS/VISUAL/LayerDataIdent.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/MetaDataBrowser.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/Plot1DCanvas.h>
#include <OpenMS/VISUAL/PlotCanvas.h>
#include <OpenMS/VISUAL/PlotWidget.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
// QT
#include <QPaintEvent>
#include <QPainter>
#include <QtWidgets/QMessageBox>
#include <iostream>
#include <utility>
using namespace std;
namespace OpenMS
{
PlotCanvas::PlotCanvas(const Param& /*preferences*/, QWidget* parent)
: QWidget(parent),
DefaultParamHandler("PlotCanvas"),
unit_mapper_({DIM_UNIT::RT, DIM_UNIT::MZ}),
visible_area_(&unit_mapper_),
rubber_band_(QRubberBand::Rectangle, this)
{
// Prevent filling background
setAttribute(Qt::WA_OpaquePaintEvent);
// get mouse coordinates while mouse moves over diagram and for focus handling
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
setMinimumSize(200, 200);
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
// set common defaults for all canvases
defaults_.setValue("default_path", ".", "Default path for loading/storing data.");
// Set focus policy in order to get keyboard events
// Set 'whats this' text
setWhatsThis(
"Translate: Translate mode is activated by default. Hold down the left mouse key and move the mouse to translate. Arrow keys can be used for translation independent of the current mode.\n\n"
"Zoom: Zoom mode is activated with the CTRL key. CTRL+/CTRL- are used to traverse the zoom stack (or mouse wheel). Pressing Backspace resets the zoom.\n\n"
"Measure: Measure mode is activated with the SHIFT key. To measure the distance between data points, press the left mouse button on a point and drag the mouse to another point.\n\n");
// set move cursor and connect signal that updates the cursor automatically
updateCursor_();
connect(this, SIGNAL(actionModeChange()), this, SLOT(updateCursor_()));
}
PlotCanvas::~PlotCanvas() = default;
void PlotCanvas::resizeEvent(QResizeEvent* /* e */)
{
#ifdef DEBUG_TOPPVIEW
cout << "BEGIN " << OPENMS_PRETTY_FUNCTION << endl;
#endif
buffer_ = QImage(width(), height(), QImage::Format_RGB32);
update_buffer_ = true;
updateScrollbars_();
update_(OPENMS_PRETTY_FUNCTION);
#ifdef DEBUG_TOPPVIEW
cout << "END " << OPENMS_PRETTY_FUNCTION << endl;
#endif
}
void PlotCanvas::initFilters(const DataFilters& filters)
{
layers_.getCurrentLayer().filters = filters;
}
void PlotCanvas::setFilters(const DataFilters& filters)
{
// set filters
layers_.getCurrentLayer().filters = filters;
// update the content
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
void PlotCanvas::showGridLines(bool show)
{
show_grid_ = show;
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
void PlotCanvas::intensityModeChange_()
{
// update axes (e.g. make it Log-scale)
if (spectrum_widget_)
{
spectrum_widget_->updateAxes();
}
recalculateSnapFactor_();
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
void PlotCanvas::dimensionsChanged_()
{
zoom_stack_.clear(); // any zoom history is bogus
// swap axes if necessary
if (spectrum_widget_)
{
spectrum_widget_->updateAxes();
}
updateScrollbars_();
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
void PlotCanvas::changeVisibleArea_(VisibleArea new_area, bool repaint, bool add_to_stack)
{
auto data_range = getDataRange(); // getDataRange() is virtual, since its special for 1D (0-based intensity)
if (intensity_mode_ == IM_PERCENTAGE)
{ // new_area will have [0, 100], and we don't want to make that any smaller if the data only goes up to, say 50
}
else
{ // make sure we stay inside the overall data range
new_area.pushInto(data_range);
}
// store old zoom state
if (add_to_stack)
{
// if we scrolled in between zooming we want to store the last position before zooming as well
if ((!zoom_stack_.empty()) && (zoom_stack_.back() != visible_area_))
{
zoomAdd_(visible_area_);
}
// add current zoom
zoomAdd_(new_area);
}
// always update, even if the area did not change, since the intensity mode might have changed
visible_area_ = new_area;
updateScrollbars_();
recalculateSnapFactor_();
emit visibleAreaChanged(new_area); // calls PlotWidget::updateAxes, which calls Plot(1D/2D/3D)Widget::recalculateAxes_
emit layerZoomChanged(this); // calls TOPPViewBase::zoomOtherWindows (for linked windows)
if (repaint)
{
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
}
void PlotCanvas::updateScrollbars_()
{
}
void PlotCanvas::wheelEvent(QWheelEvent* e)
{
zoom_(e->position().x(), e->position().y(), e->angleDelta().y() > 0);
e->accept();
}
void PlotCanvas::zoom_(int x, int y, bool zoom_in)
{
if (!zoom_in)
{
zoomBack_();
}
else
{ // we want to zoom into (x,y), which is in pixel units, hence we need to know the relative position of (x,y) in the widget
constexpr PointXYType::CoordinateType zoom_factor = 0.8;
const double rel_pos_x = (PointXYType::CoordinateType)x / width();
const double rel_pos_y = (PointXYType::CoordinateType)(height() - y) / height();
auto new_area = visible_area_.getAreaXY();
{
auto zoomed = Math::zoomIn(new_area.minX(), new_area.maxX(), zoom_factor, rel_pos_x);
new_area.setMinX(zoomed.first);
new_area.setMaxX(zoomed.second);
}
{
auto zoomed = Math::zoomIn(new_area.minY(), new_area.maxY(), zoom_factor, rel_pos_y);
new_area.setMinY(zoomed.first);
new_area.setMaxY(zoomed.second);
}
if (new_area != visible_area_.getAreaXY())
{
zoomAdd_(visible_area_.cloneWith(new_area));
PlotCanvas::changeVisibleArea_(*zoom_pos_);
}
}
}
void PlotCanvas::zoomBack_()
{
if (zoom_pos_ != zoom_stack_.begin())
{
--zoom_pos_;
changeVisibleArea_(*zoom_pos_);
}
}
void PlotCanvas::zoomForward_()
{
// if at end of zoom level then simply add a new zoom
if (zoom_pos_ == zoom_stack_.end() || (zoom_pos_ + 1) == zoom_stack_.end())
{
auto new_area = visible_area_;
auto xy = new_area.getAreaXY();
zoomAdd_(new_area.setArea(xy.extend(0.8)));
zoom_pos_ = --zoom_stack_.end(); // set to last position
}
else // goto next zoom level
{
++zoom_pos_;
}
changeVisibleArea_(*zoom_pos_);
}
void PlotCanvas::zoomAdd_(const VisibleArea& area)
{
if (zoom_pos_ != zoom_stack_.end() && (zoom_pos_ + 1) != zoom_stack_.end())
{
zoom_stack_.erase(zoom_pos_ + 1, zoom_stack_.end());
}
zoom_stack_.push_back(area);
zoom_pos_ = zoom_stack_.end();
--zoom_pos_;
}
void PlotCanvas::zoomClear_()
{
zoom_stack_.clear();
zoom_pos_ = zoom_stack_.end();
}
void PlotCanvas::resetZoom(bool repaint)
{
zoomClear_();
changeVisibleArea_(visible_area_.cloneWith(overall_data_range_), repaint, true);
}
void PlotCanvas::setVisibleArea(const VisibleArea& area)
{ // do not simply call "changeVisibleArea_(area);", since this will choke on different
// internal DimMappers (and you probably do not want to change the DimMapping. E.g. when calling this from a 2DCanvas (RT,mz) to display a 1DCanvas (mz,int))
changeVisibleArea_(visible_area_.cloneWith(area.getAreaUnit()));
}
void PlotCanvas::setVisibleArea(const RangeAllType& area)
{
changeVisibleArea_(visible_area_.cloneWith(area));
}
void PlotCanvas::setVisibleArea(const AreaXYType& area)
{
changeVisibleArea_(visible_area_.cloneWith(area));
}
void PlotCanvas::setVisibleAreaX(double min, double max)
{
auto va = visible_area_.getAreaXY();
va.setMinX(min);
va.setMaxX(max);
setVisibleArea(va);
}
void PlotCanvas::setVisibleAreaY(double min, double max)
{
auto va = visible_area_.getAreaXY();
va.setMinY(min);
va.setMaxY(max);
setVisibleArea(va);
}
void PlotCanvas::saveCurrentLayer(bool visible)
{
const LayerDataBase& layer = getCurrentLayer();
// determine proposed filename
String proposed_name = param_.getValue("default_path").toString();
if (visible == false && layer.filename != "")
{
proposed_name = layer.filename;
}
auto formats = layer.storeFullData()->getSupportedFileFormats(); // storeFullData() is cheap; we just want the formats...
QString file_name = GUIHelpers::getSaveFilename(this, "Save file", proposed_name.toQString(), formats, true, formats.getTypes().front());
if (file_name.isEmpty())
{
return;
}
auto visitor_data = visible ? layer.storeVisibleData(getVisibleArea().getAreaUnit(), layer.filters) : layer.storeFullData();
visitor_data->saveToFile(file_name, ProgressLogger::GUI);
modificationStatus_(getCurrentLayerIndex(), false);
}
void PlotCanvas::paintGridLines_(QPainter& painter)
{
if (!show_grid_ || !spectrum_widget_)
{
return;
}
QPen p1(QColor(130, 130, 130));
p1.setStyle(Qt::DashLine);
QPen p2(QColor(170, 170, 170));
p2.setStyle(Qt::DotLine);
painter.save();
unsigned int xl, xh, yl, yh; // width/height of the diagram area, x, y coordinates of lo/hi x,y values
xl = 0;
xh = width();
yl = height();
yh = 0;
// drawing of grid lines and associated text
for (Size j = 0; j != spectrum_widget_->xAxis()->gridLines().size(); j++)
{
// style definitions
switch (j)
{
case 0: // style settings for big intervals
painter.setPen(p1);
break;
case 1: // style settings for small intervals
painter.setPen(p2);
break;
default:
std::cout << "empty vertical grid line vector error!" << std::endl;
painter.setPen(QPen(QColor(0, 0, 0)));
break;
}
for (std::vector<double>::const_iterator it = spectrum_widget_->xAxis()->gridLines()[j].begin(); it != spectrum_widget_->xAxis()->gridLines()[j].end(); ++it)
{
int x = static_cast<int>(Math::intervalTransformation(*it, spectrum_widget_->xAxis()->getAxisMinimum(), spectrum_widget_->xAxis()->getAxisMaximum(), xl, xh));
painter.drawLine(x, yl, x, yh);
}
}
for (Size j = 0; j != spectrum_widget_->yAxis()->gridLines().size(); j++)
{
// style definitions
switch (j)
{
case 0: // style settings for big intervals
painter.setPen(p1);
break;
case 1: // style settings for small intervals
painter.setPen(p2);
break;
default:
std::cout << "empty vertical grid line vector error!" << std::endl;
painter.setPen(QPen(QColor(0, 0, 0)));
break;
}
for (std::vector<double>::const_iterator it = spectrum_widget_->yAxis()->gridLines()[j].begin(); it != spectrum_widget_->yAxis()->gridLines()[j].end(); ++it)
{
int y = static_cast<int>(Math::intervalTransformation(*it, spectrum_widget_->yAxis()->getAxisMinimum(), spectrum_widget_->yAxis()->getAxisMaximum(), yl, yh));
painter.drawLine(xl, y, xh, y);
}
}
painter.restore();
}
void setBaseLayerParameters(LayerDataBase* new_layer, const Param& param, const String& filename, const String& caption)
{
new_layer->param = param;
new_layer->filename = filename;
if (! caption.empty())
{
new_layer->setName(caption);
}
else
{
new_layer->setName(QFileInfo(filename.toQString()).completeBaseName());
}
}
bool PlotCanvas::addLayer(std::unique_ptr<LayerData1DBase> new_layer)
{
setBaseLayerParameters(new_layer.get(), param_, new_layer->filename, new_layer->getName());
layers_.addLayer(std::move(new_layer));
return finishAdding_();
}
bool PlotCanvas::addPeakLayer(const ExperimentSharedPtrType& map,
ODExperimentSharedPtrType od_map,
const String& filename,
const String& caption,
const bool use_noise_cutoff)
{
if (map->getMSExperiment().getSpectra().empty())
{
auto msg = "Your input data contains no spectra. Not adding layer.";
OPENMS_LOG_WARN << msg << std::endl;
QMessageBox::critical(this, "Error", msg);
return false;
}
LayerDataPeakUPtr new_layer;
if (dynamic_cast<Plot1DCanvas*>(this))
new_layer.reset(new LayerData1DPeak);
else
new_layer.reset(new LayerDataPeak);
new_layer->setPeakData(map);
new_layer->setOnDiscPeakData(std::move(od_map));
setBaseLayerParameters(new_layer.get(), param_, filename, caption);
layers_.addLayer(std::move(new_layer));
// calculate noise
if (use_noise_cutoff)
{
auto cutoff = estimateNoiseFromRandomScans(map->getMSExperiment(), 1, 10, 5); // 5% of low intensity data is considered noise
DataFilters filters;
filters.add(DataFilters::DataFilter(DataFilters::INTENSITY, DataFilters::GREATER_EQUAL, cutoff));
initFilters(filters);
}
else // no mower, hide zeros if wanted
{
if (map->getMSExperiment().hasZeroIntensities(1))
{
DataFilters filters;
filters.add(DataFilters::DataFilter(DataFilters::INTENSITY, DataFilters::GREATER_EQUAL, 0.001));
initFilters(filters);
}
}
return finishAdding_();
}
bool PlotCanvas::addChromLayer(const ExperimentSharedPtrType& map, ODExperimentSharedPtrType od_map, const String& filename, const String& caption)
{
if (map->getMSExperiment().getChromatograms().empty())
{
auto msg = "Your input data contains no chromatograms. Not adding layer.";
OPENMS_LOG_WARN << msg << std::endl;
QMessageBox::critical(this, "Error", msg);
return false;
}
LayerDataChromUPtr new_layer;
if (dynamic_cast<Plot1DCanvas*>(this))
new_layer.reset(new LayerData1DChrom);
else
new_layer.reset(new LayerDataChrom);
new_layer->setChromData(map);
new_layer->setOnDiscPeakData(std::move(od_map));
setBaseLayerParameters(new_layer.get(), param_, filename, caption);
layers_.addLayer(std::move(new_layer));
return finishAdding_();
}
bool PlotCanvas::addLayer(FeatureMapSharedPtrType map, const String& filename, const String& caption)
{
LayerDataFeatureUPtr new_layer(new LayerDataFeature);
new_layer->getFeatureMap() = std::move(map);
setBaseLayerParameters(new_layer.get(), param_, filename, caption);
layers_.addLayer(std::move(new_layer));
return finishAdding_();
}
bool PlotCanvas::addLayer(ConsensusMapSharedPtrType map, const String& filename, const String& caption)
{
LayerDataBaseUPtr new_layer(new LayerDataConsensus(map));
setBaseLayerParameters(new_layer.get(), param_, filename, caption);
layers_.addLayer(std::move(new_layer));
return finishAdding_();
}
bool PlotCanvas::addLayer(PeptideIdentificationList& peptides, const String& filename, const String& caption)
{
LayerDataIdent* new_layer(new LayerDataIdent); // ownership will be transferred to unique_ptr below; no need to delete
new_layer->setPeptideIds(std::move(peptides));
setBaseLayerParameters(new_layer, param_, filename, caption);
layers_.addLayer(LayerDataBaseUPtr(new_layer));
return finishAdding_();
}
void PlotCanvas::popIncompleteLayer_(const QString& error_message)
{
layers_.removeCurrentLayer();
if (!error_message.isEmpty())
QMessageBox::critical(this, "Error", error_message);
}
void PlotCanvas::setLayerName(Size i, const String& name)
{
getLayer(i).setName(name);
if (i == 0 && spectrum_widget_)
{
spectrum_widget_->setWindowTitle(name.toQString());
}
}
String PlotCanvas::getLayerName(const Size i)
{
return getLayer(i).getName();
}
void PlotCanvas::changeVisibility(Size i, bool b)
{
LayerDataBase& layer = getLayer(i);
if (layer.visible != b)
{
layer.visible = b;
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
}
void PlotCanvas::changeLayerFilterState(Size i, bool b)
{
LayerDataBase& layer = getLayer(i);
if (layer.filters.isActive() != b)
{
layer.filters.setActive(b);
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
}
const PlotCanvas::RangeType& PlotCanvas::getDataRange() const
{
return overall_data_range_;
}
void PlotCanvas::recalculateRanges_()
{
RangeType& layer_range = overall_data_range_;
layer_range.clearRanges();
for (Size layer_index = 0; layer_index < getLayerCount(); ++layer_index)
{
layer_range.extend(getLayer(layer_index).getRange());
}
// set minimum intensity to 0 (avoid negative intensities!)
if (layer_range.getMinIntensity() < 0) layer_range.setMinIntensity(0);
// add 4% margin (2% left, 2% right) to RT, m/z, IM and intensity
layer_range.scaleBy(1.04);
// make sure that each dimension is not a single point (axis widget won't like that)
// (this needs to be the last command to ensure this property holds when leaving the function!)
layer_range.minSpanIfSingular(1);
}
double PlotCanvas::getSnapFactor()
{ // only useful for 1D view at the moment (which only has a single snap factor). 2D view has as many as there are layers.
return snap_factors_[0];
}
double PlotCanvas::getPercentageFactor() const
{
return percentage_factor_;
}
void PlotCanvas::recalculateSnapFactor_()
{
}
void PlotCanvas::horizontalScrollBarChange(int /*value*/)
{
}
void PlotCanvas::verticalScrollBarChange(int /*value*/)
{
}
void PlotCanvas::update_(const char*)
{
update();
}
// this does not work anymore, probably due to Qt::StrongFocus :( -- todo: delete!
void PlotCanvas::focusOutEvent(QFocusEvent* /*e*/)
{
// Alt/Shift pressed and focus lost => change back action mode
if (action_mode_ != AM_TRANSLATE)
{
action_mode_ = AM_TRANSLATE;
emit actionModeChange();
}
// reset peaks
selected_peak_.clear();
measurement_start_.clear();
// update
update_(OPENMS_PRETTY_FUNCTION);
}
void PlotCanvas::leaveEvent(QEvent* /*e*/)
{
// release keyboard, when the mouse pointer leaves
releaseKeyboard();
}
void PlotCanvas::enterEvent(QEnterEvent* /*e*/)
{
// grab keyboard, as we need to handle key presses
grabKeyboard();
}
void PlotCanvas::keyReleaseEvent(QKeyEvent* e)
{
// Alt/Shift released => change back action mode
if (e->key() == Qt::Key_Control || e->key() == Qt::Key_Shift)
{
action_mode_ = AM_TRANSLATE;
emit actionModeChange();
e->accept();
}
e->ignore();
}
void PlotCanvas::keyPressEvent(QKeyEvent* e)
{
if (e->key() == Qt::Key_Control)
{ // Ctrl pressed => change action mode
action_mode_ = AM_ZOOM;
emit actionModeChange();
}
else if (e->key() == Qt::Key_Shift)
{ // Shift pressed => change action mode
action_mode_ = AM_MEASURE;
emit actionModeChange();
}
else if ((e->modifiers() & Qt::ControlModifier) &&
(e->key() == Qt::Key_Plus)) // do not use (e->modifiers() == Qt::ControlModifier) to target Ctrl exclusively, since +/- might(!) also trigger the Qt::KeypadModifier
{ // CTRL+Plus => Zoom stack
zoomForward_();
}
else if ((e->modifiers() & Qt::ControlModifier) && (e->key() == Qt::Key_Minus))
{ // CTRL+Minus => Zoom stack
zoomBack_();
}
// Arrow keys => translate
else if (e->key() == Qt::Key_Left)
{
translateLeft_(e->modifiers());
}
else if (e->key() == Qt::Key_Right)
{
translateRight_(e->modifiers());
}
else if (e->key() == Qt::Key_Up)
{
translateForward_();
}
else if (e->key() == Qt::Key_Down)
{
translateBackward_();
}
else if (e->key() == Qt::Key_Backspace)
{ // Backspace to reset zoom
resetZoom();
}
else if ((e->modifiers() == (Qt::ControlModifier | Qt::AltModifier)) && (e->key() == Qt::Key_T))
{ // CTRL+ALT+T => activate timing mode
show_timing_ = !show_timing_;
}
else
{ // call the keyPressEvent() of the parent widget
e->ignore();
}
}
void PlotCanvas::translateLeft_(Qt::KeyboardModifiers /*m*/)
{
}
void PlotCanvas::translateRight_(Qt::KeyboardModifiers /*m*/)
{
}
void PlotCanvas::translateForward_()
{
}
void PlotCanvas::translateBackward_()
{
}
void PlotCanvas::setAdditionalContextMenu(QMenu* menu)
{
context_add_ = menu;
}
const DimMapper<2>& PlotCanvas::getMapper() const
{
return unit_mapper_;
}
void PlotCanvas::setMapper(const DimMapper<2>& mapper)
{
unit_mapper_ = mapper;
}
void PlotCanvas::showMetaData(bool modifiable, Int index)
{
LayerDataBase& layer = getCurrentLayer();
MetaDataBrowser dlg(modifiable, this);
if (index == -1)
{
if (auto lp = dynamic_cast<LayerDataPeak*>(&layer))
{
dlg.add(lp->getPeakDataMuteable()->getMSExperiment());
// Exception for Plot1DCanvas, here we add the meta data of the one spectrum
if (auto lp1 = dynamic_cast<LayerData1DPeak*>(&layer))
{
dlg.add(lp1->getPeakDataMuteable()->getMSExperiment()[lp1->getCurrentIndex()]);
}
}
if (auto lp = dynamic_cast<LayerDataFeature*>(&layer))
{
dlg.add(*lp->getFeatureMap());
}
if (auto lp = dynamic_cast<LayerDataConsensus*>(&layer))
{
dlg.add(*lp->getConsensusMap());
}
else if (layer.type == LayerDataBase::DT_CHROMATOGRAM)
{
// TODO CHROM
}
else if (layer.type == LayerDataBase::DT_IDENT)
{
// TODO IDENT
}
}
else // show element meta data
{
if (auto lp = dynamic_cast<LayerDataPeak*>(&layer))
{
dlg.add(lp->getPeakDataMuteable()->getMSExperiment()[index]);
}
else if (auto lp = dynamic_cast<LayerDataFeature*>(&layer))
{
dlg.add((*lp->getFeatureMap())[index]);
}
else if (auto lp = dynamic_cast<LayerDataConsensus*>(&layer))
{
dlg.add((*lp->getConsensusMap())[index]);
}
else if (layer.type == LayerDataBase::DT_CHROMATOGRAM)
{
// TODO CHROM
}
else if (layer.type == LayerDataBase::DT_IDENT)
{
// TODO IDENT
}
}
// if the meta data was modified, set the flag
if (modifiable && dlg.exec())
{
modificationStatus_(getCurrentLayerIndex(), true);
}
}
void PlotCanvas::updateCursor_()
{
switch (action_mode_)
{
case AM_TRANSLATE:
setCursor(QCursor(QPixmap(":/cursor_move.png"), 0, 0));
break;
case AM_ZOOM:
setCursor(QCursor(QPixmap(":/cursor_zoom.png"), 0, 0));
break;
case AM_MEASURE:
setCursor(QCursor(QPixmap(":/cursor_measure.png"), 0, 0));
break;
}
}
void PlotCanvas::modificationStatus_(Size layer_index, bool modified)
{
LayerDataBase& layer = getLayer(layer_index);
if (layer.modified != modified)
{
layer.modified = modified;
#ifdef DEBUG_TOPPVIEW
cout << "BEGIN " << OPENMS_PRETTY_FUNCTION << endl;
cout << "emit: layerModificationChange" << endl;
cout << "END " << OPENMS_PRETTY_FUNCTION << endl;
#endif
emit layerModficationChange(getCurrentLayerIndex(), modified);
}
}
void PlotCanvas::drawText_(QPainter& painter, const QStringList& text)
{
GUIHelpers::drawText(painter, text, {2, 3}, Qt::black, QColor(255, 255, 255, 200));
}
double PlotCanvas::getIdentificationMZ_(const Size layer_index, const PeptideIdentification& peptide) const
{
if (getLayerFlag(layer_index, LayerDataBase::I_PEPTIDEMZ))
{
const PeptideHit& hit = peptide.getHits().front();
Int charge = hit.getCharge();
return hit.getSequence().getMZ(charge);
}
else
{
return peptide.getMZ();
}
}
void LayerStack::addLayer(LayerDataBaseUPtr new_layer)
{
// insert after last layer of same type,
// if there is no such layer after last layer of previous types,
// if there are no layers at all put at front
auto it = std::find_if(layers_.rbegin(), layers_.rend(), [&new_layer](const LayerDataBaseUPtr& l) { return l->type <= new_layer->type; });
auto where = layers_.insert(it.base(), std::move(new_layer));
// update to index we just inserted into
current_layer_ = where - layers_.begin();
}
const LayerDataBase& LayerStack::getLayer(const Size index) const
{
if (index >= layers_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, index, layers_.size());
}
return *layers_[index].get();
}
LayerDataBase& LayerStack::getLayer(const Size index)
{
if (index >= layers_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, index, layers_.size());
}
return *layers_[index].get();
}
const LayerDataBase& LayerStack::getCurrentLayer() const
{
if (current_layer_ >= layers_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, current_layer_, layers_.size());
}
return *layers_[current_layer_].get();
}
LayerDataBase& LayerStack::getCurrentLayer()
{
if (current_layer_ >= layers_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, current_layer_, layers_.size());
}
return *layers_[current_layer_].get();
}
void LayerStack::setCurrentLayer(Size index)
{
if (index >= layers_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, index, layers_.size());
}
current_layer_ = index;
}
Size LayerStack::getCurrentLayerIndex() const
{
return current_layer_;
}
bool LayerStack::empty() const
{
return layers_.empty();
}
Size LayerStack::getLayerCount() const
{
return layers_.size();
}
void LayerStack::removeLayer(Size layer_index)
{
if (layer_index >= layers_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, layer_index, layers_.size());
}
layers_.erase(layers_.begin() + layer_index);
// update current layer if it became invalid TODO dont you have to adjust the index to stay on the same layer??
if (current_layer_ >= getLayerCount())
{
current_layer_ = getLayerCount() - 1; // overflow is intentional
}
}
void LayerStack::removeCurrentLayer()
{
removeLayer(current_layer_);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/SequenceVisualizer.cpp | .cpp | 1,996 | 58 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Dhanmoni Nath, Julianus Pfeuffer $
// --------------------------------------------------------------------------
#ifdef QT_WEBENGINEWIDGETS_LIB
#include <OpenMS/VISUAL/SequenceVisualizer.h>
#include <ui_SequenceVisualizer.h>
#include <QWebChannel>
#include <QString>
#include <QtWebEngineWidgets/QWebEngineView>
// This is the window that appears when we click on 'show' in the 'sequence' column of the protein table
namespace OpenMS
{
SequenceVisualizer::SequenceVisualizer(QWidget* parent) :
QWidget(parent), ui_(new Ui::SequenceVisualizer)
{
ui_->setupUi(this);
view_ = new QWebEngineView(this);
channel_ = new QWebChannel(&backend_); // setup Qt WebChannel API
view_->page()->setWebChannel(channel_);
channel_->registerObject(QString("Backend"), &backend_); // This object will be available in HTML file.
view_->load(QUrl("qrc:/new/sequence_viz.html"));
ui_->gridLayout->addWidget(view_);
}
SequenceVisualizer::~SequenceVisualizer()
{
channel_->deleteLater();
view_->close();
view_->deleteLater();
delete ui_;
deleteLater();
}
// Get protein and peptide data from the protein table and store inside the m_json_data_obj_ object.
// Inside the HTML file, this QObject will be available and we'll access these protein and
// peptide data using the qtWebEngine and webChannel API.
void SequenceVisualizer::setProteinPeptideDataToJsonObj(
const QString& accession_num,
const QString& pro_seq,
const QJsonArray& pep_data)
{
QJsonObject j;
j["accession_num"] = accession_num;
j["protein_sequence_data"] = pro_seq;
j["peptides_data"] = pep_data;
backend_.m_json_data_obj_ = std::move(j);
}
}// namespace OpenMS
#endif | C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TVIdentificationViewController.cpp | .cpp | 53,830 | 1,400 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TVIdentificationViewController.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h>
#include <OpenMS/CHEMISTRY/NASequence.h>
#include <OpenMS/CHEMISTRY/Residue.h>
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/PROCESSING/ID/IDFilter.h>
#include <OpenMS/KERNEL/OnDiscMSExperiment.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DCaret.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DDistanceItem.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DItem.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/Plot1DWidget.h>
#include <OpenMS/VISUAL/SpectraIDViewTab.h>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/make_shared.hpp>
#include <QtWidgets/QMessageBox>
#include <QtCore/QString>
using namespace OpenMS;
using namespace std;
//#define DEBUG_IDENTIFICATION_VIEW
namespace OpenMS
{
TVIdentificationViewController::TVIdentificationViewController(TOPPViewBase* parent, SpectraIDViewTab* spec_id_view) :
TVControllerBase(parent),
spec_id_view_(spec_id_view)
{
}
void TVIdentificationViewController::showSpectrumAsNew1D(int index)
{
// Show spectrum "index" without selecting an identification
showSpectrumAsNew1D(index, -1, -1);
}
void TVIdentificationViewController::showSpectrumAsNew1D(int spectrum_index, int peptide_id_index, int peptide_hit_index)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "TVIdentificationViewController::showSpectrumAsNew1D() called" << endl;
#endif
// basic behavior 1
auto& layer = tv_->getActiveCanvas()->getCurrentLayer();
if (layer.type == LayerDataBase::DT_PEAK)
{
// open new 1D widget with the current default parameters
auto* w = new Plot1DWidget(tv_->getCanvasParameters(1), DIM::Y, (QWidget*)tv_->getWorkspace());
// copy data from current layer (keeps the TYPE and underlying data identical)
auto new_1d = layer.to1DLayer();
bool index_ok = new_1d->hasIndex(spectrum_index);
if (!index_ok || !w->canvas()->addLayer(std::move(new_1d)))
{
// Behavior if its neither (user may have clicked on an empty tree or a
// dummy entry as drawn by SpectraTreeTab::updateEntries)
QMessageBox::critical(w, "Error", "Cannot open data. Aborting!");
return;
}
w->canvas()->activateSpectrum(spectrum_index);
// set relative (%) view of visible area
w->canvas()->setIntensityMode(PlotCanvas::IM_SNAP);
// set visible area to visible area in 2D view
w->canvas()->setVisibleArea(tv_->getActiveCanvas()->getVisibleArea());
w->canvas()->getCurrentLayer().setName(layer.getName());
w->canvas()->getCurrentLayer().setNameSuffix(layer.getNameSuffix());
tv_->showPlotWidgetInWindow(w);
///////////////////////////////////////////////////////////////////////////////
// Visualization of ID data
// if no peptide identification or peptide hit index provided we can return now
if (peptide_id_index == -1 || peptide_hit_index == -1)
{
return;
}
// get peptide identification
auto layer_1d_peak = dynamic_cast<const LayerData1DPeak*>(&w->canvas()->getCurrentLayer());
const auto& pids = layer_1d_peak->getPeakData()->getPeptideIdentifications();
if (peptide_id_index >= static_cast<int>(pids.size()))
{
OPENMS_LOG_FATAL_ERROR << "PeptideIdentification index out of bounds! Aborting!" << endl;
return;
}
const PeptideIdentification& pi = pids[peptide_id_index];
switch (layer_1d_peak->getCurrentSpectrum().getMSLevel())
{
// mass fingerprint annotation of name etc.
case 1:
{
addPeakAnnotations_(PeptideIdentificationList(1, pi));
break;
}
// annotation with stored fragments or synthesized theoretical spectrum
case 2:
{
// check if index in bounds and hits are present
if (peptide_hit_index < static_cast<int>(pi.getHits().size()))
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Creating annotations for PeptideIdentification index: " << peptide_id_index << endl;
cout << "PeptideHit index: " << peptide_hit_index << endl;
cout << "PeptideHit: " << pi.getHits()[peptide_hit_index].getSequence().toString() << endl;
#endif
// get hit
PeptideHit ph = pi.getHits()[peptide_hit_index];
if (ph.getPeakAnnotations().empty())
{
// if no fragment annotations are stored, create a theoretical spectrum
addTheoreticalSpectrumLayer_(ph);
}
else
{
// otherwise, use stored fragment annotations
addPeakAnnotationsFromID_(ph);
}
}
break;
}
default:
OPENMS_LOG_WARN << "Annotation of MS level > 2 not supported.!" << endl;
}
// TODO Why would this need to trigger an update in e.g. the Tab Views??
tv_->updateLayerBar(); // todo replace
tv_->updateViewBar();
tv_->updateFilterBar();
tv_->updateMenu();
}
// else if (layer.type == LayerDataBase::DT_CHROMATOGRAM)
}
void TVIdentificationViewController::addPeakAnnotations_(const PeptideIdentificationList& ph)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "TVIdentificationViewController::addPeakAnnotations() called" << endl;
#endif
// called anew for every click on a spectrum
auto getCurrentLayer = [&]() -> LayerData1DPeak& { return dynamic_cast<LayerData1DPeak&>(tv_->getActive1DWidget()->canvas()->getCurrentLayer()); };
if (getCurrentLayer().getCurrentSpectrum().empty())
{
OPENMS_LOG_WARN << "Spectrum is empty! Nothing to annotate!" << endl;
}
// mass precision to match a peak's m/z to a feature m/z
// m/z values of features are usually an average over multiple scans...
constexpr double ppm = 0.5;
array<QColor, 5> cols{ Qt::blue, Qt::green, Qt::red, Qt::gray, Qt::darkYellow };
if (!getCurrentLayer().getCurrentSpectrum().isSorted())
{
QMessageBox::warning(tv_, "Error", "The spectrum is not sorted! Aborting!");
return;
}
for (PeptideIdentificationList::const_iterator it = ph.begin();
it!= ph.end();
++it)
{
if (!it->hasMZ())
{
continue;
}
double mz = it->getMZ();
Size peak_idx = getCurrentLayer().getCurrentSpectrum().findNearest(mz);
// m/z fits ?
if (Math::getPPMAbs(mz, getCurrentLayer().getCurrentSpectrum()[peak_idx].getMZ()) > ppm)
{
continue;
}
double peak_int = getCurrentLayer().getCurrentSpectrum()[peak_idx].getIntensity();
Annotation1DCaret<Peak1D>* first_dit(nullptr);
// we could have many hits for different compounds which have the exact same sum formula... so first group by sum formula
map<String, StringList> formula_to_names;
for (const PeptideHit& pep : it->getHits())
{
if (pep.metaValueExists("identifier") && pep.metaValueExists("chemical_formula"))
{
String name = pep.getMetaValue("identifier");
if (name.length() > 20)
{
name = name.substr(0, 17) + "...";
}
String cf = pep.getMetaValue("chemical_formula");
if (cf.empty())
{
continue; // skip unannotated "null" peaks
}
formula_to_names[cf].push_back(name);
}
else
{
StringList msg;
if (!pep.metaValueExists("identifier"))
{
msg.push_back("identifier");
}
if (!pep.metaValueExists("chemical_formula"))
{
msg.push_back("chemical_formula");
}
OPENMS_LOG_WARN << "Missing meta-value(s): " << ListUtils::concatenate(msg, ", ") << ". Cannot annotate!\n";
}
}
// assemble annotation (each formula gets a paragraph)
String text = "<html><body>";
Size i = 0;
for (map<String, StringList>::iterator ith = formula_to_names.begin();
ith!= formula_to_names.end(); ++ith)
{
if (++i == cols.size())
{ // at this point, this is the 4th entry.. which we don't show any more...
text += String("<b><span style=\"color:") + cols[i].name() + "\">..." + Size(distance(formula_to_names.begin(), formula_to_names.end()) - 4 + 1) + " more</span></b><br>";
break;
}
text += String("<b><span style=\"color:") + cols[i].name() + "\">" + ith->first + "</span></b><br>\n";
// carets for isotope profile
EmpiricalFormula ef(ith->first);
IsotopeDistribution id = ef.getIsotopeDistribution(CoarseIsotopePatternGenerator(3)); // three isotopes at most
double int_factor = peak_int / id.begin()->getIntensity();
Annotation1DCaret<Peak1D>::PositionsType points;
Size itic(0);
for (const Peak1D& iso : id)
{
points.push_back(Annotation1DCaret<Peak1D>::PointType(mz + itic * Constants::C13C12_MASSDIFF_U, iso.getIntensity() * int_factor));
++itic;
}
auto ditem = new Annotation1DCaret<Peak1D>(points,
QString(),
cols[i],
String(getCurrentLayer().param.getValue("peak_color").toString()).toQString());
ditem->setSelected(false);
temporary_annotations_.push_back(ditem); // for removal (no ownership)
getCurrentLayer().getCurrentAnnotations().push_front(ditem); // for visualization (ownership)
if (first_dit == nullptr)
{
first_dit = ditem; // remember first item (we append the text, when ready)
}
// list of compound names (shorten if required)
if (ith->second.size() > 3)
{
Size s = ith->second.size();
ith->second[3] = String("...") + (s-3) + " more";
ith->second.resize(4);
}
text += " - " + ListUtils::concatenate(ith->second, "<br> - ") + "<br>\n";
}
text += "</body></html>";
if (first_dit!=nullptr)
{
first_dit->setRichText(text.toQString());
}
}
}
void TVIdentificationViewController::activate1DSpectrum(int index)
{
activate1DSpectrum(index, -1, -1);
}
void TVIdentificationViewController::activate1DSpectrum(
int spectrum_index,
int peptide_id_index,
int peptide_hit_index)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "TVIdentificationViewController::activate1DSpectrum() called" << endl;
#endif
Plot1DWidget* widget_1D = tv_->getActive1DWidget();
// if no active 1D widget is present
if (widget_1D == nullptr)
{ // ... create one
showSpectrumAsNew1D(spectrum_index, peptide_id_index, peptide_hit_index);
return;
}
// lambda which returns the current layer. This has to be used throughout this function to ensure
// being up-to-date (no invalidated pointer etc.)
// even after adding a layer with e.g. addTheoreticalSpectrumLayer_ in L372.
auto current_layer = [&]() -> LayerData1DPeak& { return dynamic_cast<LayerData1DPeak&>(tv_->getActive1DWidget()->canvas()->getCurrentLayer()); };
widget_1D->canvas()->activateSpectrum(spectrum_index);
current_layer().peptide_id_index = peptide_id_index; // should always ne 0
current_layer().peptide_hit_index = peptide_hit_index;
if (current_layer().type == LayerDataBase::DT_PEAK)
{
UInt ms_level = current_layer().getCurrentSpectrum().getMSLevel();
const PeptideIdentification& pid = current_layer().getPeakData()->getPeptideIdentifications()[spectrum_index];
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "PeptideIdentification index: " << peptide_id_index << endl;
cout << "PeptideHit index: " << peptide_hit_index << endl;
cout << "PeptideHit: " << pid.getHits()[peptide_hit_index].getSequence().toString() << endl;
cout << "MS level: " << ms_level << endl;
cout << "Spectrum index: " << spectrum_index << endl;
#endif
switch (ms_level)
{
case 1: // mass fingerprint annotation of name etc and precursor labels
{
addPeakAnnotations_(PeptideIdentificationList(1, pid));
vector<Precursor> precursors;
// collect all MS2 spectra precursor till next MS1 spectrum is encountered
for (Size i = spectrum_index + 1; i < current_layer().getPeakData()->getMSExperiment().size(); ++i)
{
if (current_layer().getPeakData()->getMSExperiment()[i].getMSLevel() == 1)
{
break;
}
// skip MS2 without precursor
if (current_layer().getPeakData()->getMSExperiment()[i].getPrecursors().empty())
{
continue;
}
// there should be only one precursor per MS2 spectrum.
vector<Precursor> pcs = current_layer().getPeakData()->getMSExperiment()[i].getPrecursors();
copy(pcs.begin(), pcs.end(), back_inserter(precursors));
}
addPrecursorLabels1D_(precursors);
break;
}
case 2: // annotation with stored fragments or synthesized theoretical spectrum
{
// get selected hit
PeptideHit ph = pid.getHits()[peptide_hit_index];
if (ph.getPeakAnnotations().empty())
{
// if no fragment annotations are stored, create a theoretical spectrum
addTheoreticalSpectrumLayer_(ph);
// synchronize PeptideHits with the annotations in the spectrum
current_layer().synchronizePeakAnnotations();
// remove labels and theoretical spectrum (will be recreated using PH annotations)
removeGraphicalPeakAnnotations_(spectrum_index);
removeTheoreticalSpectrumLayer_();
// return if no active 1D widget is present
if (widget_1D == nullptr)
{
return;
}
// update current PeptideHit with the synchronized one
widget_1D->canvas()->activateSpectrum(spectrum_index);
const PeptideIdentification & pi2 = current_layer().getPeakData()->getPeptideIdentifications()[spectrum_index];
ph = pi2.getHits()[peptide_hit_index];
}
// use stored fragment annotations
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Creating annotations for PeptideIdentification index: " << peptide_id_index << endl;
cout << "PeptideHit index: " << peptide_hit_index << endl;
cout << "PeptideHit: " << ph.getSequence().toString() << endl;
#endif
addPeakAnnotationsFromID_(ph);
if (ph.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TYPE)) // if this meta value exists, this should be an XL-MS annotation
{
String box_text;
String vert_bar = "|";
if (ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) == "loop-link")
{
String hor_bar = "_";
String seq_alpha = ph.getSequence().toUnmodifiedString();
int xl_pos_alpha = String(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1)).toInt();
int xl_pos_beta = String(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2)).toInt() - xl_pos_alpha - 1;
String alpha_cov;
String beta_cov;
extractCoverageStrings(ph.getPeakAnnotations(), alpha_cov, beta_cov, seq_alpha.size(), 0);
// String formatting
box_text += alpha_cov + "<br>" + seq_alpha + "<br>" + String(xl_pos_alpha, ' ') + vert_bar + n_times(xl_pos_beta, hor_bar) + vert_bar;
// cut out line: "<br>" + String(xl_pos_alpha, ' ') + vert_bar + String(xl_pos_beta, ' ') + vert_bar +
}
else if (ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) == "cross-link")
{
String seq_alpha = ph.getSequence().toUnmodifiedString();
String seq_beta = AASequence::fromString(ph.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE)).toUnmodifiedString();
int xl_pos_alpha = String(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1)).toInt();
int xl_pos_beta = String(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2)).toInt();
// String formatting
Size prefix_length = max(xl_pos_alpha, xl_pos_beta);
//Size suffix_length = max(seq_alpha.size() - xl_pos_alpha, seq_beta.size() - xl_pos_beta);
Size alpha_space = prefix_length - xl_pos_alpha;
Size beta_space = prefix_length - xl_pos_beta;
String alpha_cov;
String beta_cov;
extractCoverageStrings(ph.getPeakAnnotations(), alpha_cov, beta_cov, seq_alpha.size(), seq_beta.size());
box_text += String(alpha_space, ' ') + alpha_cov + "<br>" + String(alpha_space, ' ') + seq_alpha + "<br>" + String(prefix_length, ' ') + vert_bar + "<br>" + String(beta_space, ' ') + seq_beta + "<br>" + String(beta_space, ' ') + beta_cov;
// color: <font color=\"green\">└</font>
}
else // if (ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) == "mono-link")
{
String seq_alpha = ph.getSequence().toUnmodifiedString();
int xl_pos_alpha = String(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1)).toInt();
Size prefix_length = xl_pos_alpha;
String alpha_cov;
String beta_cov;
extractCoverageStrings(ph.getPeakAnnotations(), alpha_cov, beta_cov, seq_alpha.size(), 0);
box_text += alpha_cov + "<br>" + seq_alpha + "<br>" + String(prefix_length, ' ') + vert_bar;
}
box_text = R"(<font size="5" style="background-color:white;"><pre>)" + box_text + "</pre></font> ";
widget_1D->canvas()->setTextBox(box_text.toQString());
}
else if (ph.getPeakAnnotations().empty()) // only write the sequence
{
String seq = ph.getSequence().toString();
if (seq.empty())
{
seq = ph.getMetaValue("label"); // e.g. for RNA sequences
}
widget_1D->canvas()->setTextBox(seq.toQString());
}
else if (widget_1D->canvas()->isIonLadderVisible())
{
if (!ph.getSequence().empty()) // generate sequence diagram for a peptide
{
// @TODO: read ion list from the input file (meta value)
static vector<String> top_ions = ListUtils::create<String>("a,b,c");
static vector<String> bottom_ions = ListUtils::create<String>("x,y,z");
String diagram = generateSequenceDiagram_(
ph.getSequence(),
ph.getPeakAnnotations(),
top_ions,
bottom_ions);
widget_1D->canvas()->setTextBox(diagram.toQString());
}
else if (ph.metaValueExists("label")) // generate sequence diagram for RNA
{
try
{
// @TODO: read ion list from the input file (meta value)
NASequence na_seq = NASequence::fromString(ph.getMetaValue("label"));
static vector<String> top_ions = ListUtils::create<String>("a-B,a,b,c,d");
static vector<String> bottom_ions = ListUtils::create<String>("w,x,y,z");
String diagram = generateSequenceDiagram_(na_seq, ph.getPeakAnnotations(),
top_ions, bottom_ions);
widget_1D->canvas()->setTextBox(diagram.toQString());
}
catch (Exception::ParseError&) // label doesn't contain have a valid seq.
{
}
}
}
break;
}
default:
OPENMS_LOG_WARN << "Annotation of MS level > 2 not supported." << endl;
}
} // end DT_PEAK
// else if (current_layer().type == LayerDataBase::DT_CHROMATOGRAM)
}
// Helper function for text formatting
String TVIdentificationViewController::n_times(Size n, const String& input)
{
String result;
for (Size i = 0; i < n; ++i)
{
result.append(input);
}
return result;
}
// Helper function that collapses a vector of strings into one string
String TVIdentificationViewController::collapseStringVector(vector<String> strings)
{
String result;
for (Size i = 0; i < strings.size(); ++i)
{
result.append(strings[i]);
}
return result;
}
// Helper function that turns fragment annotations into coverage strings for visualization with the sequence
void TVIdentificationViewController::extractCoverageStrings(vector<PeptideHit::PeakAnnotation> frag_annotations, String& alpha_string, String& beta_string, Size alpha_size, Size beta_size)
{
vector<String> alpha_strings(alpha_size, " ");
vector<String> beta_strings(beta_size, " ");
// vectors to keep track of assigned symbols, 0 = nothing, -1 = left, 1 = right, 2 = both
vector<int> alpha_direction(alpha_size, 0);
vector<int> beta_direction(beta_size, 0);
for (Size i = 0; i < frag_annotations.size(); ++i)
{
bool has_alpha = frag_annotations[i].annotation.hasSubstring(String("alpha|"));
bool has_beta = frag_annotations[i].annotation.hasSubstring(String("beta|"));
// if it has both, it is a complex fragment and more difficult to parse
// those are ignored for the coverage indicator for now
if ( has_alpha != has_beta )
{
vector<String> dol_split;
frag_annotations[i].annotation.split("$", dol_split);
vector<String> bar_split;
dol_split[0].split("|", bar_split);
bool alpha = bar_split[0] == "[alpha";
bool ci = bar_split[1] == "ci";
vector<String> loss_split;
dol_split[1].split("-", loss_split);
// remove b / y ion type letter (must be at first position of second string after $-split)
String pos_string = loss_split[0].suffix(loss_split[0].size()-1);
int pos;
if (pos_string.hasSubstring("]")) // this means the loss_split with "-" did not split the string
{
// remove the "]" and possible charges at its right side
vector<String> pos_split;
pos_string.split("]", pos_split);
pos_string = pos_split[0];
pos = pos_string.toInt()-1;
}
else // loss was found and splitted, so the remaining string is just the position
{
pos = pos_string.toInt()-1;
}
String frag_type = dol_split[1][0];
//bool left = (frag_type == "a" || frag_type == "b" || frag_type == "c");
int direction;
if (frag_type == "a" || frag_type == "b" || frag_type == "c")
{
direction = -1;
}
else
{
direction = 1;
}
if (direction == 1)
{
if (alpha)
{
pos = alpha_size - pos - 1;
}
else
{
pos = beta_size - pos - 1;
}
}
String arrow;
if (ci)
{
arrow += "<font color=\"green\">";
}
else
{
arrow += "<font color=\"red\">";
}
if (direction == -1)
{
arrow += "↼</font>";
}
else
{
arrow += "⇁</font>";
}
if (alpha)
{
if (alpha_direction[pos] == 0) // no arrow assigned yet
{
alpha_strings[pos] = arrow;
alpha_direction[pos] = direction;
}
else if (alpha_direction[pos] != direction && alpha_direction[pos] != 2) // assigned arrow has different direction, make bidirectional arrow
{
alpha_strings[pos] = String("<font color=\"blue\">⇋</font>");
alpha_direction[pos] = 2;
} // otherwise an arrow with the correct direction is already assigned
}
else
{
if (beta_direction[pos] == 0) // no arrow assigned yet
{
beta_strings[pos] = arrow;
beta_direction[pos] = direction;
}
else if (beta_direction[pos] != direction && beta_direction[pos] != 2) // assigned arrow has different direction, make bidirectional arrow
{
beta_strings[pos] = String("<font color=\"blue\">⇋</font>");
beta_direction[pos] = 2;
} // otherwise an arrow with the correct direction is already assigned
}
}
}
alpha_string = "<font style=\"\">" + collapseStringVector(alpha_strings) + "</font>";
beta_string = collapseStringVector(beta_strings);
}
void TVIdentificationViewController::generateSequenceRow_(const AASequence& seq, vector<String>& row)
{
// @TODO: spell out modifications or just use an indicator like "*"?
// @TODO: support "user defined modifications"?
if (seq.hasNTerminalModification())
{
row[0] = + "." + seq.getNTerminalModificationName();
}
Size col_index = 1;
for (const auto& aa : seq)
{
row[col_index] = "<b>" + aa.getOneLetterCode();
if (aa.isModified())
{
row[col_index] += "(" + aa.getModificationName() + ")";
}
row[col_index] += "</b>";
col_index += 2;
}
if (seq.hasCTerminalModification())
{
row[row.size() - 1] = "." + seq.getCTerminalModificationName();
}
}
void TVIdentificationViewController::generateSequenceRow_(const NASequence& seq, vector<String>& row)
{
if (seq.hasFivePrimeMod())
{
const String& code = seq.getFivePrimeMod()->getCode();
row[0] = (code == "5'-p" ? "p" : code);
}
Size col_index = 1;
for (const auto& ribo : seq)
{
row[col_index] = "<b>" + ribo.getCode() + "</b>";
col_index += 2;
}
if (seq.hasThreePrimeMod())
{
const String& code = seq.getThreePrimeMod()->getCode();
row[row.size() - 1] = (code == "3'-p" ? "p" : code);
}
}
template <typename SeqType>
String TVIdentificationViewController::generateSequenceDiagram_(
const SeqType& seq,
const vector<PeptideHit::PeakAnnotation>& annotations,
const vector<String>& top_ions,
const vector<String>& bottom_ions)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Generating Sequence Diagram: " << endl;
#endif
map<String, set<Size>> ion_pos;
for (const auto& ann : annotations)
{
const String& label = ann.annotation;
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Adding Peak Annotation to Diagram: " << label << endl;
#endif
// expected format: [ion][number][...]
if ((label.size() < 2) || !islower(label[0]) || !isdigit(label[1]))
{
continue;
}
// cut out the position number:
Size split = label.find_first_not_of("0123456789", 2);
String ion = label.prefix(1);
// special case for RNA: "a[n]-B", where "[n]" is the ion number
// -> don't forget to add the "-B" back on if it's there:
String more_ion = label.substr(split);
if (more_ion == "-B")
{
ion += more_ion;
}
Size pos = label.substr(1, split - 1).toInt();
ion_pos[ion].insert(pos);
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Ion: " << ion << " pos: " << pos << endl;
#endif
}
vector<vector<String>> table; // vector of rows
table.resize(top_ions.size() + bottom_ions.size() + 3);
Size n_cols = seq.size() * 2 + 1;
for (auto& row : table)
{
row.resize(n_cols);
}
if (!top_ions.empty())
{
for (Size i = 1; i < seq.size(); ++i)
{
// @TODO: check spacing for i > 9
table[0][i * 2] = "<small>" + String(i) + "</small>";
}
}
Size row_index = 1;
// ion annotations above sequence - reverse order to have first ion closest to sequence:
for (const String& ion : boost::adaptors::reverse(top_ions))
{
table[row_index][0] = "<small>" + ion + "</small>";
for (Size pos : ion_pos[ion])
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Found ion: " << ion << " pos: " << pos << endl;
#endif
Size col_index = 2 * pos;
if ((row_index == 1) || (table[row_index - 1][col_index].empty()))
{
table[row_index][col_index] = "┐"; // box drawing: down and left
}
else
{
table[row_index][col_index] = "┤"; // box drawing: vertical and left
}
table[row_index][col_index - 1] = "╶"; // box drawing: right
}
if (row_index > 1)
{
for (Size col_index = 2; col_index < n_cols - 2; col_index += 2)
{
if (table[row_index][col_index].empty() && !table[row_index - 1][col_index].empty())
{
table[row_index][col_index] = "│"; // box drawing: vertical
}
}
}
++row_index;
}
// sequence itself:
generateSequenceRow_(seq, table[row_index]);
// ion annotations below sequence - iterate over the bottom ions in reverse order (bottom-most first):
row_index = table.size() - 2;
for (const String& ion : boost::adaptors::reverse(bottom_ions))
{
table[row_index][n_cols - 1] = "<small>" + ion + "<small>";
for (Size pos : ion_pos[ion])
{
Size col_index = n_cols - 2 * pos - 1;
if ((row_index == table.size() - 1) || (table[row_index + 1][col_index].empty()))
{
table[row_index][col_index] = "└"; // box drawing: up and right
}
else
{
table[row_index][col_index] = "├"; // box drawing: vertical and right
}
table[row_index][col_index + 1] = "╴"; // box drawing: left
}
if (row_index < table.size() - 2)
{
for (Size col_index = 2; col_index < n_cols - 2; col_index += 2)
{
if (table[row_index][col_index].empty() && !table[row_index + 1][col_index].empty())
{
table[row_index][col_index] = "│"; // box drawing: vertical
}
}
}
--row_index;
}
// "row_index" is again at the sequence row - fill in "split indicators":
for (Size col_index = 2; col_index < n_cols - 2 ; col_index += 2)
{
bool top = !top_ions.empty() && !table[row_index - 1][col_index].empty();
bool bottom = !bottom_ions.empty() && !table[row_index + 1][col_index].empty();
if (top && bottom)
{
table[row_index][col_index] = "│"; // box drawing: vertical
}
else if (top)
{
table[row_index][col_index] = "╵"; // box drawing: up
}
else if (bottom)
{
table[row_index][col_index] = "╷"; // box drawing: down
}
}
if (!bottom_ions.empty())
{
for (Size i = 1; i < seq.size(); ++i)
{
// @TODO: check spacing in diagram for i > 9
table[table.size() - 1][n_cols - 2 * i - 1] = "<small>" + String(i) + "</small>";
}
}
String html = "<table cellspacing=\"0\">";
for (const auto& row : table)
{
html += "<tr>";
for (const String& cell : row)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "cell: '" << cell << "'" << endl;
#endif
html += "<td align=\"center\">" + cell + "</td>";
}
html += "</tr>";
}
html += "</table>";
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Generated html:\n" << html << endl;
#endif
return html;
}
// add specializations to allow template implementation outside of header file:
template String TVIdentificationViewController::generateSequenceDiagram_<AASequence>(const AASequence& seq, const vector<PeptideHit::PeakAnnotation>& annotations, const StringList& top_ions, const StringList& bottom_ions);
template String TVIdentificationViewController::generateSequenceDiagram_<NASequence>(const NASequence& seq, const vector<PeptideHit::PeakAnnotation>& annotations, const StringList& top_ions, const StringList& bottom_ions);
void TVIdentificationViewController::addPrecursorLabels1D_(const vector<Precursor>& pcs)
{
auto& current_layer = dynamic_cast<LayerData1DPeak&>(tv_->getActive1DWidget()->canvas()->getCurrentLayer());
if (current_layer.type == LayerDataBase::DT_PEAK)
{
const SpectrumType& spectrum = current_layer.getCurrentSpectrum();
for (const Precursor& pre : pcs)
{
// determine start and stop of isolation window
double center_mz = pre.metaValueExists("isolation window target m/z") ?
double(pre.getMetaValue("isolation window target m/z")) : pre.getMZ();
double isolation_window_lower_mz = center_mz - pre.getIsolationWindowLowerOffset();
double isolation_window_upper_mz = center_mz + pre.getIsolationWindowUpperOffset();
// determine maximum peak intensity in isolation window
SpectrumType::const_iterator vbegin = spectrum.MZBegin(isolation_window_lower_mz);
SpectrumType::const_iterator vend = spectrum.MZEnd(isolation_window_upper_mz);
double max_intensity = (numeric_limits<double>::min)();
for (; vbegin != vend; ++vbegin)
{
if (vbegin->getIntensity() > max_intensity)
{
max_intensity = vbegin->getIntensity();
}
}
// DPosition<2> precursor_position = DPosition<2>(it->getMZ(), max_intensity);
DPosition<2> lower_position = DPosition<2>(isolation_window_lower_mz, max_intensity);
DPosition<2> upper_position = DPosition<2>(isolation_window_upper_mz, max_intensity);
Annotation1DDistanceItem* item = new Annotation1DDistanceItem(QString::number(pre.getCharge()), lower_position, upper_position);
// add additional tick at precursor target position (e.g. to show if isolation window is asymmetric)
vector<PointXYType> ticks;
ticks.emplace_back(pre.getMZ(), 0);
item->setTicks(ticks);
item->setSelected(false);
temporary_annotations_.push_back(item); // for removal (no ownership)
current_layer.getCurrentAnnotations().push_front(item); // for visualization (ownership)
}
}
else if (current_layer.type == LayerDataBase::DT_CHROMATOGRAM)
{
}
}
void TVIdentificationViewController::removeTemporaryAnnotations_(Size spectrum_index)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "removePrecursorLabels1D_ " << spectrum_index << endl;
#endif
// Delete annotations added by IdentificationView (but not user added annotations)
auto& current_layer = tv_->getActive1DWidget()->canvas()->getCurrentLayer();
const vector<Annotation1DItem*>& cas = temporary_annotations_;
Annotations1DContainer& las = current_layer.getAnnotations(spectrum_index);
for (vector<Annotation1DItem*>::const_iterator it = cas.begin(); it != cas.end(); ++it)
{
Annotations1DContainer::iterator i = find(las.begin(), las.end(), *it);
if (i != las.end())
{
delete(*i);
las.erase(i);
}
}
temporary_annotations_.clear();
}
void TVIdentificationViewController::addTheoreticalSpectrumLayer_(const PeptideHit& ph)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Adding theoretical spectrum layer" << endl;
#endif
PlotCanvas* current_canvas = tv_->getActive1DWidget()->canvas();
auto& current_layer = dynamic_cast<LayerData1DPeak&>(current_canvas->getCurrentLayer());
const SpectrumType& current_spectrum = current_layer.getCurrentSpectrum();
const AASequence& aa_sequence = ph.getSequence();
// get measured spectrum indices and spectrum
Size current_spectrum_layer_index = current_canvas->getCurrentLayerIndex();
Size current_spectrum_index = current_layer.getCurrentIndex();
const Param& tv_params = tv_->getParameters();
Param tag_params = tv_params.copy("preferences:user:idview:tsg:", true);
// override: enable metavalues for simulated peaks (needed for annotation)
assert(tag_params.exists("add_metainfo"));
tag_params.setValue("add_metainfo", "true");
PeakSpectrum theo_spectrum;
try
{
TheoreticalSpectrumGenerator generator;
Int max_charge = max(1, ph.getCharge()); // at least generate charge 1 if no charge (0) is annotated
// generate mass ladder for all charge states
generator.setParameters(tag_params);
generator.getSpectrum(theo_spectrum, aa_sequence, 1, max_charge);
// scale spectrum to maximum peak intensity of real spectrum
auto scale_by = current_spectrum.getMaxIntensity();
std::for_each(theo_spectrum.begin(), theo_spectrum.end(), [scale_by](Peak1D& p) { p.setIntensity(p.getIntensity() * scale_by); });
}
catch (Exception::BaseException& e)
{
QMessageBox::warning(tv_, "Error", QString("Spectrum generation failed! (") + e.what() + "). Please report this to the developers (specify what input you used)!");
return;
}
// Block update events for identification widget
spec_id_view_->ignore_update = true;
RAIICleanup cleanup([&]() { spec_id_view_->ignore_update = false; });
ExperimentSharedPtrType new_exp_sptr = std::make_shared<AnnotatedMSRun>();
new_exp_sptr->getMSExperiment().addSpectrum(theo_spectrum);
LayerDataBase::ODExperimentSharedPtrType od_dummy(new OnDiscMSExperiment());
String layer_caption = aa_sequence.toString() + " (identification view)";
current_canvas->addPeakLayer(new_exp_sptr, od_dummy, layer_caption);
// get layer index of new layer
Size theoretical_spectrum_layer_index = tv_->getActive1DWidget()->canvas()->getCurrentLayerIndex();
// kind of a hack to check whether adding the layer was successful
if (current_spectrum_layer_index != theoretical_spectrum_layer_index && !theo_spectrum.getStringDataArrays().empty())
{
// Ensure theoretical spectrum is drawn as dashed sticks
tv_->setDrawMode1D(Plot1DCanvas::DM_PEAKS);
tv_->getActive1DWidget()->canvas()->setCurrentLayerPeakPenStyle(Qt::DashLine);
// Add ion names as annotations to the theoretical spectrum
PeakSpectrum::StringDataArray sa = theo_spectrum.getStringDataArrays()[0];
for (Size i = 0; i != theo_spectrum.size(); ++i)
{
Peak1D position(theo_spectrum[i].getMZ(), theo_spectrum[i].getIntensity());
QString s(sa[i].c_str());
if (s.at(0) == 'y')
{
auto item = new Annotation1DPeakItem<Peak1D>(position, s, Qt::darkRed);
item->setSelected(false);
tv_->getActive1DWidget()->canvas()->getCurrentLayer().getCurrentAnnotations().push_front(item);
}
else if (s.at(0) == 'b')
{
auto item = new Annotation1DPeakItem<Peak1D>(position, s, Qt::darkGreen);
item->setSelected(false);
tv_->getActive1DWidget()->canvas()->getCurrentLayer().getCurrentAnnotations().push_front(item);
}
}
// remove theoretical and activate real data layer and spectrum
tv_->getActive1DWidget()->canvas()->changeVisibility(theoretical_spectrum_layer_index, false);
tv_->getActive1DWidget()->canvas()->activateLayer(current_spectrum_layer_index);
tv_->getActive1DWidget()->canvas()->getCurrentLayer().setCurrentIndex(current_spectrum_index);
// zoom to maximum visible area in real data (as theoretical might be much larger and therefor squeezes the interesting part)
auto spec_range = tv_->getActive1DWidget()->canvas()->getCurrentLayer().getRange();
spec_range.scaleBy(1.2);
tv_->getActive1DWidget()->canvas()->setVisibleArea(RangeAllType().assign(spec_range));
// spectra alignment
Param p_align = tv_params.copy("preferences:user:idview:align", true);
tv_->getActive1DWidget()->performAlignment(current_spectrum_layer_index, theoretical_spectrum_layer_index, p_align);
vector<pair<Size, Size> > aligned_peak_indices = tv_->getActive1DWidget()->canvas()->getAlignedPeaksIndices();
// annotate original spectrum with ions and sequence
for (Size i = 0; i != aligned_peak_indices.size(); ++i)
{
PeakIndex pi(current_spectrum_index, aligned_peak_indices[i].first);
QString s(sa[aligned_peak_indices[i].second].c_str());
QString ion_nr_string = s;
if (s.at(0) == 'y')
{
ion_nr_string.replace("y", "");
ion_nr_string.replace("+", "");
Size ion_number = ion_nr_string.toUInt();
s.append("\n");
// extract peptide ion sequence
QString aa_ss;
for (Size j = aa_sequence.size() - 1; j >= aa_sequence.size() - ion_number; --j)
{
const Residue& r = aa_sequence.getResidue(j);
aa_ss.append(r.getOneLetterCode().toQString());
if (r.isModified())
{
aa_ss.append("*");
}
}
s.append(aa_ss);
Annotation1DItem* item = tv_->getActive1DWidget()->canvas()->addPeakAnnotation(pi, s, Qt::darkRed);
temporary_annotations_.push_back(item);
}
else if (s.at(0) == 'b')
{
ion_nr_string.replace("b", "");
ion_nr_string.replace("+", "");
UInt ion_number = ion_nr_string.toUInt();
s.append("\n");
// extract peptide ion sequence
AASequence aa_subsequence = aa_sequence.getSubsequence(0, ion_number);
QString aa_ss = aa_subsequence.toString().toQString();
// shorten modifications "(MODNAME)" to "*"
aa_ss.replace(QRegularExpression("[(].*[)]"), "*");
// append to label
s.append(aa_ss);
Annotation1DItem* item = tv_->getActive1DWidget()->canvas()->addPeakAnnotation(pi, s, Qt::darkGreen);
// save label for later removal
temporary_annotations_.push_back(item);
}
else
{
s.append("\n");
Annotation1DItem* item = tv_->getActive1DWidget()->canvas()->addPeakAnnotation(pi, s, Qt::black);
// save label for later removal
temporary_annotations_.push_back(item);
}
}
tv_->updateLayerBar();
}
}
void TVIdentificationViewController::removeGraphicalPeakAnnotations_(int spectrum_index)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Removing graphical peak annotations." << endl;
#endif
auto* widget_1D = tv_->getActive1DWidget();
auto& current_layer = widget_1D->canvas()->getCurrentLayer();
// remove all graphical peak annotations as these will be recreated from the stored peak annotations
Annotations1DContainer& las = current_layer.getAnnotations(spectrum_index);
auto new_end = remove_if(las.begin(), las.end(),
[](const Annotation1DItem* a)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << a->getText().toStdString() << endl;
#endif
return dynamic_cast<const Annotation1DPeakItem<Peak1D>*>(a) != nullptr;
});
las.erase(new_end, las.end());
return;
}
void TVIdentificationViewController::deactivate1DSpectrum(int spectrum_index)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Deactivating 1D spectrum with index: " << spectrum_index << endl;
#endif
// Retrieve active 1D widget
Plot1DWidget* widget_1D = tv_->getActive1DWidget();
// Return if none present
if (widget_1D == nullptr)
{
return;
}
auto& current_layer = widget_1D->canvas()->getCurrentLayer();
// Return if no valid peak layer attached
auto* current_layer_ptr = dynamic_cast<LayerData1DPeak*>(¤t_layer);
if (!current_layer_ptr || current_layer_ptr->getPeakData()->getMSExperiment().empty())
{
return;
}
MSSpectrum& spectrum = (*current_layer_ptr->getPeakDataMuteable()).getMSExperiment()[spectrum_index];
int ms_level = spectrum.getMSLevel();
if (ms_level == 2)
{
// synchronize PeptideHits with the annotations in the spectrum
current_layer_ptr->synchronizePeakAnnotations();
removeGraphicalPeakAnnotations_(spectrum_index);
removeTheoreticalSpectrumLayer_();
}
removeTemporaryAnnotations_(spectrum_index);
// reset selected id indices
current_layer.peptide_id_index = -1;
current_layer.peptide_hit_index = -1;
widget_1D->canvas()->setTextBox(QString());
}
void TVIdentificationViewController::addPeakAnnotationsFromID_(const PeptideHit& hit)
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Adding peak annotations from ID" << endl;
#endif
// get annotations and sequence
const vector<PeptideHit::PeakAnnotation>& annotations =
hit.getPeakAnnotations();
String seq = hit.getSequence().toString();
if (seq.empty())
{ // no sequence information stored? use label
if (hit.metaValueExists("label"))
{
seq = hit.getMetaValue("label");
}
}
auto* current_canvas = tv_->getActive1DWidget()->canvas();
LayerDataBase& current_layer = current_canvas->getCurrentLayer();
auto& current_layer2 = dynamic_cast<LayerData1DPeak&>(current_layer);
const MSSpectrum& current_spectrum = current_layer2.getCurrentSpectrum();
if (current_spectrum.empty())
{
OPENMS_LOG_WARN << "Spectrum is empty! Nothing to annotate!" << endl;
}
else if (!current_spectrum.isSorted())
{
QMessageBox::warning(tv_, "Error", "The spectrum is not sorted! Aborting!"); // @TODO: improve error message
return;
}
// init all peak colors to black (=no annotation)
current_layer2.peak_colors_1d.assign(current_spectrum.size(), Qt::black);
for (const auto& ann : annotations)
{
// find matching peak in experimental spectrum
Int peak_idx = current_spectrum.findNearest(ann.mz, 1e-2);
if (peak_idx == -1) // no match
{
OPENMS_LOG_WARN << "Annotation present for missing peak. m/z: " << ann.mz
<< endl;
continue;
}
String label = ann.annotation;
label.trim();
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Adding annotation item based on fragment annotations: " << label << endl;
#endif
QStringList lines = label.toQString().split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts);
if (lines.size() > 1)
{
label = String(lines[0]);
}
// write out positive and negative charges with the correct sign at the end of the annotation string
switch (ann.charge)
{
case 0: break;
case 1: label += "+"; break;
case 2: label += "++"; break;
case -1: label += "-"; break;
case -2: label += "--"; break;
default: label += ((ann.charge > 0) ? "+" : "") + String(ann.charge);
}
QColor color(Qt::black);
QColor peak_color(Qt::black);
// XL-MS specific coloring of the labels, green for linear fragments and red for cross-linked fragments
if (label.hasSubstring("[alpha|")
|| label.hasSubstring("[beta|"))
{
if (label.hasSubstring("|ci$"))
{
color = Qt::darkGreen;
peak_color = Qt::green;
}
else if (label.hasSubstring("|xi$"))
{
color = Qt::darkRed;
peak_color = Qt::red;
}
}
else
{ // different colors for left/right fragments (e.g. b/y ions)
color = (label.at(0) < 'n') ? Qt::darkRed : Qt::darkGreen;
peak_color = (label.at(0) < 'n') ? Qt::red : Qt::green;
}
Peak1D position(current_spectrum[peak_idx].getMZ(),
current_spectrum[peak_idx].getIntensity());
if (lines.size() > 1)
{
label.append("\n").append(String(lines[1]));
}
auto item = new Annotation1DPeakItem<Peak1D>(
position,
label.toQString(),
color);
// set peak color
current_layer2.peak_colors_1d[peak_idx] = peak_color;
item->setSelected(false);
tv_->getActive1DWidget()->canvas()->getCurrentLayer().getCurrentAnnotations().push_front(item);
}
// Block update events for identification widget
// TODO: Why? If it is to avoid a new selection while repainting, why just do it now and not much earlier??
spec_id_view_->ignore_update = true;
RAIICleanup cleanup([&]() {spec_id_view_->ignore_update = false; });
// zoom visible area to real data range:
auto spec_range = current_layer.getRange();
spec_range.scaleBy(1.2);
tv_->getActive1DWidget()->canvas()->setVisibleArea(RangeAllType().assign(spec_range));
tv_->updateLayerBar();
}
void TVIdentificationViewController::removeTheoreticalSpectrumLayer_()
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Removing theoretical spectrum layer" << endl;
#endif
auto* spectrum_widget_1D = tv_->getActive1DWidget();
if (spectrum_widget_1D)
{
Plot1DCanvas* canvas_1D = spectrum_widget_1D->canvas();
// Find the automatically generated layer with theoretical spectrum and remove it and the associated alignment.
// before activating the next normal spectrum
Size lc = canvas_1D->getLayerCount();
for (Size i = 0; i != lc; ++i)
{
String ln = canvas_1D->getLayerName(i);
if (ln.hasSubstring("(identification view)"))
{
canvas_1D->removeLayer(i);
canvas_1D->resetAlignment();
tv_->updateLayerBar();
break;
}
}
}
}
// override
void TVIdentificationViewController::activateBehavior()
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Activating identification view" << endl;
#endif
Plot1DWidget* w = tv_->getActive1DWidget();
if (w == nullptr)
{
return;
}
auto* current_canvas = w->canvas();
auto& current_layer = dynamic_cast<LayerData1DPeak&>(current_canvas->getCurrentLayer());
const SpectrumType& current_spectrum = current_layer.getCurrentSpectrum();
// find first MS2 spectrum with peptide identification and set current spectrum to it
if (current_spectrum.getMSLevel() == 1) // no fragment spectrum
{
for (Size i = 0; i < current_layer.getPeakData()->getMSExperiment().size(); ++i)
{
UInt ms_level = current_layer.getPeakData()->getMSExperiment()[i].getMSLevel();
if (ms_level != 2) continue;
const PeptideIdentificationList& peptide_ids = current_layer.getPeakData()->getPeptideIdentifications();
if (i >= peptide_ids.size())
{
OPENMS_LOG_FATAL_ERROR << "Peptide identification index out of bounds!" << endl;
}
const PeptideIdentification& peptide_id = peptide_ids[i];
if (peptide_id.getHits().empty()) // skip spectra with no identification
{
continue;
}
OPENMS_LOG_DEBUG << "During activation, found first MS2 spectrum with peptide identification: " << i << endl;
current_layer.setCurrentIndex(i);
break;
}
}
}
// override
void TVIdentificationViewController::deactivateBehavior()
{
#ifdef DEBUG_IDENTIFICATION_VIEW
cout << "Deactivating identification view" << endl;
#endif
Plot1DWidget* widget_1D = tv_->getActive1DWidget();
// return if no active 1D widget is present
if (widget_1D == nullptr)
{
return;
}
// clear textbox
widget_1D->canvas()->setTextBox(QString());
// remove precursor labels, theoretical spectra and trigger repaint
auto cl = dynamic_cast<LayerData1DPeak*> (&tv_->getActive1DWidget()->canvas()->getCurrentLayer());
if (!cl) return;
removeTemporaryAnnotations_(cl->getCurrentIndex());
removeTheoreticalSpectrumLayer_();
cl->peptide_id_index = -1;
cl->peptide_hit_index = -1;
tv_->getActive1DWidget()->canvas()->repaint();
}
void TVIdentificationViewController::setVisibleArea1D(double l, double h)
{
Plot1DWidget* widget_1D = tv_->getActive1DWidget();
// return if no active 1D widget is present
if (widget_1D == nullptr)
{
return;
}
DRange<2> range = tv_->getActive1DWidget()->canvas()->getVisibleArea().getAreaXY();
range.setMinX(l);
range.setMaxX(h);
tv_->getActive1DWidget()->canvas()->setVisibleArea(range);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASResource.cpp | .cpp | 1,838 | 86 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#include <iostream>
#include <OpenMS/VISUAL/TOPPASResource.h>
namespace OpenMS
{
QStringList TOPPASResource::supported_schemes = (QStringList() << "file");
TOPPASResource::TOPPASResource(const QString & file) :
QObject(),
url_(),
file_name_("")
{
fromLocalFile(file);
}
TOPPASResource::TOPPASResource(const QUrl & url) :
QObject(),
url_(),
file_name_("")
{
QString scheme = url.scheme().toLower();
if (!supported_schemes.contains(scheme))
{
std::cerr << "URL scheme not supported!" << std::endl;
}
else
{
url_ = url;
if (scheme == "file")
{
file_name_ = url.toLocalFile();
}
}
}
TOPPASResource::TOPPASResource(const TOPPASResource & rhs) :
QObject(),
url_(rhs.url_),
file_name_(rhs.file_name_)
{
}
TOPPASResource::~TOPPASResource() = default;
TOPPASResource & TOPPASResource::operator=(const TOPPASResource & rhs)
{
url_ = rhs.url_;
file_name_ = rhs.file_name_;
return *this;
}
void TOPPASResource::writeToFile(const QString & file_name)
{
// TODO retrieve data and write it to file_name
file_name_ = file_name;
}
const QString & TOPPASResource::getLocalFile() const
{
return file_name_;
}
const QUrl & TOPPASResource::getURL() const
{
return url_;
}
void TOPPASResource::fromLocalFile(const QString & file)
{
url_ = QUrl::fromLocalFile(file);
file_name_ = file;
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Painter2DBase.cpp | .cpp | 28,061 | 756 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/Painter2DBase.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/VISUAL/LayerDataChrom.h>
#include <OpenMS/VISUAL/LayerDataConsensus.h>
#include <OpenMS/VISUAL/LayerDataIdent.h>
#include <OpenMS/VISUAL/LayerDataIonMobility.h>
#include <OpenMS/VISUAL/LayerDataFeature.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/Plot2DCanvas.h>
#include <QColor>
#include <QPainter>
#include <QPoint>
using namespace std;
namespace OpenMS
{
void Painter2DBase::highlightElement(QPainter* /*painter*/, Plot2DCanvas* /*canvas*/, const PeakIndex /*element*/)
{
// does nothing by default
}
void Painter2DBase::paintConvexHull_(QPainter& painter, Plot2DCanvas* canvas, const ConvexHull2D& hull, bool has_identifications)
{
QPolygon points;
ConvexHull2D::PointArrayType ch_points = hull.getHullPoints();
points.resize((int)ch_points.size());
UInt index = 0;
// iterate over hull points
for (ConvexHull2D::PointArrayType::const_iterator it = ch_points.begin(); it != ch_points.end(); ++it, ++index)
{
Peak2D ms_peak({it->getX(), it->getY()}, 0); // assume that CH of a feature is RT and m/z
points.setPoint(index, canvas->dataToWidget_(canvas->unit_mapper_.map(ms_peak)));
}
painter.setPen(QPen(Qt::white, 5, Qt::DotLine, Qt::RoundCap, Qt::RoundJoin));
painter.drawPolygon(points);
painter.setPen(QPen(has_identifications ? Qt::green : Qt::blue, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter.drawPolygon(points);
}
void Painter2DBase::paintConvexHulls_(QPainter& painter, Plot2DCanvas* canvas, const std::vector<ConvexHull2D>& hulls, bool has_identifications)
{
for (const auto& hull : hulls)
{
paintConvexHull_(painter, canvas, hull, has_identifications);
}
}
void Painter2DBase::paintPeptideIDs_(QPainter* painter, Plot2DCanvas* canvas, const IPeptideIds::PepIds& ids, int layer_index)
{
painter->setPen(Qt::darkRed);
bool show_labels = canvas->getLayerFlag(layer_index, LayerDataBase::I_LABELS);
for (const auto& id : ids)
{
if (!id.getHits().empty() || show_labels)
{
if (!id.hasRT() || !id.hasMZ())
{
// TODO: show error message here
continue;
}
double rt = id.getRT();
if (!canvas->visible_area_.getAreaUnit().containsRT(rt))
{
continue;
}
double mz = canvas->getIdentificationMZ_(layer_index, id);
if (!canvas->visible_area_.getAreaUnit().containsMZ(mz))
{
continue;
}
// draw dot
QPoint pos = canvas->dataToWidget_(canvas->unit_mapper_.map(id));
painter->drawLine(pos.x(), pos.y() - 1.0, pos.x(), pos.y() + 1.0);
painter->drawLine(pos.x() - 1.0, pos.y(), pos.x() + 1.0, pos.y());
// draw sequence
String sequence;
if (show_labels)
{
sequence = id.getMetaValue("label");
}
else
{
sequence = id.getHits()[0].getSequence().toString();
}
if (sequence.empty() && !id.getHits().empty())
{
sequence = id.getHits()[0].getMetaValue("label");
}
if (id.getHits().size() > 1)
sequence += "...";
painter->drawText(pos.x() + 10, pos.y() + 10, sequence.toQString());
}
}
}
// ###############################
// ###### 2D Peak
// ###############################
Painter2DPeak::Painter2DPeak(const LayerDataPeak* parent) : layer_(parent)
{
}
void Painter2DPeak::paint(QPainter* painter, Plot2DCanvas* canvas, int layer_index)
{
// renaming some values for readability
const auto& peak_map = layer_->getPeakData()->getMSExperiment();
// skip empty peak maps
if (peak_map.empty())
{
return;
}
const auto [rt_min, rt_max] = canvas->visible_area_.getAreaUnit().RangeRT::getNonEmptyRange();
const auto [mz_min, mz_max] = canvas->visible_area_.getAreaUnit().RangeMZ::getNonEmptyRange();
const auto [im_min, im_max] = canvas->visible_area_.getAreaUnit().RangeMobility::getNonEmptyRange();
// do we currently show an IM frame (with IM + m/z) as units?
const bool is_IM_frame = peak_map.isIMFrame();
auto is_visible_scan = [&](MSExperiment::ConstIterator it_scan) {
if (it_scan->size() <= 1) return false;
// an IM scan? (where we do not care about MS level)
if (is_IM_frame) { return true; }
// for 'standard' RT, m/z data
return it_scan->getMSLevel() == 1;
};
//-----------------------------------------------------------------------------------------------
// Determine number of shown scans (MS1)
std::vector<Size> scan_indices; // list of visible RT/IM scans with at least 2 points
const auto rt_end = peak_map.RTEnd(rt_max);
for (auto it = peak_map.RTBegin(rt_min); it != rt_end; ++it)
{
if (is_visible_scan(it) && Math::contains(it->getDriftTime(), im_min, im_max))
{
scan_indices.push_back(std::distance(peak_map.begin(), it));
}
}
Size n_ms1_scans = scan_indices.size();
if (n_ms1_scans > 0)
{
// sample #of points at 3 scan locations (25%, 50%, 75%)
// and take the median value
Size n_peaks_in_scan(0);
{
static constexpr std::array<double, 3> quantiles = {0.25, 0.50, 0.75};
std::array<Size, quantiles.size()> n_s;
for (Size i = 0; i < quantiles.size(); ++i)
{
const auto& spec = peak_map[scan_indices[n_ms1_scans * quantiles[i]]];
if (!spec.isSorted())
throw Exception::BaseException();
n_s[i] = std::distance(spec.MZBegin(mz_min), spec.MZEnd(mz_max));
}
std::sort(n_s.begin(), n_s.end());
n_peaks_in_scan = n_s[1]; // median
}
Size rt_pixel_count, mz_pixel_count;
{ // obtain number of pixels in RT/IM and MZ dimension
auto tmp = canvas->getPixelRange().getAreaUnit();
rt_pixel_count = tmp.RangeRT::isEmpty() ? tmp.getMaxMobility() : tmp.getMaxRT();
mz_pixel_count = tmp.getMaxMZ();
}
double ratio_data2pixel_rt = n_ms1_scans / (double)rt_pixel_count;
double ratio_data2pixel_mz = n_peaks_in_scan / (double)mz_pixel_count;
// minimum fraction of image expected to be filled with data
// if not reached, we upscale point size
bool has_low_pixel_coverage = ratio_data2pixel_rt < canvas->canvas_coverage_min_ || ratio_data2pixel_mz < canvas->canvas_coverage_min_;
// Are several peaks expected to be drawn on the same pixel in either RT or m/z?
// --> thin out and show only maxima
// Also, we cannot upscale in this mode (since we operate on the buffer directly, i.e. '1 data point == 1 pixel'
if (!has_low_pixel_coverage && (n_peaks_in_scan > mz_pixel_count || n_ms1_scans > rt_pixel_count))
{
paintMaximumIntensities_(*painter, canvas, layer_index, rt_pixel_count, mz_pixel_count);
}
else
{ // this is slower to paint, but allows scaling points
// when data is zoomed in to single peaks these are visualized as circles
// compute ideal pen width (from data);
// since points are rectangular, we take the value of the most "crowded" dimension
// i.e. so that adjacent points do not overlap
double pen_width = std::min(1 / ratio_data2pixel_rt, 1 / ratio_data2pixel_mz);
// ... and make sure its within our boundaries
pen_width = std::max(pen_width, canvas->pen_size_min_);
pen_width = std::min(pen_width, canvas->pen_size_max_);
#ifdef DEBUG_TOPPVIEW
std::cerr << "pen-width " << pen_width << "\n";
#endif
// However: if one dimension is sparse (e.g. only a few, but very long scans), we want to
// avoid showing lots of white background by increasing point size
// This might lead to 'overplotting', but the paint method below can deal with it since
// it will paint high intensities last.
canvas->adaptPenScaling_(ratio_data2pixel_mz, pen_width);
canvas->adaptPenScaling_(ratio_data2pixel_rt, pen_width);
#ifdef DEBUG_TOPPVIEW
std::cerr << "new pen: " << pen_width << "\n";
#endif
// few data points expected: more expensive drawing of all data points (circles or points depending on zoom level)
paintAllIntensities_(*painter, canvas, layer_index, pen_width);
}
} // end of no-scans check
//-----------------------------------------------------------------
// draw precursor peaks
if (canvas->getLayerFlag(layer_index, LayerDataBase::P_PRECURSORS))
{
paintPrecursorPeaks_(*painter, canvas);
}
}
void Painter2DPeak::paintAllIntensities_(QPainter& painter, Plot2DCanvas* canvas, Size layer_index, double pen_width)
{
QVector<QPolygon> coloredPoints((int)layer_->gradient.precalculatedSize());
const double snap_factor = canvas->snap_factors_[layer_index];
const auto& map = layer_->getPeakData()->getMSExperiment();;
const auto& area = canvas->visible_area_.getAreaUnit();
const auto end_area = map.areaEndConst();
// for IM data, use whatever is there. For RT/mz data, use MSlevel 1
const UInt MS_LEVEL = (! map.empty() && map.isIMFrame()) ? map[0].getMSLevel() : 1;
for (auto i = map.areaBeginConst(area, MS_LEVEL); i != end_area; ++i)
{
PeakIndex pi = i.getPeakIndex();
if (layer_->filters.passes(map[pi.spectrum], pi.peak))
{
auto from = canvas->unit_mapper_.map(i);
QPoint pos = canvas->dataToWidget_(from);
// store point in the array of its color
Int colorIndex = canvas->precalculatedColorIndex_(i->getIntensity(), layer_->gradient, snap_factor);
coloredPoints[colorIndex].push_back(pos);
}
}
// draw point arrays from minimum to maximum intensity,
// avoiding low-intensity points obscuring the high-intensity ones
painter.save();
QPen newPointsPen;
newPointsPen.setWidthF(pen_width);
for (Int colorIx = 0; colorIx < coloredPoints.size(); colorIx++)
{
const QPolygon& pointsArr = coloredPoints[colorIx];
if (pointsArr.size())
{
newPointsPen.setColor(layer_->gradient.precalculatedColorByIndex(colorIx));
painter.setPen(newPointsPen);
painter.drawPoints(pointsArr);
}
}
painter.restore();
}
/// abstract away the RT or IM dimension (so we can iterate over both using the same code in paintMaximumIntensities_())
struct DimInfo
{
DimInfo(const MSExperiment& map, const RangeBase& dim, const DimMapper<2>& mapper) : exp_(map), dim_(dim), mapper_(mapper)
{
}
const MSExperiment& exp_;
const RangeBase& dim_;
const DimMapper<2>& mapper_;
/// Maximum RT or IM value for the whole layer
virtual double getMaximum() const = 0;
/// get the RT or IM from a spectrum
virtual double getValue(const MSSpectrum& spec) const = 0;
/// Iterator to first scan with this RT/IM value
virtual MSExperiment::ConstIterator getFirstScan(double value) const = 0;
/// Map a pair of RT/mz (or IM/mz) to the XY-plane
virtual DimMapper<2>::Point mapToPoint(double value, double mz) const = 0;
};
struct DimInfoRT : DimInfo
{
using DimInfo::DimInfo; // inherit C'tor
double getMaximum() const override
{
return exp_.getMaxRT();
}
double getValue(const MSSpectrum& spec) const override
{
return spec.getRT();
}
MSExperiment::ConstIterator getFirstScan(double value) const override
{
return exp_.RTBegin(value);
}
DimMapper<2>::Point mapToPoint(double value, double mz) const override
{
return mapper_.map(Peak2D({value, mz}, 0));
}
};
struct DimInfoIM : DimInfo {
using DimInfo::DimInfo; // inherit C'tor
double getMaximum() const override
{
return exp_.getMaxMobility();
}
double getValue(const MSSpectrum& spec) const override
{
return spec.getDriftTime();
}
MSExperiment::ConstIterator getFirstScan(double value) const override
{
return exp_.IMBegin(value);
}
DimMapper<2>::Point mapToPoint(double value, double mz) const override
{
// there is no datastructure
return mapper_.map(MobilityPeak2D({value, mz}, 0));
}
};
void Painter2DPeak::paintMaximumIntensities_(QPainter& painter, Plot2DCanvas* canvas, Size layer_index, Size rt_pixel_count, Size mz_pixel_count)
{
// set painter to black (we operate directly on the pixels for all colored data)
painter.setPen(Qt::black);
const double snap_factor = canvas->snap_factors_[layer_index];
const auto& map = layer_->getPeakData()->getMSExperiment();
const auto& area = canvas->visible_area_.getAreaUnit();
// for IM data, use whatever is there. For RT/mz data, use MSlevel 1
const UInt MS_LEVEL = (! map.empty() && map.isIMFrame()) ? map[0].getMSLevel() : 1;
auto RT_or_IM_paint = [&](const DimInfo& mapper) {
// note: the variables are named, assuming we have an RT+mz canvas.
// However, by using 'DimInfo' this could well be an IM+mz canvas (i.e. an IM Frame)
const double rt_min = mapper.dim_.getMin();
const double rt_max = mapper.dim_.getMax();
const double mz_min = area.getMinMZ();
const double mz_max = area.getMaxMZ();
// calculate pixel size in data coordinates
double rt_step_size = (rt_max - rt_min) / rt_pixel_count;
double mz_step_size = (mz_max - mz_min) / mz_pixel_count;
// start at first visible RT scan
Size scan_index = std::distance(map.begin(), mapper.getFirstScan(rt_min));
vector<Size> scan_indices, peak_indices;
// iterate over all pixels (RT dimension)
for (Size rt = 0; rt < rt_pixel_count; ++rt)
{
// interval in data coordinates for the current pixel
double rt_start = rt_min + rt_step_size * rt;
double rt_end = rt_start + rt_step_size;
// cout << "rt: " << rt << " (" << rt_start << " - " << rt_end << ")" << endl;
// reached the end of data
if (rt_end >= mapper.getMaximum())
{
break;
}
// determine the relevant spectra and reserve an array for the peak indices
scan_indices.clear();
peak_indices.clear();
for (Size i = scan_index; i < map.size(); ++i)
{
const auto& spec = map[i];
if (mapper.getValue(spec) >= rt_end)
{
scan_index = i; // store last scan index for next RT pixel
break;
}
if (spec.getMSLevel() == MS_LEVEL && ! spec.empty())
{
scan_indices.push_back(i);
peak_indices.push_back(spec.MZBegin(mz_min) - spec.begin());
}
}
if (scan_indices.empty())
{
continue;
}
// iterate over all pixels (m/z dimension)
for (Size mz = 0; mz < mz_pixel_count; ++mz)
{
double mz_start = mz_min + mz_step_size * mz;
double mz_end = mz_start + mz_step_size;
// iterate over all relevant peaks in all relevant scans
float max = -1.0;
for (Size i = 0; i < scan_indices.size(); ++i)
{
Size s = scan_indices[i];
Size p = peak_indices[i];
const auto& spec = map[s];
for (; p < spec.size(); ++p)
{
if (spec[p].getMZ() >= mz_end)
{
break;
}
if (spec[p].getIntensity() > max && layer_->filters.passes(spec, p))
{
max = spec[p].getIntensity();
}
}
peak_indices[i] = p; // store last peak index for next m/z pixel
}
// draw to buffer
if (max >= 0.0)
{
QPoint pos = canvas->dataToWidget_(mapper.mapToPoint(rt_start + 0.5 * rt_step_size, mz_start + 0.5 * mz_step_size));
canvas->buffer_.setPixel(pos.x(), pos.y(), canvas->heightColor_(max, layer_->gradient, snap_factor).rgb());
}
}
}
}; // end lambda
if (map.isIMFrame())
{
RT_or_IM_paint(DimInfoIM(map, area.getRangeForDim(MSDim::IM), canvas->unit_mapper_));
}
else
{
RT_or_IM_paint(DimInfoRT(map, area.getRangeForDim(MSDim::RT), canvas->unit_mapper_));
}
}
void Painter2DPeak::paintPrecursorPeaks_(QPainter& painter, Plot2DCanvas* canvas)
{
const auto& peak_map = layer_->getPeakData()->getMSExperiment();
QPen p;
p.setColor(Qt::black);
painter.setPen(p);
auto it_prec = peak_map.end(); // MS1 spectrum of parent ion
auto it_end = peak_map.RTEnd(canvas->visible_area_.getAreaUnit().getMaxRT());
for (auto it = peak_map.RTBegin(canvas->visible_area_.getAreaUnit().getMinRT()); it != it_end; ++it)
{
// remember last precursor spectrum (do not call it->getPrecursorSpectrum(), since it can be very slow if no MS1 data is present)
if (it->getMSLevel() == 1)
{
it_prec = it;
}
else if (it->getMSLevel() == 2 && !it->getPrecursors().empty())
{ // this is an MS/MS scan
// position of precursor in MS2 (only works for 2D views with RT, m/z), not for ion mobility (IM, m/z) views.
try
{
const auto data_xy_ms2 = canvas->unit_mapper_.map(Peak2D({it->getRT(), it->getPrecursors()[0].getMZ()}, {}));
const QPoint pos_px_ms2 = canvas->dataToWidget_(data_xy_ms2);
const int x2 = pos_px_ms2.x();
const int y2 = pos_px_ms2.y();
if (it_prec != peak_map.end())
{
// position of precursor in MS1
const auto data_xy_ms1 = canvas->unit_mapper_.map(Peak2D({it_prec->getRT(), it->getPrecursors()[0].getMZ()}, {}));
const QPoint pos_px_ms1 = canvas->dataToWidget_(data_xy_ms1);
const int x = pos_px_ms1.x();
const int y = pos_px_ms1.y();
// diamond shape in MS1
drawDiamond({x, y}, &painter, 6);
// rt position of corresponding MS2
painter.drawLine(x, y, x2, y2);
}
else // no preceding MS1
{
// rt position of corresponding MS2 (cross)
drawCross({x2, y2}, &painter, 6);
}
} // end try
catch (...)
{
// paint nothing, since the coordinate system is wrong
}
}
}
}
Painter2DChrom::Painter2DChrom(const LayerDataChrom* parent) : layer_(parent)
{
}
void Painter2DChrom::paint(QPainter* painter, Plot2DCanvas* canvas, int /*layer_index*/)
{
const PeakMap& exp = layer_->getChromatogramData()->getMSExperiment();
// TODO CHROM implement layer filters
// paint chromatogram rt start and end as line
float mz_origin = 0;
QPoint posi;
QPoint posi2;
for (const auto& chrom : exp.getChromatograms())
{
if (chrom.empty())
{
continue;
}
mz_origin = chrom.getPrecursor().getMZ();
posi = canvas->dataToWidget_(canvas->unit_mapper_.map(Peak2D {{chrom.front().getRT(), mz_origin}, 0}));
posi2 = canvas->dataToWidget_(canvas->unit_mapper_.map(Peak2D {{chrom.back().getRT(), mz_origin}, 0}));
painter->drawLine(posi.x(), posi.y(), posi2.x(), posi2.y());
}
}
Painter2DIonMobility::Painter2DIonMobility(const LayerDataIonMobility* parent) : layer_(parent)
{
}
void Painter2DIonMobility::paint(QPainter* /*painter*/, Plot2DCanvas* /*canvas*/, int /*layer_index*/)
{
}
Painter2DFeature::Painter2DFeature(const LayerDataFeature* parent) : layer_(parent)
{
}
void Painter2DFeature::paint(QPainter* painter, Plot2DCanvas* canvas, int layer_index)
{
if (canvas->getLayerFlag(layer_index, LayerDataBase::F_HULLS))
{
paintTraceConvexHulls_(painter, canvas);
}
if (canvas->getLayerFlag(layer_index, LayerDataBase::F_HULL))
{
paintFeatureConvexHulls_(painter, canvas);
}
if (canvas->getLayerFlag(layer_index, LayerDataBase::F_UNASSIGNED))
{
paintPeptideIDs_(painter, canvas, layer_->getPeptideIds(), layer_index);
}
const double snap_factor = canvas->snap_factors_[layer_index];
int line_spacing = QFontMetrics(painter->font()).lineSpacing();
const auto icon = toShapeIcon(layer_->param.getValue("dot:feature_icon").toString());
Size icon_size = layer_->param.getValue("dot:feature_icon_size");
bool show_label = (layer_->label != LayerDataBase::L_NONE);
UInt num = 0;
for (const auto& f : *layer_->getFeatureMap())
{
if (canvas->visible_area_.getAreaUnit().containsRT(f.getRT()) && canvas->visible_area_.getAreaUnit().containsMZ(f.getMZ()) && layer_->filters.passes(f))
{
// determine color
QColor color;
if (f.metaValueExists(5))
{
color = QColor(f.getMetaValue(5).toQString());
}
else
{
color = canvas->heightColor_(f.getIntensity(), layer_->gradient, snap_factor);
}
// paint
QPoint pos = canvas->dataToWidget_(canvas->unit_mapper_.map(f));
drawIcon(pos, color.rgb(), icon, icon_size, *painter);
// labels
if (show_label)
{
if (layer_->label == LayerDataBase::L_INDEX)
{
painter->setPen(Qt::darkBlue);
painter->drawText(pos.x() + 10, pos.y() + 10, QString::number(num));
}
else if ((layer_->label == LayerDataBase::L_ID || layer_->label == LayerDataBase::L_ID_ALL) && !f.getPeptideIdentifications().empty() && !f.getPeptideIdentifications()[0].getHits().empty())
{
painter->setPen(Qt::darkGreen);
Size maxHits = (layer_->label == LayerDataBase::L_ID_ALL) ? f.getPeptideIdentifications()[0].getHits().size() : 1;
for (Size j = 0; j < maxHits; ++j)
{
painter->drawText(pos.x() + 10, pos.y() + 10 + int(j) * line_spacing, f.getPeptideIdentifications()[0].getHits()[j].getSequence().toString().toQString());
}
}
else if (layer_->label == LayerDataBase::L_META_LABEL)
{
painter->setPen(Qt::darkBlue);
painter->drawText(pos.x() + 10, pos.y() + 10, f.getMetaValue(3).toQString());
}
}
}
++num;
}
}
void Painter2DFeature::highlightElement(QPainter* painter, Plot2DCanvas* canvas, const PeakIndex /*element*/)
{
painter->setPen(QPen(Qt::red, 2));
const Feature& f = canvas->selected_peak_.getFeature(*layer_->getFeatureMap());
paintConvexHulls_(*painter, canvas, f.getConvexHulls(), f.getPeptideIdentifications().size() && f.getPeptideIdentifications()[0].getHits().size());
}
void Painter2DFeature::paintTraceConvexHulls_(QPainter* painter, Plot2DCanvas* canvas)
{
painter->setPen(Qt::black);
const auto& area = canvas->visible_area_.getAreaUnit();
for (const auto& f : *layer_->getFeatureMap())
{
if (area.containsRT(f.getRT()) && area.containsMZ(f.getMZ()) && layer_->filters.passes(f))
{
bool hasIdentifications = !f.getPeptideIdentifications().empty() && !f.getPeptideIdentifications()[0].getHits().empty();
paintConvexHulls_(*painter, canvas, f.getConvexHulls(), hasIdentifications);
}
}
}
void Painter2DFeature::paintFeatureConvexHulls_(QPainter* painter, Plot2DCanvas* canvas)
{
const auto& area = canvas->visible_area_.getAreaUnit();
for (const auto& f : *layer_->getFeatureMap())
{
if (area.containsRT(f.getRT()) && area.containsMZ(f.getMZ()) && layer_->filters.passes(f))
{
paintConvexHull_(*painter, canvas, f.getConvexHull(), !f.getPeptideIdentifications().empty() && !f.getPeptideIdentifications()[0].getHits().empty());
}
}
}
Painter2DConsensus::Painter2DConsensus(const LayerDataConsensus* parent) : layer_(parent)
{
}
void Painter2DConsensus::paint(QPainter* painter, Plot2DCanvas* canvas, int layer_index)
{
if (canvas->getLayerFlag(layer_index, LayerDataBase::C_ELEMENTS))
{
paintConsensusElements_(painter, canvas, layer_index);
}
const double snap_factor = canvas->snap_factors_[layer_index];
const auto icon = toShapeIcon(layer_->param.getValue("dot:feature_icon").toString());
Size icon_size = layer_->param.getValue("dot:feature_icon_size");
const auto area = canvas->visible_area_.getAreaUnit();
for (const auto& cf : *layer_->getConsensusMap())
{
if (area.containsRT(cf.getRT()) && area.containsMZ(cf.getMZ()) && layer_->filters.passes(cf))
{
// determine color
QColor color;
if (cf.metaValueExists(5))
{
color = cf.getMetaValue(5).toQString();
}
else
{
// use intensity as color
color = canvas->heightColor_(cf.getIntensity(), layer_->gradient, snap_factor);
}
// paint
auto pos_unit = canvas->unit_mapper_.map(cf);
drawIcon(canvas->dataToWidget_(pos_unit), color.rgb(), icon, icon_size, *painter);
}
}
}
void Painter2DConsensus::highlightElement(QPainter* painter, Plot2DCanvas* canvas, const PeakIndex element)
{
painter->setPen(QPen(Qt::red, 2));
paintConsensusElement_(painter, canvas, canvas->getCurrentLayerIndex(), element.getFeature(*layer_->getConsensusMap()));
}
void Painter2DConsensus::paintConsensusElements_(QPainter* painter, Plot2DCanvas* canvas, Size layer_index)
{
for (const auto& cf : *layer_->getConsensusMap())
{
paintConsensusElement_(painter, canvas, layer_index, cf);
}
}
void Painter2DConsensus::paintConsensusElement_(QPainter* painter, Plot2DCanvas* canvas, Size layer_index, const ConsensusFeature& cf)
{
// Is CF or any of its handles visible?
if (!isConsensusFeatureVisible_(canvas, cf, layer_index) || !layer_->filters.passes(cf))
{
return;
}
// calculate position of consensus feature (centroid)
QPoint consensus_pos = canvas->dataToWidget_(canvas->unit_mapper_.map(cf));
// iterate over elements
for (const FeatureHandle& element : cf)
{
// calculate position of consensus element
QPoint pos = canvas->dataToWidget_(canvas->unit_mapper_.map(element));
// paint line
painter->drawLine(consensus_pos, pos);
painter->drawPoint(pos.x(), pos.y());
painter->drawPoint(pos.x() - 1, pos.y());
painter->drawPoint(pos.x() + 1, pos.y());
painter->drawPoint(pos.x(), pos.y() - 1);
painter->drawPoint(pos.x(), pos.y() + 1);
}
}
bool Painter2DConsensus::isConsensusFeatureVisible_(const Plot2DCanvas* canvas, const ConsensusFeature& cf, Size layer_index)
{
const auto& area = canvas->visible_area_.getAreaUnit();
// check the centroid first
if (area.containsRT(cf.getRT()) && area.containsMZ(cf.getMZ()))
{
return true;
}
// if element-flag is set, check if any of the consensus elements is visible
if (canvas->getLayerFlag(layer_index, LayerDataBase::C_ELEMENTS))
{
for (const auto& ce : cf.getFeatures())
{
if (area.containsRT(ce.getRT()) && area.containsMZ(ce.getMZ()))
{
return true;
}
}
}
return false;
}
Painter2DIdent::Painter2DIdent(const LayerDataIdent* parent) : layer_(parent)
{
}
void Painter2DIdent::paint(QPainter* painter, Plot2DCanvas* canvas, int layer_index)
{
paintPeptideIDs_(painter, canvas, layer_->getPeptideIds(), layer_index);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASWidget.cpp | .cpp | 5,515 | 209 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
// OpenMS
#include <OpenMS/VISUAL/TOPPASWidget.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/TOPPASVertex.h>
#include <OpenMS/VISUAL/TOPPASEdge.h>
#include <OpenMS/CONCEPT/Types.h>
// Qt
#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QDropEvent>
#include <QtCore/QMimeData>
#include <QUrl>
using namespace std;
namespace OpenMS
{
TOPPASWidget::TOPPASWidget(const Param & /*preferences*/, QWidget * parent, const String & tmp_path) :
QGraphicsView(parent),
EnhancedTabBarWidgetInterface(),
scene_(new TOPPASScene(this, tmp_path.toQString()))
{
setAttribute(Qt::WA_DeleteOnClose);
setAttribute(Qt::WA_AlwaysShowToolTips);
setRenderHint(QPainter::Antialiasing);
setScene(scene_);
setAcceptDrops(true);
setDragMode(QGraphicsView::ScrollHandDrag);
setFocusPolicy(Qt::StrongFocus);
}
TOPPASWidget::~TOPPASWidget() = default;
TOPPASScene * TOPPASWidget::getScene()
{
return scene_;
}
void TOPPASWidget::zoom(bool zoom_in)
{
qreal factor = 1.1;
if (zoom_in)
{
factor = 1.0 / factor;
}
scale(factor, factor);
QRectF items_rect = scene_->itemsBoundingRect();
QRectF new_scene_rect = items_rect.united(mapToScene(rect()).boundingRect());
qreal top_left_x = new_scene_rect.topLeft().x();
qreal top_left_y = new_scene_rect.topLeft().y();
qreal bottom_right_x = new_scene_rect.bottomRight().x();
qreal bottom_right_y = new_scene_rect.bottomRight().y();
qreal width = new_scene_rect.width();
qreal height = new_scene_rect.height();
new_scene_rect.setTopLeft(QPointF(top_left_x - width / 2.0, top_left_y - height / 2.0));
new_scene_rect.setBottomRight(QPointF(bottom_right_x + width / 2.0, bottom_right_y + height / 2.0));
scene_->setSceneRect(new_scene_rect);
}
void TOPPASWidget::wheelEvent(QWheelEvent * event)
{
zoom(event->angleDelta().y() < 0);
}
void TOPPASWidget::dragEnterEvent(QDragEnterEvent * event)
{
// TODO: test mime type/source? where?
event->acceptProposedAction();
}
void TOPPASWidget::dragMoveEvent(QDragMoveEvent * event)
{
// TODO: test mime type/source? where?
event->acceptProposedAction();
}
void TOPPASWidget::dropEvent(QDropEvent * event)
{
// TODO: test mime type/source? where?
//std::cerr << "Drop Event with data:\n " << String( event->mimeData()->formats().join("\n ")) << "\n\n";
if (event->mimeData()->hasUrls())
{
String filename = String(event->mimeData()->urls().front().toLocalFile());
emit sendStatusMessage("loading drop file '" + filename + "' (press CRTL while dropping to insert into current window)", 0);
// open pipeline in new window (or in current if CTRL is pressed)
emit pipelineDroppedOnWidget(filename, event->modifiers() != Qt::ControlModifier);
}
else
{
QPointF scene_pos = mapToScene(event->position().toPoint());
emit toolDroppedOnWidget(scene_pos.x(), scene_pos.y());
}
event->acceptProposedAction();
}
void TOPPASWidget::keyPressEvent(QKeyEvent * e)
{
if (e->key() == Qt::Key_C && e->modifiers() == Qt::ControlModifier)
{
scene_->copySelected();
e->accept();
}
else if (e->key() == Qt::Key_X && e->modifiers() == Qt::ControlModifier)
{
scene_->copySelected();
scene_->removeSelected();
e->accept();
}
else if (e->key() == Qt::Key_V && e->modifiers() == Qt::ControlModifier)
{
scene_->paste();
e->accept();
}
else if (e->key() == Qt::Key_Control)
{
setDragMode(QGraphicsView::RubberBandDrag);
//color of hovering edge may change
TOPPASEdge* hover_edge = scene_->getHoveringEdge();
if (hover_edge)
{
hover_edge->update();
}
e->accept();
}
else if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace)
{
scene_->removeSelected();
e->accept();
}
else if (e->key() == Qt::Key_Plus)
{
zoom(false);
e->accept();
}
else if (e->key() == Qt::Key_Minus)
{
zoom(true);
e->accept();
}
else
{
e->ignore();
}
}
void TOPPASWidget::keyReleaseEvent(QKeyEvent * e)
{
if (e->key() == Qt::Key_Control)
{
setDragMode(QGraphicsView::ScrollHandDrag);
//color of hovering edge may change
TOPPASEdge* hover_edge = scene_->getHoveringEdge();
if (hover_edge)
{
hover_edge->update();
}
e->accept();
}
}
void TOPPASWidget::leaveEvent(QEvent * /*e*/)
{
}
void TOPPASWidget::enterEvent(QEnterEvent* /*e*/)
{
#ifndef Q_WS_MAC
setFocus();
#endif
}
void TOPPASWidget::resizeEvent(QResizeEvent * /*event*/)
{
// QGraphicsView::resizeEvent(event);
// if (scene_)
// {
// QRectF items_rect = scene_->itemsBoundingRect();
// scene_->setSceneRect(items_rect.united(mapToScene(viewport()->rect()).boundingRect()));
// }
}
void TOPPASWidget::closeEvent(QCloseEvent * e)
{
bool close = scene_->saveIfChanged();
if (close)
{
e->accept();
}
else
{
e->ignore();
}
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASTreeView.cpp | .cpp | 3,540 | 150 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASTreeView.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QDrag>
#include <QApplication>
#include <QtCore/QMimeData>
using namespace std;
namespace OpenMS
{
TOPPASTreeView::TOPPASTreeView(QWidget * parent) :
QTreeWidget(parent)
{
// we drag by ourselves:
setDragEnabled(false);
}
TOPPASTreeView::~TOPPASTreeView() = default;
void TOPPASTreeView::filter(const QString& must_match)
{
// hide all
QTreeWidgetItemIterator it(this);
while (*it)
{
(*it)->setHidden(true);
(*it)->setExpanded(false);
++it;
}
// recursive lambda: show items and its subchildren (e.g. when a category matches)
function<void(QTreeWidgetItem*)> show_sub_tree = [&](QTreeWidgetItem* item) {
item->setHidden(false);
for (int i = 0; i < item->childCount(); i++)
{
QTreeWidgetItem* child = item->child(i);
child->setHidden(false);
child->setExpanded(true); // technically not required, since our tree is only 2 layers deep, but maybe in the future...
show_sub_tree(child);
}
};
// show stuff that matches
auto items = this->findItems(must_match, Qt::MatchContains | Qt::MatchRecursive);
for (auto& it : items)
{
// show parent (if any) -- otherwise the children will not be displayed
if (it->parent())
{
it->parent()->setHidden(false);
it->parent()->setExpanded(true);
}
show_sub_tree(it); // also show all children
it->setExpanded(true);
}
}
void TOPPASTreeView::expandAll()
{
QTreeWidgetItemIterator it(this);
while (*it)
{
(*it)->setExpanded(true);
++it;
}
}
void TOPPASTreeView::collapseAll()
{
QTreeWidgetItemIterator it(this);
while (*it)
{
(*it)->setExpanded(false);
++it;
}
}
void TOPPASTreeView::mousePressEvent(QMouseEvent* event)
{
QTreeWidget::mousePressEvent(event);
if (event->button() == Qt::LeftButton)
{
drag_start_pos_ = event->pos();
}
}
void TOPPASTreeView::mouseMoveEvent(QMouseEvent* event)
{
QTreeWidget::mouseMoveEvent(event);
if (!(event->buttons() & Qt::LeftButton))
{
return;
}
if ((event->pos() - drag_start_pos_).manhattanLength() < QApplication::startDragDistance())
{
return;
}
if (currentItem() && currentItem()->childCount() > 0)
{
// drag item is a category or a tool with types - one of the types must be selected
return;
}
QDrag * drag = new QDrag(this);
QMimeData * mime_data = new QMimeData;
mime_data->setText(currentItem()->text(0));
drag->setMimeData(mime_data);
// start drag
drag->exec(Qt::CopyAction);
}
void TOPPASTreeView::keyPressEvent(QKeyEvent* e)
{
QTreeWidget::keyPressEvent(e);
if (currentItem() && e->key() == Qt::Key_Return)
{
e->accept();
emit itemDoubleClicked(currentItem(), 0);
}
else
{
e->ignore();
}
}
void TOPPASTreeView::enterEvent(QEnterEvent* /*e*/)
{
setFocus();
}
void TOPPASTreeView::leaveEvent(QEvent* /*e*/)
{
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/EnhancedTabBar.cpp | .cpp | 3,441 | 147 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/EnhancedTabBar.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QMouseEvent>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMessageBox>
using namespace std;
namespace OpenMS
{
EnhancedTabBar::EnhancedTabBar(QWidget * parent) :
QTabBar(parent)
{
connect(this, SIGNAL(currentChanged(int)), this, SLOT(currentChanged_(int)));
//set up drag-and-drop
setAcceptDrops(true);
}
EnhancedTabBar::~EnhancedTabBar() = default;
void EnhancedTabBar::setTabText(const QString& text)
{
QTabBar::setTabText(currentIndex(), text);
}
void EnhancedTabBar::dragEnterEvent(QDragEnterEvent * e)
{
e->acceptProposedAction();
}
void EnhancedTabBar::dropEvent(QDropEvent * e)
{
int tab = tabAt_(e->position().toPoint());
if (tab != -1)
{
emit dropOnTab(e->mimeData(), dynamic_cast<QWidget*>(e->source()), tabData(tab).toInt());
}
else
{ // did not hit a tab, but the void area on the right of tabs --> create new tab
emit dropOnWidget(e->mimeData(), dynamic_cast<QWidget*>(e->source()));
}
e->acceptProposedAction();
}
void EnhancedTabBar::contextMenuEvent(QContextMenuEvent * e)
{
int tab = tabAt_(e->pos());
if (tab != -1)
{
QMenu menu(this);
menu.addAction("Close");
if (menu.exec(e->globalPos()))
{
emit closeRequested(tabData(tab).toInt());
}
}
}
void EnhancedTabBar::mouseDoubleClickEvent(QMouseEvent * e)
{
if (e->button() != Qt::LeftButton)
{
e->ignore();
return;
}
int tab = tabAt_(e->pos());
if (tab != -1)
{
// will close the window and remove it from the tabbar
emit closeRequested(tabData(tab).toInt());
}
}
int EnhancedTabBar::addTab(const String& text, int id)
{
// make sure this ID does not exist yet
for (int i = 0; i < this->count(); ++i)
{
if (tabData(i).toInt() == id)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Widget with the same ID was added before!");
}
}
int tab_index = QTabBar::addTab(text.c_str());
setTabData(tab_index, id);
return tab_index;
}
void EnhancedTabBar::removeId(int id)
{
for (int i = 0; i < this->count(); ++i)
{
if (tabData(i).toInt() == id)
{
removeTab(i);
return;
}
}
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Tab with ID ") + id + " is already gone!");
}
void EnhancedTabBar::show(int id)
{
for (int i = 0; i < this->count(); ++i)
{
if (tabData(i).toInt() == id)
{
setCurrentIndex(i);
break;
}
}
}
void EnhancedTabBar::currentChanged_(int index)
{
emit currentIdChanged(tabData(index).toInt());
}
int EnhancedTabBar::tabAt_(const QPoint & pos)
{
for (int i = 0; i < this->count(); ++i)
{
if (tabRect(i).contains(pos))
{
return i;
}
}
return -1;
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerDataChrom.cpp | .cpp | 7,687 | 241 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerDataChrom.h>
#include <OpenMS/DATASTRUCTURES/OSWData.h>
#include <OpenMS/KERNEL/DimMapper.h>
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/LayerData1DChrom.h>
#include <OpenMS/VISUAL/Painter2DBase.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
#include <OpenMS/METADATA/AnnotatedMSRun.h>
#include <boost/make_shared.hpp>
using namespace std;
namespace OpenMS
{
LayerDataChrom::LayerDataChrom():
LayerDataBase(LayerDataBase::DT_CHROMATOGRAM)
{}
std::unique_ptr<Painter2DBase> LayerDataChrom::getPainter2D() const
{
return make_unique<Painter2DChrom>(this);
}
std::unique_ptr<LayerData1DBase> LayerDataChrom::to1DLayer() const
{
return make_unique<LayerData1DChrom>(*this);
}
std::unique_ptr<LayerStoreData> LayerDataChrom::storeVisibleData(const RangeAllType& visible_range, const DataFilters& layer_filters) const
{
auto ret = make_unique<LayerStoreDataPeakMapVisible>();
ret->storeVisibleExperiment(chromatogram_map_.get()->getMSExperiment(), visible_range, layer_filters);
return ret;
}
std::unique_ptr<LayerStoreData> LayerDataChrom::storeFullData() const
{
auto ret = make_unique<LayerStoreDataPeakMapAll>();
ret->storeFullExperiment(chromatogram_map_.get()->getMSExperiment());
return ret;
}
LayerDataChrom::ProjectionData LayerDataChrom::getProjection(const DIM_UNIT unit_x, const DIM_UNIT unit_y, const RangeAllType& /*area*/) const
{
ProjectionData result;
// create projection data
map<float, float> rt;
map<int, float> mzint;
map<int, float> mzsum;
MSSpectrum projection_mz;
MSChromatogram projection_rt;
// this does not work yet for chromatograms...
/*
auto& peak_count = result.stats.number_of_datapoints;
auto& intensity_max = result.stats.max_intensity;
double total_intensity_sum = 0.0;
// divide visible range into 100 bins (much faster than using a constant, e.g. 0.05, leading to many peaks for large maps without more information)
float rt_range = area.RangeRT::getSpan();
float mult = 100.0f / (std::isnan(rt_range) ? 1 : rt_range);
for (auto i = chromatogram_map_->areaBeginConst(area.getMinRT(), area.getMaxRT(), area.getMinMZ(), area.getMaxMZ()); i != getPeakData()->areaEndConst(); ++i)
{
PeakIndex pi = i.getPeakIndex();
if (filters.passes((*getPeakData())[pi.spectrum], pi.peak))
{
// summary stats
++peak_count;
total_intensity_sum += i->getIntensity();
intensity_max = max(intensity_max, i->getIntensity());
// binning for m/z
auto intensity = i->getIntensity();
mzint[int(i->getMZ() * mult)] += intensity;
// ... to later obtain an intensity weighted average m/z value
mzsum[int(i->getMZ() * mult)] += i->getMZ() * intensity;
// binning in RT (one value per scan)
rt[i.getRT()] += i->getIntensity();
}
}
// write to spectra/chrom
projection_mz.resize(mzint.size() + 2);
projection_mz[0].setMZ(area.getMinMZ());
projection_mz[0].setIntensity(0.0);
projection_mz.back().setMZ(area.getMaxMZ());
projection_mz.back().setIntensity(0.0);
projection_rt.resize(rt.size() + 2);
projection_rt[0].setRT(area.getMinRT());
projection_rt[0].setIntensity(0.0);
projection_rt.back().setRT(area.getMaxRT());
projection_rt.back().setIntensity(0.0);
Size i = 1;
map<int, float>::iterator intit = mzint.begin();
for (auto it = mzsum.cbegin(); it != mzsum.cend(); ++it)
{
auto intensity = intit->second;
projection_mz[i].setMZ(it->second / intensity);
projection_mz[i].setIntensity(intensity);
++intit;
++i;
}
i = 1;
for (auto it = rt.cbegin(); it != rt.cend(); ++it)
{
projection_rt[i].setMZ(it->first);
projection_rt[i].setIntensity(it->second);
++i;
}
*/
// create final datastructure
// projection for m/z
auto ptr_mz = make_unique<LayerData1DPeak>();
ExperimentSharedPtrType exp_mz = std::make_shared<ExperimentType>();
exp_mz->getMSExperiment().addSpectrum(std::move(projection_mz));
ptr_mz->setPeakData(exp_mz);
// projection for RT
auto ptr_rt = make_unique<LayerData1DChrom>();
exp_mz->getMSExperiment().addChromatogram(std::move(projection_rt));
ptr_rt->setChromData(std::make_shared<AnnotatedMSRun>());
auto assign_axis = [&](auto unit, auto& layer) {
switch (unit)
{
case DIM_UNIT::MZ:
layer = std::move(ptr_mz);
break;
case DIM_UNIT::RT:
layer = std::move(ptr_rt);
break;
default:
// do nothing, leave projection empty
break;
}
};
assign_axis(unit_x, result.projection_ontoX);
assign_axis(unit_y, result.projection_ontoY);
return result;
}
PeakIndex LayerDataChrom::findHighestDataPoint(const RangeAllType& area) const
{
const PeakMap& exp = getChromatogramData().get()->getMSExperiment();
int count {-1};
for (const auto& chrom : exp.getChromatograms())
{
++count;
if (chrom.empty())
{
continue; // ensure that empty chromatograms are not examined (iter->front = segfault)
}
auto mz_origin = chrom.getPrecursor().getMZ();
// check m/z first
if (area.containsMZ(mz_origin))
{
// the center point's RT should be inside the RT range of the chromatogram
if (RangeRT(chrom.front().getRT(), chrom.back().getRT()).containsRT(area.RangeRT::center()))
{
return PeakIndex(count, 0); // we only care about the chrom, not the peak inside
}
}
}
return PeakIndex();
}
PointXYType LayerDataChrom::peakIndexToXY(const PeakIndex& peak, const DimMapper<2>& mapper) const
{
const auto& chrom = getChromatogram(peak.spectrum);
return mapper.map(chrom, peak.peak);
}
String LayerDataChrom::getDataArrayDescription(const PeakIndex& peak_index)
{
String status;
const auto& s = getChromatogram(peak_index.spectrum);
for (Size m = 0; m < s.getFloatDataArrays().size(); ++m)
{
if (peak_index.peak < s.getFloatDataArrays()[m].size())
{
status += s.getFloatDataArrays()[m].getName() + ": " + s.getFloatDataArrays()[m][peak_index.peak] + " ";
}
}
for (Size m = 0; m < s.getIntegerDataArrays().size(); ++m)
{
if (peak_index.peak < s.getIntegerDataArrays()[m].size())
{
status += s.getIntegerDataArrays()[m].getName() + ": " + s.getIntegerDataArrays()[m][peak_index.peak] + " ";
}
}
for (Size m = 0; m < s.getStringDataArrays().size(); ++m)
{
if (peak_index.peak < s.getStringDataArrays()[m].size())
{
status += s.getStringDataArrays()[m].getName() + ": " + s.getStringDataArrays()[m][peak_index.peak] + " ";
}
}
return status;
}
void LayerDataChrom::setChromatogramAnnotation(OSWData&& data)
{
chrom_annotation_ = OSWDataSharedPtrType(new OSWData(std::move(data)));
}
std::unique_ptr<LayerStatistics> LayerDataChrom::getStats() const
{
return make_unique<LayerStatisticsPeakMap>(chromatogram_map_->getMSExperiment());
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/SpectraTreeTab.cpp | .cpp | 22,694 | 615 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/SpectraTreeTab.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/LayerDataChrom.h>
#include <OpenMS/VISUAL/TreeView.h>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMenu>
namespace OpenMS
{
std::vector<int> listToVec(const QList<QVariant>& in)
{
std::vector<int> out;
for (const auto & i : in)
{
out.push_back(i.toInt());
}
return out;
}
QList<QVariant> vecToList(const std::vector<Size>& in)
{
QList<QVariant> res;
for (Size i : in) res.push_back((unsigned int)i);
return res;
}
// Use a namespace to encapsulate names, yet use c-style 'enum' for fast conversion to int.
// So we can write: 'ClmnPeak::MS_LEVEL', but get implicit conversion to int
namespace ClmnPeak
{
enum HeaderNames
{ // indices into QTableWidget's columns (which start at index 0)
// note: make sure SPEC_INDEX remains at 1 (and is synced with ClmnChrom::CHROM_INDEX!!!)
MS_LEVEL, SPEC_INDEX, RT, PRECURSOR_MZ, DISSOCIATION, SCANTYPE, ZOOM, /* last entry --> */ SIZE_OF_HEADERNAMES
};
// keep in SYNC with enum HeaderNames
const QStringList HEADER_NAMES = QStringList()
<< "MS level" << "index" << "RT" << "precursor m/z" << "dissociation" << "scan" << "zoom";
}
// Use a namespace to encapsulate names, yet use c-style 'enum' for fast conversion to int.
// So we can write: 'ClmnPeak::MS_LEVEL', but get implicit conversion to int
namespace ClmnChrom
{
enum HeaderNames
{ // indices into QTableWidget's columns (which start at index 0)
// note: make sure CHROM_INDEX remains at 1 (and is synced with ClmnPeak::SPEC_INDEX!!!)
TYPE, CHROM_INDEX, MZ, DESCRIPTION, RT_START, RT_END, CHARGE, CHROM_TYPE, /* last entry --> */ SIZE_OF_HEADERNAMES
};
// keep in SYNC with enum HeaderNames
const QStringList HEADER_NAMES = QStringList()
<< " type" << "index" << "m/z" << "Description" << "rt start" << "rt end" << "charge" << "chromatogram type";
}
struct IndexExtrator
{
explicit IndexExtrator(const QTreeWidgetItem* item)
: spectrum_index(item->data(ClmnPeak::SPEC_INDEX, Qt::DisplayRole).toInt()),
res(item->data(ClmnChrom::TYPE, Qt::UserRole).toList()) // this works, even if the QVariant is invalid (then the list is empty)
{
}
bool hasChromIndices() const
{
return !res.empty();
}
const int spectrum_index;
const QList<QVariant> res;
};
SpectraTreeTab::SpectraTreeTab(QWidget * parent) :
QWidget(parent)
{
// these must be identical, because there is code which extracts the scan index irrespective of what we show
assert(ClmnPeak::SPEC_INDEX == ClmnChrom::CHROM_INDEX);
setObjectName("Scans");
QVBoxLayout* spectra_widget_layout = new QVBoxLayout(this);
spectra_treewidget_ = new TreeView(this);
spectra_treewidget_->setWhatsThis("Spectrum selection bar<BR><BR>Here all spectra of the current experiment are shown. Left-click on a spectrum to show it. "
"Double-clicking might be implemented as well, depending on the data. "
"Context-menus for both the column header and data rows are available by right-clicking.");
//~ no good for huge experiments - omitted:
//~ spectrum_selection_->setSortingEnabled(true);
//~ spectrum_selection_->sortByColumn ( 1, Qt::AscendingOrder);
spectra_treewidget_->setDragEnabled(true);
spectra_treewidget_->setContextMenuPolicy(Qt::CustomContextMenu);
connect(spectra_treewidget_, &QTreeWidget::currentItemChanged, this, &SpectraTreeTab::itemSelectionChange_);
connect(spectra_treewidget_, &QTreeWidget::itemDoubleClicked, this, &SpectraTreeTab::itemDoubleClicked_);
connect(spectra_treewidget_, &QTreeWidget::customContextMenuRequested, this, &SpectraTreeTab::spectrumContextMenu_);
spectra_widget_layout->addWidget(spectra_treewidget_);
QHBoxLayout* tmp_hbox_layout = new QHBoxLayout();
spectra_search_box_ = new QLineEdit(this);
spectra_search_box_->setPlaceholderText("<search text>");
spectra_search_box_->setWhatsThis("Search in a certain column. Hits are shown as you type. Press <Enter> to display the first hit.");
spectra_search_box_->setToolTip(spectra_search_box_->whatsThis());
spectra_combo_box_ = new QComboBox(this);
spectra_combo_box_->setWhatsThis("Sets the column in which to search.");
spectra_combo_box_->setToolTip(spectra_combo_box_->whatsThis());
// search whenever text is typed (and highlight the hits)
connect(spectra_search_box_, &QLineEdit::textEdited, this, &SpectraTreeTab::spectrumSearchText_);
// .. show hit upon pressing Enter (internally we search again, since the user could have activated another layer with different selections after last search)
connect(spectra_search_box_, &QLineEdit::returnPressed, this, &SpectraTreeTab::searchAndShow_);
tmp_hbox_layout->addWidget(spectra_search_box_);
tmp_hbox_layout->addWidget(spectra_combo_box_);
spectra_widget_layout->addLayout(tmp_hbox_layout);
}
void SpectraTreeTab::spectrumSearchText_()
{
const QString& text = spectra_search_box_->text(); // get text from QLineEdit
if (!text.isEmpty())
{
Qt::MatchFlags matchflags = Qt::MatchFixedString;
matchflags |= Qt::MatchRecursive; // match subitems (below top-level)
// 'index' must be named identically for both data types
assert(ClmnPeak::HEADER_NAMES[ClmnPeak::SPEC_INDEX] == ClmnChrom::HEADER_NAMES[ClmnChrom::CHROM_INDEX]);
// ... for the following to work:
if (spectra_combo_box_->currentText() != ClmnPeak::HEADER_NAMES[ClmnPeak::SPEC_INDEX])
{ // only the 'index' has to be matched exactly
matchflags |= Qt::MatchStartsWith;
}
QList<QTreeWidgetItem*> searched = spectra_treewidget_->findItems(text, matchflags, spectra_combo_box_->currentIndex());
if (!searched.isEmpty())
{
spectra_treewidget_->clearSelection();
searched.first()->setSelected(true);
spectra_treewidget_->update();
spectra_treewidget_->scrollToItem(searched.first());
}
}
}
bool SpectraTreeTab::getSelectedScan(MSExperiment& exp, LayerDataBase::DataType& current_type) const
{
exp.clear(true);
QTreeWidgetItem* item = spectra_treewidget_->currentItem();
if (item == nullptr)
{
return false;
}
// getting the index works for PEAK and CHROM data
int index = item->data(ClmnPeak::SPEC_INDEX, Qt::DisplayRole).toInt();
if (spectra_treewidget_->headerItem()->text(ClmnChrom::MZ) == ClmnChrom::HEADER_NAMES[ClmnChrom::MZ])
{ // we currently show chromatogram data
current_type = LayerDataBase::DT_CHROMATOGRAM;
exp.addChromatogram(last_peakmap_->getChromatograms()[index]);
}
else
{
current_type = LayerDataBase::DT_PEAK;
exp.addSpectrum(last_peakmap_->getSpectra()[index]);
}
return true;
}
void SpectraTreeTab::itemSelectionChange_(QTreeWidgetItem* current, QTreeWidgetItem* /*previous*/)
{
if (current == nullptr)
{
return;
}
IndexExtrator ie(current);
if (ie.hasChromIndices())
{ // open several chromatograms at once
emit chromsSelected(listToVec(ie.res));
}
else
{
emit spectrumSelected(ie.spectrum_index);
}
}
void SpectraTreeTab::searchAndShow_()
{
spectrumSearchText_(); // update selection first (we might be in a new layer)
QList<QTreeWidgetItem*> selected = spectra_treewidget_->selectedItems();
// show the first selected item
if (!selected.empty())
{
itemSelectionChange_(selected.first(), selected.first());
}
}
void SpectraTreeTab::itemDoubleClicked_(QTreeWidgetItem* current)
{
if (current == nullptr)
{
return;
}
IndexExtrator ie(current);
if (!ie.hasChromIndices())
{
emit spectrumDoubleClicked(ie.spectrum_index);
}
else
{ // open several chromatograms at once
emit chromsDoubleClicked(listToVec(ie.res));
}
}
void SpectraTreeTab::spectrumContextMenu_(const QPoint& pos)
{
QTreeWidgetItem* item = spectra_treewidget_->itemAt(pos);
if (item)
{
// create menu
IndexExtrator ie(item);
QMenu context_menu(spectra_treewidget_);
context_menu.addAction("Show in 1D view", [&]()
{
if (!ie.hasChromIndices())
{
emit showSpectrumAsNew1D(ie.spectrum_index);
}
else
{ // open several chromatograms at once
emit showChromatogramsAsNew1D(listToVec(ie.res));
}
});
context_menu.addAction("Meta data", [&]()
{
emit showSpectrumMetaData(ie.spectrum_index);
});
context_menu.exec(spectra_treewidget_->viewport()->mapToGlobal(pos));
}
}
void populatePeakDataRow_(QTreeWidgetItem* item, const int index, const MSSpectrum& spec)
{
item->setText(ClmnPeak::MS_LEVEL, QString("MS") + QString::number(spec.getMSLevel()));
item->setData(ClmnPeak::SPEC_INDEX, Qt::DisplayRole, index);
item->setData(ClmnPeak::RT, Qt::DisplayRole, spec.getRT());
const std::vector<Precursor>& current_precursors = spec.getPrecursors();
if (!current_precursors.empty() || spec.metaValueExists("analyzer scan offset"))
{
double precursor_mz;
if (spec.metaValueExists("analyzer scan offset"))
{
precursor_mz = spec.getMetaValue("analyzer scan offset");
}
else
{
const Precursor& current_pc = current_precursors[0];
precursor_mz = current_pc.getMZ();
item->setText(ClmnPeak::DISSOCIATION, ListUtils::concatenate(current_pc.getActivationMethodsAsString(), ",").toQString());
}
item->setData(ClmnPeak::PRECURSOR_MZ, Qt::DisplayRole, precursor_mz);
}
item->setText(ClmnPeak::SCANTYPE, QString::fromStdString(spec.getInstrumentSettings().NamesOfScanMode[static_cast<size_t>(spec.getInstrumentSettings().getScanMode())]));
item->setText(ClmnPeak::ZOOM, (spec.getInstrumentSettings().getZoomScan() ? "yes" : "no"));
}
bool SpectraTreeTab::hasData(const LayerDataBase* layer)
{
if (layer == nullptr)
{
return false;
}
bool is_peak = layer->type == LayerDataBase::DT_PEAK;
bool is_chrom = layer->type == LayerDataBase::DT_CHROMATOGRAM;
return is_peak || is_chrom;
}
void SpectraTreeTab::updateEntries(LayerDataBase* layer)
{
if (layer == nullptr)
{
clear();
return;
}
layer_ = layer;
if (!spectra_treewidget_->isVisible() || spectra_treewidget_->signalsBlocked())
{
return;
}
spectra_treewidget_->blockSignals(true);
RAIICleanup clean([&](){
spectra_treewidget_->blockSignals(false);
});
QTreeWidgetItem* toplevel_item = nullptr;
QTreeWidgetItem* selected_item = nullptr;
QList<QTreeWidgetItem*> toplevel_items;
bool more_than_one_spectrum = true;
// Branch if the current layer is a spectrum
if (auto* lp = dynamic_cast<LayerDataPeak*>(layer))
{
Size spec_index = std::numeric_limits<Size>::max();
if (auto* layer_peak1d = dynamic_cast<LayerData1DPeak*>(lp))
{
spec_index = layer_peak1d->getCurrentIndex();
}
const auto& cl = *lp;
spectra_treewidget_->clear();
std::vector<QTreeWidgetItem *> parent_stack;
parent_stack.push_back(nullptr);
bool fail = false;
last_peakmap_ = &(cl.getPeakData()->getMSExperiment());
spectra_treewidget_->setHeaders(ClmnPeak::HEADER_NAMES);
for (Size i = 0; i < cl.getPeakData()->getMSExperiment().size(); ++i)
{
const MSSpectrum& current_spec = cl.getPeakData()->getMSExperiment()[i];
if (i > 0)
{
const MSSpectrum& prev_spec = cl.getPeakData()->getMSExperiment()[i-1];
// current MS level = previous MS level + 1 (e.g. current: MS2, previous: MS1)
if (current_spec.getMSLevel() == prev_spec.getMSLevel() + 1)
{
toplevel_item = new QTreeWidgetItem(parent_stack.back());
parent_stack.resize(parent_stack.size() + 1);
}
// current MS level = previous MS level (e.g. MS2,MS2 or MS1,MS1)
else if (current_spec.getMSLevel() == prev_spec.getMSLevel())
{
if (parent_stack.size() == 1)
{
toplevel_item = new QTreeWidgetItem();
}
else
{
toplevel_item = new QTreeWidgetItem(*(parent_stack.end() - 2));
}
}
// current MS level < previous MS level (e.g. MS1,MS2)
else if (current_spec.getMSLevel() < prev_spec.getMSLevel())
{
Int level_diff = prev_spec.getMSLevel() - current_spec.getMSLevel();
Size parent_index = 0;
if (parent_stack.size() - level_diff >= 2)
{
parent_index = parent_stack.size() - level_diff - 1;
QTreeWidgetItem * parent = parent_stack[parent_index];
toplevel_item = new QTreeWidgetItem(parent, parent_stack[parent_index + 1]);
}
else
{
toplevel_item = new QTreeWidgetItem((QTreeWidget *)nullptr);
}
parent_stack.resize(parent_index + 1);
}
else
{
std::cerr << "Cannot build treelike view for spectrum browser, generating flat list instead." << std::endl;
fail = true;
break;
}
}
else
{
toplevel_item = new QTreeWidgetItem();
}
parent_stack.back() = toplevel_item;
if (parent_stack.size() == 1)
{
toplevel_items.push_back(toplevel_item);
}
populatePeakDataRow_(toplevel_item, i, current_spec);
if (i == spec_index)
{
// just remember it, select later
selected_item = toplevel_item;
}
}
if (fail)
{
// generate flat list instead
spectra_treewidget_->clear();
toplevel_items.clear();
selected_item = nullptr;
for (Size i = 0; i < cl.getPeakData()->getMSExperiment().size(); ++i)
{
const MSSpectrum& current_spec = cl.getPeakData()->getMSExperiment()[i];
toplevel_item = new QTreeWidgetItem();
populatePeakDataRow_(toplevel_item, i, current_spec);
toplevel_items.push_back(toplevel_item);
if (i == spec_index)
{
// just remember it, select later
selected_item = toplevel_item;
}
}
}
spectra_treewidget_->addTopLevelItems(toplevel_items);
if (selected_item)
{
// now, select and scroll down to item
selected_item->setSelected(true);
// selected = for mouse clicks and multiselection,
// current = for arrow navigation and signifies THE ONE active item
spectra_treewidget_->setCurrentItem(selected_item);
spectra_treewidget_->scrollToItem(selected_item);
}
if (cl.getPeakData()->getMSExperiment().size() > 1)
{
more_than_one_spectrum = false; // why is this false if > 1???????
}
}
// Branch if the current layer is a chromatogram (either indicated by its
// type or by the flag which is set).
else if (auto* lp = dynamic_cast<LayerDataChrom*>(layer))
{
const auto cl = *lp;
LayerDataBase::ConstExperimentSharedPtrType exp = cl.getChromatogramData();
if (last_peakmap_ == &exp->getMSExperiment())
{ // underlying data did not change (which is ALWAYS the chromatograms, never peakdata!)
// --> Do not update (could be many 10k entries for sqMass data and the lag would be unbearable ...)
return;
}
last_peakmap_ = &exp->getMSExperiment();
spectra_treewidget_->clear();
// New data:
// We need to redraw the whole Widget because the we have changed all the layers.
// First we need to figure out which chromatogram was selected and
// whether multiple ones are selected.
bool multiple_select = false;
int this_selected_item = -1;
const MSExperiment& chrom_data = cl.getChromatogramData()->getMSExperiment();
if (!chrom_data.empty())
{
if (chrom_data.metaValueExists("multiple_select"))
{
multiple_select = chrom_data.getMetaValue("multiple_select").toBool();
}
if (chrom_data.metaValueExists("selected_chromatogram"))
{
this_selected_item = (int)chrom_data.getMetaValue("selected_chromatogram");
}
}
// create a header list
spectra_treewidget_->setHeaders(ClmnChrom::HEADER_NAMES);
if (exp->getMSExperiment().getChromatograms().size() > 1)
{
more_than_one_spectrum = false;
}
// try to retrieve the map from the cache if available
// TODO: same precursor mass / different precursors are not supported!
bool was_cached = map_precursor_to_chrom_idx_cache_.find((size_t)(exp.get())) != map_precursor_to_chrom_idx_cache_.end();
// create new cache or get the existing one
std::map<Precursor, std::vector<Size>, Precursor::MZLess>& map_precursor_to_chrom_idx = map_precursor_to_chrom_idx_cache_[(size_t)(exp.get())];
if (!was_cached)
{ // create cache: collect all precursor that fall into the mz rt window
for (auto it = exp->getMSExperiment().getChromatograms().cbegin(); it != exp->getMSExperiment().getChromatograms().cend(); ++it)
{
map_precursor_to_chrom_idx[it->getPrecursor()].push_back(it - exp->getMSExperiment().getChromatograms().begin());
}
}
int precursor_idx = 0;
for (const auto& [pc, indx] : map_precursor_to_chrom_idx)
{
// Top level precursor entry
toplevel_item = new QTreeWidgetItem();
toplevel_item->setText(ClmnChrom::TYPE, "Peptide");
toplevel_item->setData(ClmnChrom::TYPE, Qt::UserRole, vecToList(indx));
toplevel_item->setData(ClmnChrom::CHROM_INDEX, Qt::DisplayRole, precursor_idx++);
toplevel_item->setData(ClmnChrom::MZ, Qt::DisplayRole, pc.getMZ());
// Show the peptide sequence if available, otherwise show the m/z and charge only
QString description;
if (pc.metaValueExists("peptide_sequence"))
{
description = String(pc.getMetaValue("peptide_sequence")).toQString();
}
else if (pc.metaValueExists("description"))
{
description = String(pc.getMetaValue("description")).toQString();
}
toplevel_item->setText(ClmnChrom::DESCRIPTION, description);
toplevel_item->setData(ClmnChrom::CHARGE, Qt::DisplayRole, pc.getCharge());
toplevel_items.push_back(toplevel_item);
bool one_selected = false;
// Show single chromatogram: iterate over all chromatograms corresponding to the current precursor and add action for the single chromatogram
for (const Size chrom_idx : indx)
{
const MSChromatogram& current_chromatogram = exp->getMSExperiment().getChromatograms()[chrom_idx];
// Children chromatogram entry
QTreeWidgetItem* sub_item = new QTreeWidgetItem(toplevel_item);
if ((int)chrom_idx == this_selected_item)
{
one_selected = true;
selected_item = sub_item;
}
QString chrom_description = "ion";
if (pc.metaValueExists("description"))
{
chrom_description = String(pc.getMetaValue("description")).toQString();
}
sub_item->setText(ClmnChrom::TYPE, "Transition");
sub_item->setData(ClmnChrom::TYPE, Qt::UserRole, vecToList({chrom_idx}));
sub_item->setData(ClmnChrom::CHROM_INDEX, Qt::DisplayRole, (unsigned int)chrom_idx);
sub_item->setData(ClmnChrom::MZ, Qt::DisplayRole, current_chromatogram.getProduct().getMZ());
sub_item->setText(ClmnChrom::DESCRIPTION, chrom_description);
if (!current_chromatogram.empty())
{
sub_item->setData(ClmnChrom::RT_START, Qt::DisplayRole, current_chromatogram.front().getRT());
sub_item->setData(ClmnChrom::RT_END, Qt::DisplayRole, current_chromatogram.back().getRT());
}
sub_item->setText(ClmnChrom::CHROM_TYPE, MSChromatogram::ChromatogramNames[static_cast<size_t>(current_chromatogram.getChromatogramType())]);
}
if (one_selected && multiple_select)
{
selected_item = toplevel_item;
}
}
spectra_treewidget_->addTopLevelItems(toplevel_items);
if (selected_item && this_selected_item != -1)
{
// now, select and scroll down to item
spectra_treewidget_->setCurrentItem(selected_item);
selected_item->setSelected(true);
spectra_treewidget_->scrollToItem(selected_item);
// expand the item if necessary
if (!multiple_select)
{
selected_item->parent()->setExpanded(true);
}
}
}
// Branch if its neither (just draw an empty item)
else
{
spectra_treewidget_->setHeaders(QStringList() << "No peak map");
}
populateSearchBox_();
if (more_than_one_spectrum && toplevel_item != nullptr)
{ // not enabled
toplevel_item->setFlags(Qt::NoItemFlags);
}
// automatically set column width, depending on data
spectra_treewidget_->header()->setStretchLastSection(false);
spectra_treewidget_->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
}
void SpectraTreeTab::populateSearchBox_()
{
QStringList headers = spectra_treewidget_->getHeaderNames(WidgetHeader::WITH_INVISIBLE);
int current_index = spectra_combo_box_->currentIndex(); // when repainting we want the index to stay the same
spectra_combo_box_->clear();
spectra_combo_box_->addItems(headers);
spectra_combo_box_->setCurrentIndex(current_index);
}
void SpectraTreeTab::clear()
{
spectra_treewidget_->clear();
spectra_combo_box_->clear();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Plot1DWidget.cpp | .cpp | 8,021 | 245 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm, Timo Sachsenberg $
// --------------------------------------------------------------------------
// OpenMS
#include <OpenMS/VISUAL/Plot1DWidget.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/DIALOGS/Plot1DGoToDialog.h>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QScrollBar>
#include <QtWidgets/QFileDialog>
#include <QPainter>
#include <QPaintEvent>
#include <QtSvg/QtSvg>
#include <QtSvg/QSvgGenerator>
using namespace std;
namespace OpenMS
{
using namespace Internal;
using namespace Math;
Plot1DWidget::Plot1DWidget(const Param& preferences, const DIM gravity_axis, QWidget* parent) :
PlotWidget(preferences, parent)
{
x_axis_->setAllowShortNumbers(false);
y_axis_->setAllowShortNumbers(true);
y_axis_->setMinimumWidth(50);
flipped_y_axis_ = new AxisWidget(AxisPainter::LEFT, "", this);
flipped_y_axis_->setInverseOrientation(true);
flipped_y_axis_->setAllowShortNumbers(true);
flipped_y_axis_->setMinimumWidth(50);
flipped_y_axis_->hide();
spacer_ = new QSpacerItem(0, 0);
// set the label mode for the axes - side effect
setCanvas_(new Plot1DCanvas(preferences, gravity_axis, this));
// Delegate signals
connect(canvas(), &Plot1DCanvas::showCurrentPeaksAs2D, this, &Plot1DWidget::showCurrentPeaksAs2D);
connect(canvas(), &Plot1DCanvas::showCurrentPeaksAs3D, this, &Plot1DWidget::showCurrentPeaksAs3D);
connect(canvas(), &Plot1DCanvas::showCurrentPeaksAsIonMobility, this, &Plot1DWidget::showCurrentPeaksAsIonMobility);
connect(canvas(), &Plot1DCanvas::showCurrentPeaksAsDIA, this, &Plot1DWidget::showCurrentPeaksAsDIA);
}
void Plot1DWidget::recalculateAxes_()
{
// set names
x_axis_->setLegend(string(canvas()->getMapper().getDim(DIM::X).getDimName()));
y_axis_->setLegend(string(canvas()->getMapper().getDim(DIM::Y).getDimName()));
// determine which is the gravity axis (usually equals intensity axis (for LOG mode))
AxisWidget* other_axis = x_axis_;
AxisWidget* int_axis = y_axis_;
// in the unusual case: gravity is on X axis
if (canvas()->getGravitator().getGravityAxis() == DIM::X)
{
swap(other_axis, int_axis);
//vis_area_xy.swapDimensions();
//all_area_xy.swapDimensions();
}
// from now on, we can assume X-dim = data; Y-dim = gravity=intensity
// deal with log scaling for intensity axis
int_axis->setLogScale(canvas()->getIntensityMode() == PlotCanvas::IM_LOG);
// use visible area. Its the only authority!
const auto& xy_ranges = canvas()->getVisibleArea().getAreaXY();
x_axis_->setAxisBounds(xy_ranges.minX(), xy_ranges.maxX());
y_axis_->setAxisBounds(xy_ranges.minY(), xy_ranges.maxY());
// assume flipped-y-axis is identical
flipped_y_axis_->setLegend(y_axis_->getLegend());
flipped_y_axis_->setLogScale(y_axis_->isLogScale());
flipped_y_axis_->setAxisBounds(y_axis_->getAxisMinimum(), y_axis_->getAxisMaximum());
}
Plot1DWidget::~Plot1DWidget()
{
delete spacer_;
}
void Plot1DWidget::showGoToDialog()
{
Plot1DGoToDialog goto_dialog(this);
auto vis_area_xy = canvas_->getVisibleArea().getAreaXY();
auto all_area_xy = canvas_->getMapper().mapRange(canvas_->getDataRange());
// in the unusual case: gravity is on X axis
if (canvas()->getGravitator().getGravityAxis() == DIM::X)
{
vis_area_xy.swapDimensions();
all_area_xy.swapDimensions();
}
goto_dialog.setRange(vis_area_xy.minX(), vis_area_xy.maxX());
goto_dialog.setMinMaxOfRange(all_area_xy.minX(), all_area_xy.maxX());
if (goto_dialog.exec())
{
goto_dialog.fixRange();
PlotCanvas::AreaXYType area(goto_dialog.getMin(), 0, goto_dialog.getMax(), 0);
if (canvas()->getGravitator().getGravityAxis() == DIM::X)
{
area.swapDimensions();
}
auto va_new = canvas_->getVisibleArea().cloneWith(area);
canvas()->setVisibleArea(va_new);
}
}
void Plot1DWidget::showLegend(bool show)
{
y_axis_->showLegend(show);
flipped_y_axis_->showLegend(show);
x_axis_->showLegend(show);
update();
}
void Plot1DWidget::hideAxes()
{
y_axis_->hide();
flipped_y_axis_->hide();
x_axis_->hide();
}
void Plot1DWidget::toggleMirrorView(bool mirror)
{
if (mirror)
{
grid_->addItem(spacer_, 1, 1);
grid_->addWidget(flipped_y_axis_, 2, 1);
grid_->removeWidget(canvas());
grid_->removeWidget(x_axis_);
grid_->removeWidget(x_scrollbar_);
grid_->addWidget(canvas(), 0, 2, 3, 1); // rowspan = 3
grid_->addWidget(x_axis_, 3, 2);
grid_->addWidget(x_scrollbar_, 4, 2);
flipped_y_axis_->show();
}
else
{
grid_->removeWidget(canvas());
grid_->removeWidget(flipped_y_axis_);
flipped_y_axis_->hide();
grid_->removeItem(spacer_);
grid_->removeWidget(x_axis_);
grid_->removeWidget(x_scrollbar_);
grid_->addWidget(canvas(), 0, 2);
grid_->addWidget(x_axis_, 1, 2);
grid_->addWidget(x_scrollbar_, 2, 2);
}
}
void Plot1DWidget::performAlignment(Size layer_index_1, Size layer_index_2, const Param& param)
{
spacer_->changeSize(0, 10);
grid_->removeWidget(y_axis_);
grid_->removeWidget(flipped_y_axis_);
grid_->addWidget(y_axis_, 0, 1);
grid_->addWidget(flipped_y_axis_, 2, 1);
canvas()->performAlignment(layer_index_1, layer_index_2, param);
}
void Plot1DWidget::resetAlignment()
{
spacer_->changeSize(0, 0);
grid_->removeWidget(y_axis_);
grid_->removeWidget(flipped_y_axis_);
grid_->addWidget(y_axis_, 0, 1);
grid_->addWidget(flipped_y_axis_, 2, 1);
}
void Plot1DWidget::renderForImage(QPainter& painter)
{
bool x_visible = x_scrollbar_->isVisible();
bool y_visible = y_scrollbar_->isVisible();
x_scrollbar_->hide();
y_scrollbar_->hide();
this->render(&painter);
x_scrollbar_->setVisible(x_visible);
y_scrollbar_->setVisible(y_visible);
}
void Plot1DWidget::saveAsImage()
{
QString filter = "Raster images *.bmp *.png *.jpg *.gif (*.bmp *.png *.jpg *.gif);;Vector images *.svg (*.svg)";
QString sel_filter;
QString file_name = QFileDialog::getSaveFileName(this, "Save File", "", filter, &sel_filter);
bool x_visible = x_scrollbar_->isVisible();
bool y_visible = y_scrollbar_->isVisible();
x_scrollbar_->hide();
y_scrollbar_->hide();
if (sel_filter.contains(".svg", Qt::CaseInsensitive)) // svg vector format
{
QSvgGenerator generator;
generator.setFileName(file_name);
generator.setSize(QSize(this->width(), this->height()));
generator.setViewBox(QRect(0, 0, this->width() - 1, this->height() - 1));
generator.setTitle(file_name);
generator.setDescription("TOPPView generated SVG");
QPainter painter;
painter.begin(&generator);
painter.save();
painter.translate(QPoint(y_axis_->pos()));
y_axis_->paint(&painter, new QPaintEvent(y_axis_->contentsRect()));
painter.restore();
painter.save();
painter.translate(QPoint(canvas_->pos()));
dynamic_cast<Plot1DCanvas*>(canvas_)->paint(&painter, new QPaintEvent(canvas_->contentsRect()));
painter.restore();
painter.save();
painter.translate(QPoint(x_axis_->pos()));
x_axis_->paint(&painter, new QPaintEvent(x_axis_->contentsRect()));
painter.restore();
painter.end();
x_scrollbar_->setVisible(x_visible);
y_scrollbar_->setVisible(y_visible);
}
else // raster graphics formats
{
QPixmap pixmap = this->grab();
x_scrollbar_->setVisible(x_visible);
y_scrollbar_->setVisible(y_visible);
pixmap.save(file_name);
}
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerData1DIonMobility.cpp | .cpp | 3,237 | 94 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerData1DIonMobility.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/Painter1DBase.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
#include <QMenu>
using namespace std;
namespace OpenMS
{
std::unique_ptr<LayerStoreData> LayerData1DIonMobility::storeVisibleData(const RangeAllType& /*visible_range*/, const DataFilters& /*layer_filters*/) const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
// does not exist yet...
}
std::unique_ptr<LayerStoreData> LayerData1DIonMobility::storeFullData() const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
// does not exist yet...
}
QMenu* LayerData1DIonMobility::getContextMenuAnnotation(Annotation1DItem* /*annot_item*/, bool& /*need_repaint*/)
{
auto* context_menu = new QMenu("MobilityPeak", nullptr);
return context_menu;
}
PeakIndex LayerData1DIonMobility::findClosestDataPoint(const RangeAllType& area) const
{
MobilityPeak1D peak_lt(area.getMinMobility(), area.getMinIntensity()), peak_rb(area.getMaxMobility(), area.getMaxIntensity());
// reference to the current data
const auto& mg = getCurrentMobilogram();
const Size spectrum_index = getCurrentIndex();
// get iterator on first peak with lower position than interval_start
auto left_it = lower_bound(mg.begin(), mg.end(), peak_lt, PeakType::PositionLess());
// get iterator on first peak with higher position than interval_end
auto right_it = lower_bound(left_it, mg.end(), peak_rb, PeakType::PositionLess());
if (left_it == right_it) // both are equal => no peak falls into this interval
{
return PeakIndex();
}
if (left_it == right_it - 1)
{
return PeakIndex(spectrum_index, left_it - mg.begin());
}
auto nearest_it = left_it;
const auto center_intensity = (peak_lt.getIntensity() + peak_rb.getIntensity()) * 0.5;
for (auto it = left_it; it != right_it; ++it)
{
if (abs(center_intensity - it->getIntensity()) < abs(center_intensity - nearest_it->getIntensity()))
{
nearest_it = it;
}
}
return PeakIndex(spectrum_index, nearest_it - mg.begin());
}
std::unique_ptr<Painter1DBase> LayerData1DIonMobility::getPainter1D() const
{
return make_unique<Painter1DIonMobility>(this);
}
Annotation1DItem* LayerData1DIonMobility::addPeakAnnotation(const PeakIndex& peak_index, const QString& text, const QColor& color)
{
auto peak = getCurrentMobilogram()[peak_index.peak];
auto* item = new Annotation1DPeakItem<decltype(peak)>(peak, text, color);
item->setSelected(false);
getCurrentAnnotations().push_front(item);
return item;
}
}// namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerData1DBase.cpp | .cpp | 1,404 | 44 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerData1DBase.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotations1DContainer.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
using namespace std;
namespace OpenMS
{
String LayerData1DBase::getDecoratedName() const
{
String n = LayerDataBase::getDecoratedName();
if (flipped)
{
n += " [flipped]";
}
return n;
}
void LayerData1DBase::setCurrentIndex(Size index)
{
current_idx_ = index;
if (current_idx_ >= annotations_1d_.size())
{
annotations_1d_.resize(current_idx_ + 1);
}
// Clear peak colors to force reinitialization for the new spectrum
// Unlike annotations which persist across spectra, peak colors need to be regenerated
// to match the size of the new spectrum, preventing "Peak color array size doesn't
// match number of peaks" errors that occur when switching between spectra with
// different numbers of peaks
peak_colors_1d.clear();
}
}// namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/MultiGradient.cpp | .cpp | 6,824 | 280 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/MultiGradient.h>
#include <cstdlib>
#include <limits>
#include <sstream>
#include <utility>
using namespace std;
namespace OpenMS
{
using namespace Exception;
MultiGradient::MultiGradient() :
pos_col_(),
interpolation_mode_(IM_LINEAR),
pre_min_(0),
pre_size_(0),
pre_steps_(0)
{
pos_col_[0] = Qt::white;
pos_col_[100] = Qt::black;
}
MultiGradient::MultiGradient(const MultiGradient & multigradient) = default;
MultiGradient & MultiGradient::operator=(const MultiGradient & rhs)
{
if (this == &rhs)
{
return *this;
}
pos_col_ = rhs.pos_col_,
interpolation_mode_ = rhs.interpolation_mode_;
pre_ = rhs.pre_;
pre_min_ = rhs.pre_min_;
pre_size_ = rhs.pre_size_;
pre_steps_ = rhs.pre_steps_;
return *this;
}
MultiGradient::~MultiGradient() = default;
Size MultiGradient::size() const
{
return pos_col_.size();
}
void MultiGradient::insert(double position, QColor color)
{
if (position >= 0 && position <= 100)
{
pos_col_[position] = std::move(color);
}
else
{
throw InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
}
UInt MultiGradient::position(UInt index)
{
if (index > size() - 1)
{
throw IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
map<double, QColor>::iterator it = pos_col_.begin();
for (Size i = 0; i < index; ++i)
{
++it;
}
return it->first;
}
QColor MultiGradient::color(UInt index)
{
if (index > size() - 1)
{
throw IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
map<double, QColor>::iterator it = pos_col_.begin();
for (Size i = 0; i < index; ++i)
{
++it;
}
return it->second;
}
QColor MultiGradient::interpolatedColorAt(double position) const
{
if (position <= 0.0)
{
return pos_col_.begin()->second;
}
if (position >= 100.0)
{
return (--(pos_col_.end()))->second;
}
//linear
if (interpolation_mode_ == IM_LINEAR)
{
map<double, QColor>::const_iterator it1 = pos_col_.lower_bound(position);
if (std::abs(it1->first - position) < numeric_limits<double>::epsilon()) // compare double
{
return it1->second;
}
else
{
map<double, QColor>::const_iterator it0 = it1;
--it0;
double factor = (position - it0->first) / (it1->first - it0->first);
return QColor(Int(factor * it1->second.red() + (1 - factor) * it0->second.red() + 0.001)
, Int(factor * it1->second.green() + (1 - factor) * it0->second.green() + 0.001)
, Int(factor * it1->second.blue() + (1 - factor) * it0->second.blue() + 0.001));
}
}
//stairs
else
{
map<double, QColor>::const_iterator it = pos_col_.upper_bound(position);
--it;
return it->second;
}
}
QColor MultiGradient::interpolatedColorAt(double position, double min, double max) const
{
return interpolatedColorAt((position - min) / (max - min) * 100.0);
}
void MultiGradient::setInterpolationMode(MultiGradient::InterpolationMode mode)
{
interpolation_mode_ = mode;
}
MultiGradient::InterpolationMode MultiGradient::getInterpolationMode() const
{
return interpolation_mode_;
}
string MultiGradient::toString() const
{
stringstream out;
//Interpolation Mode
if (getInterpolationMode() == IM_LINEAR)
{
out << "Linear|";
}
else if (getInterpolationMode() == IM_STAIRS)
{
out << "Stairs|";
}
for (map<double, QColor>::const_iterator it = pos_col_.begin(); it != pos_col_.end(); ++it)
{
if (it != pos_col_.begin())
{
out << ";";
}
out << it->first << "," << it->second.name().toStdString();
}
return out.str();
}
void MultiGradient::fromString(const string & gradient)
{
pos_col_.clear();
if (gradient.empty())
{
pos_col_[0] = Qt::white;
pos_col_[100] = Qt::black;
return;
}
string g(gradient);
string::iterator tmp(g.begin());
double tmp_pos = 0;
for (string::iterator it = g.begin(); it != g.end(); ++it)
{
if (*it == '|')
{
//interploation mode
if (string(tmp, it) == "Linear")
{
setInterpolationMode(IM_LINEAR);
}
else if (string(tmp, it) == "Stairs")
{
setInterpolationMode(IM_STAIRS);
}
}
else if (*it == ';')
{
pos_col_[tmp_pos] = QColor(string(tmp, it).c_str());
tmp = it + 1;
}
else if (*it == ',')
{
tmp_pos = QString(string(tmp, it).c_str()).toDouble();
tmp = it + 1;
}
}
// last entry
pos_col_[tmp_pos] = QColor(string(tmp, g.end()).c_str());
}
void MultiGradient::activatePrecalculationMode(double min, double max, UInt steps)
{
//add security margin to range to avoid numerical problems
pre_min_ = std::min(min, max) - 0.000005;
pre_size_ = fabs(max - min) + 0.00001;
pre_steps_ = steps - 1;
pre_.clear();
pre_.reserve(steps);
for (Size step = 0; step < steps; ++step)
{
pre_.push_back(interpolatedColorAt(step, 0, pre_steps_));
//cout << pre_.back().red() << " " << pre_.back().green() << " " << pre_.back().blue() << endl;
}
}
void MultiGradient::deactivatePrecalculationMode()
{
pre_.clear();
}
bool MultiGradient::exists(double position)
{
return pos_col_.find(position) != pos_col_.end();
}
bool MultiGradient::remove(double position)
{
if (position < 0 + std::numeric_limits<double>::epsilon() || position > 100 - std::numeric_limits<double>::epsilon())
{
return false;
}
map<double, QColor>::iterator it = pos_col_.find(position);
if (it != pos_col_.end())
{
pos_col_.erase(it);
return true;
}
return false;
}
// static
MultiGradient MultiGradient::getDefaultGradientLinearIntensityMode()
{
MultiGradient mg;
mg.fromString("Linear|0,#eeeeee;1,#ffea00;6,#ff0000;14,#aa00ff;23,#5500ff;100,#000000");
return mg;
}
// static
MultiGradient MultiGradient::getDefaultGradientLogarithmicIntensityMode()
{
MultiGradient mg;
mg.fromString("Linear|0,#ffea00;6,#ff0000;14,#aa00ff;23,#5500ff;100,#000000");
return mg;
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TVSpectraViewController.cpp | .cpp | 6,463 | 172 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TVSpectraViewController.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/KERNEL/ChromatogramTools.h>
#include <OpenMS/KERNEL/OnDiscMSExperiment.h>
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/Plot1DWidget.h>
#include <QtWidgets/QMessageBox>
#include <QtCore/QString>
using namespace OpenMS;
using namespace std;
namespace OpenMS
{
TVSpectraViewController::TVSpectraViewController(TOPPViewBase* parent):
TVControllerBase(parent)
{
}
void TVSpectraViewController::showSpectrumAsNew1D(int index)
{
// basic behavior 1
LayerDataBase& layer = tv_->getActiveCanvas()->getCurrentLayer();
// create new 1D widget; if we return due to error, the widget will be cleaned up automatically
unique_ptr<Plot1DWidget> wp(new Plot1DWidget(tv_->getCanvasParameters(1), DIM::Y, (QWidget*)tv_->getWorkspace()));
Plot1DWidget* w = wp.get();
// copy data from current layer (keeps the TYPE and underlying data identical)
if (!w->canvas()->addLayer(layer.to1DLayer()))
{
// Behavior if its neither (user may have clicked on an empty tree or a
// dummy entry as drawn by SpectraTreeTab::updateEntries)
QMessageBox::critical(w, "Error", "Cannot open data that is neither chromatogram nor spectrum data. Aborting!");
return;
}
w->canvas()->activateSpectrum(index);
// set visible area to visible area in 2D view
w->canvas()->setVisibleArea(tv_->getActiveCanvas()->getVisibleArea());
// set relative (%) view of visible area
w->canvas()->setIntensityMode(PlotCanvas::IM_SNAP);
tv_->showPlotWidgetInWindow(wp.release());
tv_->updateLayerBar();
tv_->updateViewBar();
tv_->updateFilterBar();
tv_->updateMenu();
}
bool add1DChromLayers(const std::vector<int>& indices,
Plot1DWidget* target,
const LayerDataDefs::ExperimentSharedPtrType& chrom_exp_sptr,
const LayerDataDefs::ODExperimentSharedPtrType& ondisc_sptr,
const OSWDataSharedPtrType& chrom_annotation,
const String& layer_basename,
const String& filename)
{
//
for (const auto& index : indices)
{
// get caption (either chromatogram idx or peptide sequence, if available)
String basename_suffix;
if (chrom_exp_sptr->getMSExperiment().metaValueExists("peptide_sequence"))
{
basename_suffix = String(chrom_exp_sptr->getMSExperiment().getMetaValue("peptide_sequence"));
}
((basename_suffix += "[") += index) += "]";
// add chromatogram data
if (!target->canvas()->addChromLayer(chrom_exp_sptr, ondisc_sptr, chrom_annotation, index, filename, layer_basename, basename_suffix))
{
return false;
}
}
return true;
}
void TVSpectraViewController::showChromatogramsAsNew1D(const std::vector<int>& indices)
{
// show multiple spectra together is only used for chromatograms directly
// where multiple (SRM) traces are shown together
auto layer_chrom = dynamic_cast<LayerDataChrom*>(&tv_->getActiveCanvas()->getCurrentLayer());
if (!layer_chrom) return;
auto exp_sptr = layer_chrom->getChromatogramData();
auto ondisc_sptr = layer_chrom->getOnDiscPeakData();
// open new 1D widget
auto* w = new Plot1DWidget(tv_->getCanvasParameters(1), DIM::Y, (QWidget *)tv_->getWorkspace());
// use RT + intensity mapping
w->setMapper({{DIM_UNIT::RT, DIM_UNIT::INT}});
if (!add1DChromLayers(indices, w, layer_chrom->getChromatogramData(), layer_chrom->getOnDiscPeakData(),
layer_chrom->getChromatogramAnnotation(), layer_chrom->getName(), layer_chrom->filename))
{
return;
}
// set relative (%) view of visible area (recalcs snap factor)
w->canvas()->setIntensityMode(PlotCanvas::IM_SNAP);
tv_->showPlotWidgetInWindow(w);
tv_->updateBarsAndMenus();
}
// called by SpectraTreeTab::spectrumSelected()
void TVSpectraViewController::activate1DSpectrum(int index)
{
Plot1DWidget* widget_1d = tv_->getActive1DWidget();
// return if no active 1D widget is present or no layers are present (e.g. the addPeakLayer call failed)
if (widget_1d == nullptr) return;
if (widget_1d->canvas()->getLayerCount() == 0) return;
widget_1d->canvas()->activateSpectrum(index);
}
// called by SpectraTreeTab::chromsSelected()
void TVSpectraViewController::activate1DSpectrum(const std::vector<int>& indices)
{
Plot1DWidget * widget_1d = tv_->getActive1DWidget();
// return if no active 1D widget is present or no layers are present (e.g. the addPeakLayer call failed)
if (widget_1d == nullptr) return;
if (widget_1d->canvas()->getLayerCount() == 0) return;
const auto* layer = dynamic_cast<LayerDataChrom*>(&widget_1d->canvas()->getCurrentLayer());
if (!layer) return;
auto chrom_sptr = layer->getChromatogramData();
auto ondisc_sptr = layer->getOnDiscPeakData();
auto annotation = layer->getChromatogramAnnotation();
const String basename = layer->getName();
const String filename = layer->filename;
widget_1d->canvas()->removeLayers(); // this actually deletes layer
layer = nullptr; // ... make sure its not used any more
widget_1d->canvas()->blockSignals(true);
RAIICleanup clean([&]() {widget_1d->canvas()->blockSignals(false); });
if (!add1DChromLayers(indices, widget_1d, chrom_sptr, ondisc_sptr, annotation, basename,
filename))
{
return;
}
// set relative (%) view of visible area (recalcs snap factor)
widget_1d->canvas()->setIntensityMode(PlotCanvas::IM_SNAP);
tv_->updateBarsAndMenus(); // needed since we blocked update above (to avoid repeated layer updates for many layers!)
}
void TVSpectraViewController::deactivate1DSpectrum(int /* spectrum_index */)
{
// no special handling of spectrum deactivation needed
}
} // OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerDataIonMobility.cpp | .cpp | 3,195 | 94 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerDataIonMobility.h>
#include <OpenMS/KERNEL/DimMapper.h>
#include <OpenMS/VISUAL/Painter2DBase.h>
#include <OpenMS/VISUAL/LayerData1DIonMobility.h>
using namespace std;
namespace OpenMS
{
LayerDataIonMobility::LayerDataIonMobility() : LayerDataBase(LayerDataBase::DT_PEAK)
{
}
LayerDataIonMobility::LayerDataIonMobility(const LayerDataIonMobility& ld)
: LayerDataBase(static_cast<const LayerDataBase&>(ld))
{
}
std::unique_ptr<Painter2DBase> LayerDataIonMobility::getPainter2D() const
{
return make_unique<Painter2DIonMobility>(this);
}
std::unique_ptr<LayerData1DBase> LayerDataIonMobility::to1DLayer() const
{
return make_unique<LayerData1DIonMobility>(*this);
}
std::unique_ptr<LayerStoreData> LayerDataIonMobility::storeVisibleData(const RangeAllType& /*visible_range*/, const DataFilters& /*layer_filters*/) const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
// does not exist yet...
/*auto ret = make_unique<LayerStoreDataMobilogramVisible>();
ret->storeVisibleMobilogram(single_mobilogram_, visible_range, layer_filters);
return ret;*/
}
std::unique_ptr<LayerStoreData> LayerDataIonMobility::storeFullData() const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
// does not exist yet...
/*auto ret = make_unique<LayerStoreDataMobilogramAll>();
ret->storeFullMobilograms(*peak_map_.get());
return ret;*/
}
LayerDataIonMobility::ProjectionData LayerDataIonMobility::getProjection(const DIM_UNIT /*unit_x*/, const DIM_UNIT /*unit_y*/, const RangeAllType& /*area*/) const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
/*ProjectionData result;
return result;*/
}
PointXYType LayerDataIonMobility::peakIndexToXY(const PeakIndex& peak, const DimMapper<2>& mapper) const
{
if (peak.spectrum != 0)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Currently only one mobilogram is supported!", String(peak.spectrum));
}
return mapper.map(single_mobilogram_, peak.peak);
}
String LayerDataIonMobility::getDataArrayDescription(const PeakIndex& peak_index)
{
if (peak_index.spectrum != 0)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Currently only one mobilogram is supported!", String(peak_index.spectrum));
}
// no array data exists for mobilograms (yet)
String status;
return status;
}
std::unique_ptr<LayerStatistics> LayerDataIonMobility::getStats() const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
// does not exist yet...
//return make_unique<LayerStatisticsIonMobilityMap>(single_mobilogram_);
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/InputFileList.cpp | .cpp | 5,582 | 208 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/InputFileList.h>
#include <ui_InputFileList.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/DIALOGS/TOPPASInputFileDialog.h>
#include <QtWidgets/QFileDialog>
#include <QApplication>
#include <QClipboard>
#include <QKeyEvent>
#include <QUrl>
#include <QMimeData>
#include <QString>
#include <QtWidgets/QFileDialog>
#include <QMessageBox>
#include <QListWidgetItem>
//#include <iostream>
using namespace std;
namespace OpenMS
{
namespace Internal
{
InputFileList::InputFileList(QWidget *parent) :
QWidget(parent),
ui_(new Ui::InputFileList)
{
ui_->setupUi(this);
connect(ui_->add_button, SIGNAL(clicked()), this, SLOT(showFileDialog()));
connect(ui_->edit_button, SIGNAL(clicked()), this, SLOT(editCurrentItem()));
connect(ui_->remove_button, SIGNAL(clicked()), this, SLOT(removeSelected()));
connect(ui_->remove_all_button, SIGNAL(clicked()), this, SLOT(removeAll()));
}
InputFileList::~InputFileList()
{
delete ui_;
}
void InputFileList::dragEnterEvent(QDragEnterEvent* e)
{
// file dropped from a window manager come as URLs
if (e->mimeData()->hasUrls())
{
e->acceptProposedAction();
}
}
void InputFileList::dropEvent(QDropEvent* e)
{
QStringList files;
for (const QUrl& url : e->mimeData()->urls())
{
files << url.toLocalFile();
}
addFiles_(files);
}
void InputFileList::dragMoveEvent(QDragMoveEvent* p_event)
{
// TODO allow filtering?
//if (!p_event->mimeData()->hasFormat(MY_MIMETYPE))
//{
// p_event->ignore();
// return;
//}
p_event->accept();
}
void InputFileList::keyPressEvent(QKeyEvent* e) {
// when Ctrl-C is pressed, copy all selected files to clipboard as text
if (e->matches(QKeySequence::Copy))
{
QStringList strings;
QList<QListWidgetItem*> selected_items = ui_->input_file_list->selectedItems();
for (QListWidgetItem * item : selected_items)
{
strings << item->text();
}
QApplication::clipboard()->setText(strings.join("\n"));
e->accept(); // do not propagate upstream
}
// exit on escape (without saving the list)
else if (e->key() == Qt::Key_Escape)
{
this->close();
}
// delete currently selected items
else if (e->key() == Qt::Key_Delete)
{
removeSelected();
}
}
void InputFileList::showFileDialog()
{
QStringList file_names = QFileDialog::getOpenFileNames(this, tr("Select input file(s)"), cwd_);
addFiles_(file_names);
}
void InputFileList::removeSelected()
{
QList<QListWidgetItem*> selected_items = ui_->input_file_list->selectedItems();
for (QListWidgetItem * item : selected_items)
{
ui_->input_file_list->takeItem(ui_->input_file_list->row(item));
}
updateCWD_();
}
void InputFileList::removeAll()
{
ui_->input_file_list->clear();
updateCWD_();
}
void InputFileList::getFilenames(QStringList& files) const
{
files.clear();
for (int i = 0; i < ui_->input_file_list->count(); ++i)
{
files.push_back(ui_->input_file_list->item(i)->text());
}
}
StringList InputFileList::getFilenames() const
{
int nr_files = ui_->input_file_list->count();
StringList files;
for (int i = 0; i < nr_files; ++i)
{
files.push_back(ui_->input_file_list->item(i)->text());
}
return files;
}
void OpenMS::Internal::InputFileList::setFilenames(const QStringList& files)
{
addFiles_(files);
}
const QString& InputFileList::getCWD() const
{
return cwd_;
}
void OpenMS::Internal::InputFileList::setCWD(const QString& cwd, bool force)
{
if (force || (cwd_.isEmpty() && !cwd.isEmpty())) // do not set cwd_ as empty (does not help the user in browsing for files)
{
cwd_ = cwd;
}
emit updatedCWD(cwd_);
}
void InputFileList::editCurrentItem()
{
QListWidgetItem* item = ui_->input_file_list->currentItem();
if (!item)
{
if (ui_->input_file_list->count() == 0)
{
return;
}
// use the first item if none is selected
ui_->input_file_list->setCurrentItem(ui_->input_file_list->item(0));
item = ui_->input_file_list->currentItem();
}
TOPPASInputFileDialog tifd(item->text());
if (tifd.exec())
{
item->setText(tifd.getFilename());
updateCWD_();
}
}
void InputFileList::addFiles_(const QStringList& files)
{
if (!files.isEmpty())
{
ui_->input_file_list->addItems(files);
setCWD(File::path(files.back()).toQString()); // emit the signal
}
}
void OpenMS::Internal::InputFileList::updateCWD_()
{
QListWidgetItem* item = ui_->input_file_list->currentItem();
// also update with empty, to ensure emitting the updatedCWD() signal
setCWD(item ? item->text() : "", false);
}
} //namespace Internal
} //namspace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/AxisTickCalculator.cpp | .cpp | 3,422 | 150 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// STL
#include <iostream>
#include <cmath>
#include <numeric>
// OpenMS
#include <OpenMS/VISUAL/AxisTickCalculator.h>
#include <OpenMS/MATH/MathFunctions.h>
using namespace std;
namespace OpenMS
{
using namespace Math;
void AxisTickCalculator::calcGridLines(double x1, double x2, GridVector & grid)
{
grid.clear();
if (std::isnan(x1) || std::isnan(x2))
{
return;
}
if (x1 > -0.0001 && x1 < 0.0001)
{
x1 = 0.0001;
}
double dx = x2 - x1;
if (dx < 0.0000001)
{
return;
}
double epsilon = dx / 200;
double sDecPow = floor(log10(dx));
double sDec = pow(10.0, sDecPow);
UInt n_max_big_gridlines = (UInt)floor(dx / sDec);
std::vector<double> big;
double currGL = ceilDecimal(x1, (UInt)sDecPow);
// big grid lines
while (currGL < (x2 + epsilon))
{
big.push_back(currGL);
currGL += sDec;
}
grid.push_back(big);
// only one major grid line
if (n_max_big_gridlines <= 3)
{
std::vector<double> small;
currGL = grid[0][0] - sDec * 9 / 10;
while (currGL < (x2 + epsilon))
{
// check if in visible area
if (currGL > x1)
{
// check for overlap with big gridlines
bool overlap = false;
for (Size i = 0; i != big.size(); ++i)
{
if (fabs(big[i] - currGL) < epsilon)
{
overlap = true;
}
}
if (!overlap)
{
small.push_back(currGL);
}
}
currGL += sDec / 10;
}
grid.push_back(small);
return;
}
// four or more major grid lines
std::vector<double> small;
currGL = grid[0][0] - sDec / 2;
while (currGL < (x2 + epsilon))
{
if (currGL > x1)
{
small.push_back(currGL);
}
currGL += sDec;
}
grid.push_back(small);
}
void AxisTickCalculator::calcLogGridLines(double x1, double x2, GridVector& grid)
{
if (std::isnan(x1)) {
x1 = 0; // may happen for negative values
}
if (std::isnan(x2))
{
x2 = 0; // may happen for negative values
}
double dx = x2 - x1;
if (dx < 0.00000001)
{
return;
}
// small ticks covering one log order
static const double TICK_VALUES[] = {log10(2.0), log10(3.0), log10(4.0), log10(5.0), log10(6.0), log10(7.0), log10(8.0), log10(9.0)};
static constexpr int TICK_COUNT = sizeof(TICK_VALUES) / sizeof(decltype(TICK_VALUES[0]));
grid.clear();
grid.resize(2);
Int x1floor = (Int)floor(x1);
Int x2ceil = (Int)ceil(x2);
std::vector<double>& big = grid[0];
std::vector<double>& small = grid[1];
big.resize(x2ceil - x1floor);
std::iota(big.begin(), big.end(), x1floor);
for (const auto b : big)
{
for (Int j = 0; j != TICK_COUNT; ++j)
{
const auto mini_tick = b + TICK_VALUES[j];
if (mini_tick > x2)
{
break;
}
small.push_back(mini_tick);
}
}
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASOutputVertex.cpp | .cpp | 3,975 | 134 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASOutputVertex.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/TOPPASEdge.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <QtCore/QDir>
namespace OpenMS
{
TOPPASOutputVertex::TOPPASOutputVertex(const TOPPASOutputVertex& rhs):
TOPPASVertex(rhs),
output_folder_name_() // leave empty on copy, otherwise we will have conficting output folder names
{
}
TOPPASOutputVertex& TOPPASOutputVertex::operator=(const TOPPASOutputVertex& rhs)
{
TOPPASVertex::operator=(rhs);
output_folder_name_ = ""; // leave empty on copy, otherwise we will have conficting output folder names
return *this;
}
void TOPPASOutputVertex::setOutputFolderName(const QString& name)
{
if (output_folder_name_ != name)
{
output_folder_name_ = name;
emit outputFolderNameChanged(); // enable storing of modified pipeline
}
}
const QString& TOPPASOutputVertex::getOutputFolderName() const
{
return output_folder_name_;
}
void TOPPASOutputVertex::inEdgeHasChanged()
{
reset(true);
qobject_cast<TOPPASScene*>(scene())->updateEdgeColors();
TOPPASVertex::inEdgeHasChanged();
}
void TOPPASOutputVertex::openContainingFolder() const
{
GUIHelpers::openFolder(getFullOutputDirectory().toQString());
}
String TOPPASOutputVertex::getFullOutputDirectory() const
{
TOPPASScene* ts = qobject_cast<TOPPASScene*>(scene());
auto dir = String(ts->getOutDir()).substitute("\\", "/").ensureLastChar('/') + getOutputDir();
String clean_dir = QDir::cleanPath(dir.toQString());
return clean_dir.substitute("\\", "/").ensureLastChar('/');
}
String TOPPASOutputVertex::getOutputDir() const
{
String dir = "TOPPAS_out/";
if (output_folder_name_.isEmpty())
{
TOPPASEdge* e = *inEdgesBegin();
if (e == nullptr)
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"To open the output folder, an input edge is required to knit a folder name.");
}
const TOPPASVertex* tv = e->getSourceVertex();
// create meaningful output name using vertex + TOPP name + output parameter, e.g. "010-FileConverter-out"
dir += get3CharsNumber_(topo_nr_) + "-" + tv->getName() + "-" + e->getSourceOutParamName().remove(':');
}
else {
dir += output_folder_name_;
}
dir.ensureLastChar('/');
return dir;
}
String TOPPASOutputVertex::createOutputDir() const
{
String full_dir = getFullOutputDirectory();
if (! File::exists(full_dir))
{
if (! File::makeDir(full_dir)) { std::cerr << "Could not create path " << full_dir << std::endl; }
}
return full_dir;
}
void TOPPASOutputVertex::setTopoNr(UInt nr)
{
if (topo_nr_ != nr)
{
// topological number changes --> output dir changes --> reset
reset(true);
topo_nr_ = nr;
}
}
void TOPPASOutputVertex::reset(bool reset_all_files)
{
__DEBUG_BEGIN_METHOD__
files_total_ = 0;
files_written_ = 0;
TOPPASVertex::reset();
if (reset_all_files)
{
// do not actually delete the output files here
// for TOPPASOutputFolderVertex we do not even know which files were written by the tool
// and which were already there (we do not want to delete user files)
}
__DEBUG_END_METHOD__
}
void TOPPASOutputVertex::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* /*e*/)
{
openContainingFolder();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TreeView.cpp | .cpp | 3,234 | 109 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TreeView.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/Qt5Port.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QHeaderView>
#include <QMenu>
using namespace std;
///@improvement write the visibility-status of the columns in toppview.ini and read at start
namespace OpenMS
{
TreeView::TreeView(QWidget* parent) :
QTreeWidget(parent)
{
this->setObjectName("tree_widget");
this->header()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this->header(), &QHeaderView::customContextMenuRequested, this, &TreeView::headerContextMenu_);
}
void TreeView::headerContextMenu_(const QPoint& pos)
{
// allows to hide/show columns
QMenu context_menu(this->header());
const auto& header = this->headerItem();
for (int i = 0; i < header->columnCount(); ++i)
{
auto action = context_menu.addAction(header->text(i), [i, this]() {
this->setColumnHidden(i, !this->isColumnHidden(i));
});
action->setCheckable(true);
action->setChecked(!this->isColumnHidden(i));
}
// show and execute menu
context_menu.exec(this->mapToGlobal(pos));
}
void TreeView::setHeaders(const QStringList& headers)
{
setColumnCount(headers.size());
setHeaderLabels(headers);
}
void TreeView::hideColumns(const QStringList& header_names)
{
auto hset = toQSet(header_names);
// add actions which show/hide columns
const auto& header = this->headerItem();
for (int i = 0; i < header->columnCount(); ++i)
{
if (hset.contains(header->text(i)))
{
setColumnHidden(i, true);
hset.remove(header->text(i));
}
}
if (!hset.empty())
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "header_names contains a column name which is unknown: " + String(hset.values().join(", ")));
}
}
QStringList TreeView::getHeaderNames(const WidgetHeader which) const
{
QStringList header_labels;
for (int i = 0; i != columnCount(); ++i)
{
// do not export hidden columns
if (which == WidgetHeader::VISIBLE_ONLY && isColumnHidden(i))
{
continue;
}
header_labels << getHeaderName(i);
}
return header_labels;
}
/// get the displayed name of the header in column with index @p header_column
/// @throws Exception::ElementNotFound if header at index @p header_column is not valid
QString TreeView::getHeaderName(const int header_column) const
{
const auto& header = this->headerItem();
if (header->columnCount() <= header_column)
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Header index " + String(header_column) + " is too large. There are only " + String(header->columnCount()) + " columns!");
}
return header->text(header_column);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ListEditor.cpp | .cpp | 11,397 | 380 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: David Wojnar $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ListEditor.h>
#include <OpenMS/DATASTRUCTURES/String.h>
// for DIALOG
#include <QtWidgets/QPushButton>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QFileDialog>
#include <utility>
#include <vector>
using namespace std;
namespace OpenMS
{
namespace Internal
{
//////////////////////////////////////////////////////////////
//DELEGATE
//////////////////////////////////////////////////////////////
ListEditorDelegate::ListEditorDelegate(QObject * parent) :
QItemDelegate(parent)
{
}
QWidget * ListEditorDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem &, const QModelIndex & index) const
{
if (type_ == ListEditor::INPUT_FILE)
{
QLineEdit * editor = new QLineEdit(parent);
//editor->setReadOnly(true);
QString str = index.data(Qt::DisplayRole).toString();
editor->setFocusPolicy(Qt::StrongFocus);
file_name_ = QFileDialog::getOpenFileName(editor, tr("Input File List"), str);
return editor;
}
else if (type_ == ListEditor::OUTPUT_FILE)
{
QLineEdit * editor = new QLineEdit(parent);
//editor->setReadOnly(true);
QString str = index.data(Qt::DisplayRole).toString();
file_name_ = QFileDialog::getSaveFileName(editor, tr("Output File List"), str);
return editor;
}
else if (type_ == ListEditor::STRING && !restrictions_.empty())
{
QComboBox * editor = new QComboBox(parent);
QStringList list;
list.append("");
list += restrictions_.toQString().split(",");
editor->addItems(list);
return editor;
}
else
{
QLineEdit * editor = new QLineEdit(parent);
editor->setFocusPolicy(Qt::StrongFocus);
return editor;
}
}
void ListEditorDelegate::setEditorData(QWidget * editor, const QModelIndex & index) const
{
if (index.isValid())
{
QString str = index.data(Qt::DisplayRole).toString();
if (type_ == ListEditor::INPUT_FILE || type_ == ListEditor::OUTPUT_FILE)
{
if (!file_name_.isNull())
{
static_cast<QLineEdit *>(editor)->setText(file_name_);
}
}
else if (qobject_cast<QComboBox *>(editor))
{
int index = static_cast<QComboBox *>(editor)->findText(str);
if (index == -1)
{
index = 0;
}
static_cast<QComboBox *>(editor)->setCurrentIndex(index);
}
else if (qobject_cast<QLineEdit *>(editor))
{
static_cast<QLineEdit *>(editor)->setText(str);
}
}
}
void ListEditorDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const
{
QVariant present_value = index.data(Qt::DisplayRole);
QVariant new_value;
if (index.column() == 0)
{
if (qobject_cast<QComboBox *>(editor)) //Drop-down list for enums
{
new_value = QVariant(static_cast<QComboBox *>(editor)->currentText());
}
else if (type_ == ListEditor::INPUT_FILE || type_ == ListEditor::OUTPUT_FILE)
{
new_value = QVariant(static_cast<QLineEdit *>(editor)->text()); //file_name_;
file_name_ = "\0";
}
else
{
if (type_ == ListEditor::FLOAT && static_cast<QLineEdit *>(editor)->text() == "")
{
new_value = QVariant("0.0");
}
else if (type_ == ListEditor::INT && static_cast<QLineEdit *>(editor)->text() == "")
{
new_value = QVariant("0");
}
else
{
new_value = QVariant(static_cast<QLineEdit *>(editor)->text());
}
}
//check if it matches the restrictions or is empty
if (new_value.toString() != "")
{
bool restrictions_met = true;
switch (type_)
{
//check if valid integer
case ListEditor::INT:
{
bool ok;
new_value.toString().toLong(&ok);
if (!ok)
{
QMessageBox::warning(nullptr, "Invalid value", QString("Cannot convert '%1' to integer number!").arg(new_value.toString()));
new_value = present_value;
if (new_value == "")
new_value = 0;
}
//restrictions
vector<String> parts;
if (restrictions_.split(' ', parts))
{
if (!parts[0].empty() && new_value.toInt() < parts[0].toInt())
{
restrictions_met = false;
}
if (!parts[1].empty() && new_value.toInt() > parts[1].toInt())
{
restrictions_met = false;
}
}
}
break;
case ListEditor::FLOAT: //check if valid float
{
bool ok;
new_value.toString().toDouble(&ok);
if (!ok)
{
QMessageBox::warning(nullptr, "Invalid value", QString("Cannot convert '%1' to floating point number!").arg(new_value.toString()));
new_value = present_value;
if (new_value == "")
{
new_value = 0;
}
}
//restrictions
vector<String> parts;
if (restrictions_.split(' ', parts))
{
if (!parts[0].empty() && new_value.toDouble() < parts[0].toDouble())
{
restrictions_met = false;
}
if (!parts[1].empty() && new_value.toDouble() > parts[1].toDouble())
{
restrictions_met = false;
}
}
}
break;
default:
break;
}
if (!restrictions_met)
{
QMessageBox::warning(nullptr, "Invalid value", QString("Value restrictions not met: %1").arg(index.sibling(index.row(), 3).data(Qt::DisplayRole).toString()));
new_value = present_value;
}
}
}
//check if modified
if (new_value != present_value)
{
model->setData(index, new_value);
model->setData(index, QBrush(Qt::yellow), Qt::BackgroundRole);
}
}
void ListEditorDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex &) const
{
editor->setGeometry(option.rect);
}
void ListEditorDelegate::setType(const ListEditor::Type type)
{
type_ = type;
}
void ListEditorDelegate::setRestrictions(const String & restrictions)
{
restrictions_ = restrictions;
}
void ListEditorDelegate::setTypeName(QString name)
{
typeName_ = std::move(name);
}
void ListEditorDelegate::setFileName(QString name)
{
file_name_ = std::move(name);
}
//////////////////////////////////////////////////////////////
//LISTTABLE
//////////////////////////////////////////////////////////////
ListTable::ListTable(QWidget * parent) :
QListWidget(parent)
{
}
StringList ListTable::getList()
{
String stringit;
list_.clear();
for (Int i = 0; i < count(); ++i)
{
stringit = item(i)->text();
if (!stringit.empty())
{
stringit.trim();
}
list_.push_back(stringit);
}
return list_;
}
void ListTable::setList(const StringList & list, ListEditor::Type type)
{
type_ = type;
for (UInt i = 0; i < list.size(); ++i)
{
QListWidgetItem * item = new QListWidgetItem(list[i].toQString());
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);
insertItem(i, item);
}
list_ = list;
adjustSize();
}
void ListTable::createNewRow()
{
QListWidgetItem * item = nullptr;
switch (type_)
{
case ListEditor::INT:
item = new QListWidgetItem("0");
break;
case ListEditor::FLOAT:
item = new QListWidgetItem("0.0");
break;
default:
item = new QListWidgetItem("");
}
item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);
addItem(item);
item->setSelected(true);
setCurrentRow(row(item));
itemActivated(item);
edit(currentIndex());
}
void ListTable::removeCurrentRow()
{
takeItem(currentRow());
}
} //namespace Internal
////////////////////////////////////////////////////////////
//ListEditor
////////////////////////////////////////////////////////////
ListEditor::ListEditor(QWidget * parent, const QString& title) :
QDialog(parent)
{
listTable_ = new Internal::ListTable(this);
listTable_->setRowHidden(-1, true);
listDelegate_ = new Internal::ListEditorDelegate(listTable_);
listTable_->setItemDelegate(listDelegate_);
removeRowButton_ = new QPushButton(tr("&delete"));
newRowButton_ = new QPushButton(tr("&new"));
newRowButton_->setDefault(true);
OkButton_ = new QPushButton(tr("&ok"));
CancelButton_ = new QPushButton(tr("&cancel"));
connect(newRowButton_, SIGNAL(clicked()), listTable_, SLOT(createNewRow()));
connect(removeRowButton_, SIGNAL(clicked()), listTable_, SLOT(removeCurrentRow()));
QDialogButtonBox * rightLayout = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Vertical);
rightLayout->addButton(newRowButton_, QDialogButtonBox::ActionRole);
rightLayout->addButton(removeRowButton_, QDialogButtonBox::ActionRole);
connect(rightLayout, SIGNAL(accepted()), this, SLOT(accept()));
connect(rightLayout, SIGNAL(rejected()), this, SLOT(reject()));
QHBoxLayout * mainLayout = new QHBoxLayout;
mainLayout->addWidget(listTable_);
mainLayout->addWidget(rightLayout);
setLayout(mainLayout);
QString tit = "List Editor" + title;
setWindowTitle(tit);
setMinimumSize(800, 500);
}
StringList ListEditor::getList() const
{
return listTable_->getList();
}
void ListEditor::setList(const StringList & list, ListEditor::Type type)
{
type_ = type;
listTable_->setList(list, type_);
listDelegate_->setType(type_);
}
void ListEditor::setListRestrictions(const String & restrictions)
{
listDelegate_->setRestrictions(restrictions);
}
void ListEditor::setTypeName(QString name)
{
listDelegate_->setTypeName(std::move(name));
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/GUIProgressLoggerImpl.cpp | .cpp | 2,259 | 81 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche, Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/GUIProgressLoggerImpl.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QApplication>
#include <QProgressDialog>
#include <iostream>
namespace OpenMS
{
GUIProgressLoggerImpl::GUIProgressLoggerImpl() :
dlg_(nullptr),
begin_(0),
end_(0),
current_(0)
{
}
void GUIProgressLoggerImpl::startProgress(const SignedSize begin, const SignedSize end, const String& label, const int /* current_recursion_depth */) const
{
begin_ = begin;
current_ = begin_;
end_ = end;
delete dlg_; // delete old dialog, if present
dlg_ = new QProgressDialog(label.c_str(), QString(), int(begin), int(end));
dlg_->setWindowTitle(label.c_str());
dlg_->setWindowModality(Qt::WindowModal);
dlg_->show();
QApplication::processEvents(); // show it...
}
void GUIProgressLoggerImpl::setProgress(const SignedSize value, const int /* current_recursion_depth */) const
{
if (value < begin_ || value > end_)
{
std::cout << "ProgressLogger: Invalid progress value '" << value << "'. Should be between '" << begin_ << "' and '" << end_ << "'!" << std::endl;
}
else
{
if (dlg_)
{
dlg_->setValue((int)value);
QApplication::processEvents(); // show it...
}
else
{
std::cout << "ProgressLogger warning: 'setProgress' called before 'startProgress'!" << std::endl;
}
}
}
SignedSize GUIProgressLoggerImpl::nextProgress() const
{
return ++current_;
}
void GUIProgressLoggerImpl::endProgress(const int /* current_recursion_depth */, UInt64 /* bytes_processed */) const
{
if (dlg_)
{
dlg_->setValue((int)end_);
}
else
{
std::cout << "ProgressLogger warning: 'endProgress' called before 'startProgress'!" << std::endl;
}
}
GUIProgressLoggerImpl::~GUIProgressLoggerImpl()
{
delete dlg_;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/SpectraIDViewTab.cpp | .cpp | 45,653 | 1,080 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include "OpenMS/VISUAL/LayerDataPeak.h"
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>
#include <OpenMS/COMPARISON/SpectrumAlignment.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/METADATA/MetaInfoInterfaceUtils.h>
#include <OpenMS/SYSTEM/NetworkGetRequest.h>
#include <OpenMS/VISUAL/LayerData1DPeak.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/SequenceVisualizer.h>
#include <OpenMS/VISUAL/SpectraIDViewTab.h>
#include <OpenMS/VISUAL/TableView.h>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QRegularExpression>
#include <QString>
#include <QStringList>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <vector>
#include <string>
//#define DEBUG_SPECTRA_ID_VIEW 1
using namespace std;
///@improvement write the visibility-status of the columns in toppview.ini and read at start
// Use a namespace to encapsulate names, yet use c-style 'enum' for fast conversion to int.
// So we can write: 'Clmn::MS_LEVEL', but get implicit conversion to int
namespace Clmn
{
enum HeaderNames
{ // indices into QTableWidget's columns (which start at index 0)
MS_LEVEL, SPEC_INDEX, RT, PRECURSOR_MZ, DISSOCIATION, SCANTYPE, ZOOM, SCORE, RANK,
CHARGE, SEQUENCE, ACCESSIONS, START, END, ID_NR, PEPHIT_NR, CURATED, PREC_PPM, PREC_INT, PEAK_ANNOTATIONS, /* last entry --> */ SIZE_OF_HEADERNAMES
};
// keep in SYNC with enum HeaderNames
const QStringList HEADER_NAMES = QStringList()
<< "MS" << "index" << "RT"
<< "precursor m/z" << "dissociation" << "scan type" << "zoom" << "score"
<< "rank" << "charge" << "sequence" << "accessions" << "start" << "end" << "#ID" << "#PH"
<< "Curated" << "precursor error (|ppm|)" << "precursor intensity" << "peak annotations";
}
// Use a namespace to encapsulate names, yet use c-style 'enum' for fast conversion to int.
// So we can write: 'Clmn::MS_LEVEL', but get implicit conversion to int
namespace ProteinClmn
{
enum HeaderNames
{ // indices into QTableWidget's columns (which start at index 0)
ACCESSION,
FULL_PROTEIN_SEQUENCE,
SEQUENCE,
DESCRIPTION,
SCORE,
COVERAGE,
NR_PSM,
/* last entry --> */ SIZE_OF_HEADERNAMES
};
// keep in SYNC with enum HeaderNames
const QStringList HEADER_NAMES = QStringList()
<< "accession" << "full sequence" << "sequence" << "description" << "score" << "coverage" << "#PSMs";
}
namespace OpenMS
{
SpectraIDViewTab::SpectraIDViewTab(const Param&, QWidget* parent) :
QWidget(parent),
DefaultParamHandler("SpectraIDViewTab")
{
setObjectName("Identifications");
// make sure they are in sync
assert(Clmn::HEADER_NAMES.size() == Clmn::HeaderNames::SIZE_OF_HEADERNAMES);
// id view parameters (warning: must be matched in TOPPViewPrefDialog)
defaults_.insert("tsg:", TheoreticalSpectrumGenerator().getParameters());
defaults_.insert("align:", SpectrumAlignment().getParameters());
QVBoxLayout* all = new QVBoxLayout(this);
tables_splitter_ = new QSplitter(Qt::Horizontal);
table_widget_ = new TableView(tables_splitter_);
// exported protein accessions and PSM rank even if hidden
table_widget_->setMandatoryExportColumns(QStringList() << "accessions" << "rank");
table_widget_->setWhatsThis("Spectrum selection bar<BR><BR>Here all spectra of the current experiment are shown. Left-click on a spectrum to open it.");
tables_splitter_->addWidget(table_widget_);
protein_table_widget_ = new TableView(tables_splitter_);
protein_table_widget_->setWhatsThis("Protein selection bar<BR><BR>Here all proteins of the current experiment are shown. TODO what can you do with it");
tables_splitter_->addWidget(protein_table_widget_);
all->addWidget(tables_splitter_);
////////////////////////////////////
// additional checkboxes and buttons
QHBoxLayout* buttons_hbox_layout = new QHBoxLayout();
hide_no_identification_ = new QCheckBox("Only hits", this);
hide_no_identification_->setChecked(true);
create_rows_for_commmon_metavalue_ = new QCheckBox("Show advanced\nannotations", this);
QPushButton* save_IDs = new QPushButton("Save IDs", this);
connect(save_IDs, &QPushButton::clicked, this, &SpectraIDViewTab::saveIDs_);
QPushButton* export_table = new QPushButton("Export table", this);
QPushButton* switch_orientation_ = new QPushButton("Switch orientation", this);
connect(switch_orientation_, &QPushButton::clicked, this, &SpectraIDViewTab::switchOrientation_);
buttons_hbox_layout->addWidget(hide_no_identification_);
buttons_hbox_layout->addWidget(create_rows_for_commmon_metavalue_);
buttons_hbox_layout->addWidget(save_IDs);
buttons_hbox_layout->addWidget(export_table);
buttons_hbox_layout->addWidget(switch_orientation_);
all->addLayout(buttons_hbox_layout);
//TODO add search boxes like in spectrum list view
//TODO add score filter box or Apply Tool to identifications
connect(table_widget_, &QTableWidget::currentCellChanged, this, &SpectraIDViewTab::currentCellChanged_);
connect(table_widget_, &QTableWidget::itemChanged, this, &SpectraIDViewTab::updatedSingleCell_);
connect(table_widget_->selectionModel(), &QItemSelectionModel::selectionChanged, this, &SpectraIDViewTab::currentSpectraSelectionChanged_);
connect(protein_table_widget_, &QTableWidget::cellClicked, this, &SpectraIDViewTab::proteinCellClicked_);
connect(protein_table_widget_, &QTableWidget::itemChanged, this, &SpectraIDViewTab::updatedSingleProteinCell_);
connect(hide_no_identification_, &QCheckBox::toggled, this, &SpectraIDViewTab::updateEntries_);
connect(create_rows_for_commmon_metavalue_, &QCheckBox::toggled, this, &SpectraIDViewTab::updateEntries_);
connect(export_table, &QPushButton::clicked, table_widget_, &TableView::exportEntries);
}
void SpectraIDViewTab::clear()
{
table_widget_->clear();
protein_table_widget_->clear();
layer_ = nullptr;
}
// Create the protein accession to peptide identification map using C++ STL unordered_map
void SpectraIDViewTab::createProteinToPeptideIDMap_()
{
//clear the map each time entries are updated with updateEntries()
protein_to_peptide_id_map.clear();
if (is_first_time_loading_ && layer_)
{
auto& annotated_peak_data = *layer_->getPeakData();
if (annotated_peak_data.getPeptideIdentifications().empty())
{
return;
}
for (const auto& [spec, pepid] : annotated_peak_data)
{
const vector<PeptideHit>& pep_hits = pepid.getHits();
//add id_accession as the key of the map and push the peptideID to the vector value-
for (const auto & pep_hit : pep_hits)
{
const vector<PeptideEvidence>& evidences = pep_hit.getPeptideEvidences();
for (const auto & evidence : evidences)
{
const String& id_accession = evidence.getProteinAccession();
protein_to_peptide_id_map[id_accession].push_back(&pepid);
}
}
}
// set is_first_time_loading to false so that the map gets created only the first time!
is_first_time_loading_ = false;
}
}
// extract required part of accession and open browser
QString SpectraIDViewTab::extractNumFromAccession_(const QString& full_accession)
{
// anchored (^...$) regex for matching accession
QRegularExpression reg_pre_accession("^(tr|sp)$", QRegularExpression::PatternOption::CaseInsensitiveOption);
QRegularExpression reg_uniprot_accession("^[OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2}$");
// The full accession is in the form "tr|A9GID7|A9GID7_SORC5" or "P02769|ALBU_BOVIN",
// so split it with | and get the individual parts
QStringList acsn = full_accession.split("|");
for (const QString& substr : acsn)
{
//eg, substr2 = tr, substr2 = p02769 etc
// if substr = tr/sp then skip
if (reg_pre_accession.match(substr.simplified()).hasMatch())
{
continue;
}
else
{
if (reg_uniprot_accession.match(substr.simplified()).hasMatch())
{
return substr.simplified();
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid accession found!",
String(full_accession));
}
}
}
return {};
}
void SpectraIDViewTab::openUniProtSiteWithAccession_(const QString& accession)
{
QString accession_num;
try
{
accession_num = extractNumFromAccession_(accession);
}
catch (Exception::InvalidValue&)
{
// TODO: print in status(?) that accession format is not supported
}
if (!accession_num.isEmpty())
{
QString base_url = "https://www.uniprot.org/uniprot/";
QString url = base_url + accession_num;
GUIHelpers::openURL(url);
}
}
void SpectraIDViewTab::proteinCellClicked_(int row, int column)
{
//TODO maybe highlight/filter all PepHits that may provide evidence for this protein (or at least that are top scorer)
if (row < 0 || column < 0)
return;
if (row >= protein_table_widget_->rowCount() || column >= protein_table_widget_->columnCount())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "invalid cell clicked.", String(row) + " " + column);
}
// Open browser with accession when clicked on the accession column on a row
if (column == ProteinClmn::ACCESSION)
{
// This stores the complete accession, eg, "tr|A9GID7|A9GID7_SORC5"
QString accession = protein_table_widget_->item(row, ProteinClmn::ACCESSION)->data(Qt::DisplayRole).toString();
// As with the current logic, we have only one accession per row, we can directly use that accession
// while opening the window instead of showing another widget that lists all accessions
openUniProtSiteWithAccession_(accession);
}
//
// Check if Qt WebEngineWidgets is installed on user's machine and if so,
// open a new window to visualize protein sequence
#ifdef QT_WEBENGINEWIDGETS_LIB
if (column == ProteinClmn::SEQUENCE)
{
// store the current sequence clicked from the FULL_PROTEIN_SEQUENCE column. This column(hidden by default)
// stores the full protein sequence
QString protein_sequence = protein_table_widget_->item(row, ProteinClmn::FULL_PROTEIN_SEQUENCE)->data(Qt::DisplayRole).toString();
// store the accession as string, eg: tr|P02769|ALBU_BOVIN
QString current_accession = protein_table_widget_->item(row, ProteinClmn::ACCESSION)->data(Qt::DisplayRole).toString();
// extract the part of accession , eg: P02769
QString accession_num;
try
{
accession_num = extractNumFromAccession_(current_accession);
}
catch (Exception::InvalidValue&)
{
// TODO: print in status(?) that accession format is not supported
}
auto item_pepid = table_widget_->item(row, Clmn::ID_NR);
if (item_pepid)
{
//array to store object of start-end positions, sequence and mod data of peptides;
QJsonArray peptides_data;
//use data from the protein_to_peptide_id_map map and store the start/end position to the QJsonArray
for (auto pep_id_ptr : protein_to_peptide_id_map[current_accession])
{
const vector<PeptideHit>& pep_hits = pep_id_ptr->getHits();
//store start and end positions
//TODO maybe we could store the index of the hit that belongs to that specific protein in the map as well
// or we generally should only look at the first hit
for (const auto & pep_hit : pep_hits)
{
const vector<PeptideEvidence>& evidences = pep_hit.getPeptideEvidences();
const AASequence& aaseq = pep_hit.getSequence();
const auto qstrseq = aaseq.toString().toQString();
for (const auto & evidence : evidences)
{
const String& id_accession = evidence.getProteinAccession();
QJsonObject pep_data_obj;
int pep_start = evidence.getStart();
int pep_end = evidence.getEnd();
if (id_accession.toQString() == current_accession)
{
// contains key-value of modName and vector of indices
QJsonObject mod_data;
for (int i = 0; i < (int)aaseq.size(); ++i)
{
if (aaseq[i].isModified())
{
const String& mod_name = aaseq[i].getModificationName();
if (!mod_data.contains(mod_name.toQString()))
{
mod_data[mod_name.toQString()] = QJsonArray{i + pep_start}; // add pep_start to get the correct location in the whole sequence
}
else
{
QJsonArray values = mod_data.value(mod_name.toQString()).toArray();
// add pep_start to get the correct location in the whole sequence
values.push_back(i + pep_start);
mod_data[mod_name.toQString()] = values;
}
}
}
pep_data_obj["start"] = pep_start;
pep_data_obj["end"] = pep_end;
pep_data_obj["seq"] = qstrseq;
pep_data_obj["mod_data"] = mod_data;
//Push objects to array that will be passed to html
peptides_data.push_back(pep_data_obj);
}
}
}
}
auto* widget = new SequenceVisualizer(this); // no parent since we want a new window
widget->setWindowFlags(Qt::Window);
widget->resize(1500,500); // make a bit bigger
widget->setProteinPeptideDataToJsonObj(accession_num, protein_sequence, peptides_data);
widget->show();
}
}
#endif
}
void SpectraIDViewTab::currentSpectraSelectionChanged_()
{
if (table_widget_->selectionModel()->selectedRows().empty())
{
// deselect whatever is currently shown
//layer_->getCurrentSpectrumIndex();
// Deselecting spectrum does not do what you think it does. It still paints stuff. Without annotations..
// so just leave it for now.
//
// PARTLY SOLVED: The problem was, that if you defocus the TOPPView window, somehow
// selectionChange is called, with EMPTY selection. Maybe this is a feature and we have to store the
// selected spectrum indices as well. I want to support multi-selection in the future to see shared peptides
// Actually this might be solved by the removal of the unnecessary updates in activateSubWindow.
// I think updateEntries resets selections as well.. not sure how we could avoid that. We really have to avoid
// calling this crazy function when only small updates are needed.
//emit spectrumDeselected(last_spectrum_index);
// TODO also currently, the current active spectrum can be restored after deselection by clicking on
// the Scans tab and then switching back to ID tab. (Scans will get the current scan in the 1D View, which
// is still there. I guess I have to deselect in the 1D view, too, after all.
updateProteinEntries_(-1);
}
//TODO if you deselected the current spectrum, you currently cannot click on/navigate to the same spectrum
// because currentCellChanged_ will not trigger. We would need to do it here.
}
void SpectraIDViewTab::currentCellChanged_(int row, int column, int /*old_row*/, int /*old_column*/)
{
// TODO you actually only have to do repainting if the row changes..
// sometimes Qt calls this function when table empty during refreshing
if (row < 0 || column < 0)
{
return;
}
if (row >= table_widget_->rowCount()
|| column >= table_widget_->columnCount())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "invalid cell clicked.", String(row) + " " + column);
}
// deselect whatever is currently shown (if we are in 1D view)
auto* layer_1d = dynamic_cast<LayerData1DPeak*>(layer_);
if (layer_1d)
{
emit spectrumDeselected(int(layer_1d->getCurrentIndex()));
}
int current_spectrum_index = table_widget_->item(row, Clmn::SPEC_INDEX)->data(Qt::DisplayRole).toInt();
const auto& annotated_exp = *layer_->getPeakData();
const auto& exp = annotated_exp.getMSExperiment();
const auto& spec2 = exp[current_spectrum_index];
//
// Signal for a new spectrum to be shown
//
// show precursor spectrum (usually MS1)
if (column == Clmn::PRECURSOR_MZ)
{
const auto prec_it = exp.getPrecursorSpectrum(exp.getSpectra().begin() + current_spectrum_index);
if (prec_it != exp.getSpectra().end() && !spec2.getPrecursors().empty())
{
double precursor_mz = spec2.getPrecursors()[0].getMZ();
// determine start and stop of isolation window
double isolation_window_lower_mz = precursor_mz - spec2.getPrecursors()[0].getIsolationWindowLowerOffset();
double isolation_window_upper_mz = precursor_mz + spec2.getPrecursors()[0].getIsolationWindowUpperOffset();
emit spectrumSelected(std::distance(exp.getSpectra().begin(), prec_it), -1, -1); // no identification or hit selected (-1)
// zoom into precursor area
emit requestVisibleArea1D(isolation_window_lower_mz - 50.0, isolation_window_upper_mz + 50.0);
}
}
else
{// if spectrum with no PepIDs is selected, there is nothing to show...
auto item_pepid = table_widget_->item(row, Clmn::ID_NR);
if (item_pepid == nullptr// null for MS1 spectra
|| (!(item_pepid->data(Qt::DisplayRole).isValid())))
{
return;
}
int current_identification_index = item_pepid->data(Qt::DisplayRole).toInt();
int current_peptide_hit_index = table_widget_->item(row, Clmn::PEPHIT_NR)->data(Qt::DisplayRole).toInt();
emit spectrumSelected(current_spectrum_index, current_identification_index, current_peptide_hit_index);
}
//
// show extra peak-fragment window
//
if (column == Clmn::PEAK_ANNOTATIONS
// column might not be present. Check the header name to make sure
&& table_widget_->horizontalHeaderItem(Clmn::PEAK_ANNOTATIONS)->text() == Clmn::HEADER_NAMES[Clmn::PEAK_ANNOTATIONS])
{
auto item_pepid = table_widget_->item(row, Clmn::ID_NR);
if (item_pepid)// might be null for MS1 spectra
{
// int current_identification_index = item_pepid->data(Qt::DisplayRole).toInt();
int current_peptide_hit_index = table_widget_->item(row, Clmn::PEPHIT_NR)->data(Qt::DisplayRole).toInt();
const PeptideIdentification& peptide_id = annotated_exp.getPeptideIdentifications()[current_spectrum_index];
const vector<PeptideHit>& phits = peptide_id.getHits();
const PeptideHit& hit = phits[current_peptide_hit_index];
// initialize window, when the table is requested for the first time
// afterwards the size will stay at the manually resized window size
if (fragment_window_ == nullptr)
{
fragment_window_ = new QTableWidget();
fragment_window_->resize(320, 500);
fragment_window_->verticalHeader()->setHidden(true);// hide vertical column
QStringList header_labels;
header_labels << "m/z"
<< "name"
<< "intensity"
<< "charge";
fragment_window_->setColumnCount(header_labels.size());
fragment_window_->setHorizontalHeaderLabels(header_labels);
QTableWidgetItem* proto_item = new QTableWidgetItem();
proto_item->setTextAlignment(Qt::AlignCenter);
fragment_window_->setItemPrototype(proto_item);
fragment_window_->setSortingEnabled(true);
fragment_window_->setWindowTitle(QApplication::translate("tr_fragment_annotation", "Peak Annotations"));
}
// reset table, if a new ID is chosen
fragment_window_->setRowCount(0);
for (const PeptideHit::PeakAnnotation& pa : hit.getPeakAnnotations())
{
fragment_window_->insertRow(fragment_window_->rowCount());
QTableWidgetItem* item = fragment_window_->itemPrototype()->clone();
item->setData(Qt::DisplayRole, pa.mz);
fragment_window_->setItem(fragment_window_->rowCount() - 1, 0, item);
item = fragment_window_->itemPrototype()->clone();
item->setData(Qt::DisplayRole, pa.annotation.toQString());
fragment_window_->setItem(fragment_window_->rowCount() - 1, 1, item);
item = fragment_window_->itemPrototype()->clone();
item->setData(Qt::DisplayRole, pa.intensity);
fragment_window_->setItem(fragment_window_->rowCount() - 1, 2, item);
item = fragment_window_->itemPrototype()->clone();
item->setData(Qt::DisplayRole, pa.charge);
fragment_window_->setItem(fragment_window_->rowCount() - 1, 3, item);
}
fragment_window_->resizeColumnsToContents();
fragment_window_->resizeRowsToContents();
fragment_window_->show();
fragment_window_->setFocus(Qt::ActiveWindowFocusReason);
fragment_window_->activateWindow();
}
} // PeakAnnotation cell clicked
// Update the protein table with data of the id row that was clicked
updateProteinEntries_(row);
}
bool SpectraIDViewTab::hasData(const LayerDataBase* layer)
{
// this is a very easy check.
// We do not check for PeptideIdentifications attached to Spectra, because the user could just
// want the list of unidentified MS2 spectra (obtained by unchecking the 'just hits' button).
auto* ptr_peak = dynamic_cast<const LayerDataPeak*>(layer);
bool no_data = (ptr_peak == nullptr
|| (ptr_peak && ptr_peak->getPeakData()->getMSExperiment().empty()));
return !no_data;
}
void SpectraIDViewTab::updateEntries(LayerDataBase* cl)
{
// do not try to be smart and check if layer_ == cl; to return early
// since the layer content might have changed, e.g. pepIDs were added
auto* ptr_peak = dynamic_cast<LayerDataPeak*>(cl);
layer_ = ptr_peak; // might be nullptr
// setting "is_first_time_loading_ = true;" here currently negates the logic of creating the map only the first time
// the data loads, but in future, after fixing the issue of calling updateEntries() multiple times, we can use it to only
// create the map when the table data loads completely new data from idXML file. Currently the map gets created each time
// the updateEntries() is called.
is_first_time_loading_ = true;
createProteinToPeptideIDMap_();
updateEntries_(); // we need this extra function since it's an internal slot
}
LayerDataBase* SpectraIDViewTab::getLayer()
{
return layer_;
}
namespace Detail
{
template<>
struct MetaKeyGetter<std::reference_wrapper<const PeptideHit>>
{
static void getKeys(const std::reference_wrapper<const PeptideHit>& object, std::vector<String>& keys)
{
object.get().getKeys(keys);
};
};
}// namespace Detail
void SpectraIDViewTab::updateProteinEntries_(int selected_spec_row_idx)
{
//TODO Currently when switching to 2D view of the same dataset and then switching back to the fragment spectrum,
// the spectrum table (almost; annotations gone) correctly restores the row, while the proteins do not get newly
// refreshed. Check why and fix. It is not too bad though.
// no valid peak layer attached
if (!hasData(layer_) || layer_->getPeakData()->getProteinIdentifications().empty())
{
//clear(); this was done in updateEntries_() already.
return;
}
if (ignore_update)
{
return;
}
if (!isVisible())
{
return;
}
set<String> accs;
if(selected_spec_row_idx >= 0)
//TODO another option would be a "Filter proteins" checkbox that filters for proteins for this Hit
// only when checked, otherwise only highlights
{
int row = selected_spec_row_idx;
//int spectrum_index = table_widget_->item(row, Clmn::SPEC_INDEX)->data(Qt::DisplayRole).toInt();
int num_id = table_widget_->item(row, Clmn::ID_NR)->data(Qt::DisplayRole).toInt();
int num_ph = table_widget_->item(row, Clmn::PEPHIT_NR)->data(Qt::DisplayRole).toInt();
const PeptideIdentification& pep_id = layer_->getPeakData()->getPeptideIdentifications()[num_id];
const vector<PeptideHit>& hits = pep_id.getHits();
if (!hits.empty()) accs = hits[num_ph].extractProteinAccessionsSet();
}
// create header labels (setting header labels must occur after fill)
QStringList headers = ProteinClmn::HEADER_NAMES;
protein_table_widget_->clear();
protein_table_widget_->setRowCount(0);
protein_table_widget_->setColumnCount(headers.size());
protein_table_widget_->setSortingEnabled(false);
protein_table_widget_->setUpdatesEnabled(false);
protein_table_widget_->blockSignals(true);
// generate flat list
int selected_row(-1);
// index i is needed, so iterate the old way...
for (Size i = 0; i < layer_->getPeakData()->getProteinIdentifications()[0].getHits().size(); ++i)
{
const auto& protein = layer_->getPeakData()->getProteinIdentifications()[0].getHits()[i];
if (accs.empty() || accs.find(protein.getAccession()) != accs.end())
{
// set row background color
QColor bg_color = accs.empty() ? Qt::white : Qt::lightGray;
int total_pepids = protein_to_peptide_id_map[protein.getAccession()].size();
// add new row at the end of the table
protein_table_widget_->insertRow(protein_table_widget_->rowCount());
protein_table_widget_->setAtBottomRow(protein.getAccession().toQString(), ProteinClmn::ACCESSION, bg_color, Qt::blue);
protein_table_widget_->setAtBottomRow(protein.getSequence().toQString(), ProteinClmn::FULL_PROTEIN_SEQUENCE, bg_color);
protein_table_widget_->setAtBottomRow("show", ProteinClmn::SEQUENCE, bg_color, Qt::blue);
protein_table_widget_->setAtBottomRow(protein.getDescription().toQString(), ProteinClmn::DESCRIPTION, bg_color);
protein_table_widget_->setAtBottomRow(protein.getScore(), ProteinClmn::SCORE, bg_color);
protein_table_widget_->setAtBottomRow(protein.getCoverage(), ProteinClmn::COVERAGE, bg_color);
protein_table_widget_->setAtBottomRow(total_pepids, ProteinClmn::NR_PSM, bg_color);
/*if ((int)i == restore_spec_index) //TODO actually extract the accessions for the selected spectrum and compare
{
selected_row = protein_table_widget_->rowCount() - 1; // get model index of selected spectrum
}*/
}
}
protein_table_widget_->setHeaders(headers);
protein_table_widget_->setColumnHidden(ProteinClmn::FULL_PROTEIN_SEQUENCE, true);
#ifndef QT_WEBENGINEWIDGETS_LIB
protein_table_widget_->setColumnHidden(ProteinClmn::SEQUENCE, true); // no web engine? hide sequence column used to do the JS query
#endif
protein_table_widget_->resizeColumnsToContents();
protein_table_widget_->setSortingEnabled(true);
protein_table_widget_->sortByColumn(ProteinClmn::SCORE, Qt::AscendingOrder); //TODO figure out higher_score_better
if (selected_row != -1) // select and scroll down to item
{
protein_table_widget_->selectRow(selected_row);
QTableWidgetItem* selected_item = protein_table_widget_->item(selected_row, 0);
selected_item->setSelected(true);
protein_table_widget_->setCurrentItem(selected_item);
protein_table_widget_->scrollToItem(selected_item);
}
protein_table_widget_->blockSignals(false);
protein_table_widget_->setUpdatesEnabled(true);
protein_table_widget_->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
protein_table_widget_->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
}
void SpectraIDViewTab::updateEntries_()
{
#ifdef DEBUG_SPECTRA_ID_VIEW
cout << "Updating entries in SpectraIDViewTab" << endl;
#endif
// no valid peak layer attached
if (!hasData(layer_))
{
clear();
return;
}
if (ignore_update)
{
return;
}
if (!isVisible())
{
return;
}
auto layer_peak = dynamic_cast<LayerData1DPeak*>(layer_);
if (!layer_peak) return;
int restore_spec_index = int(layer_peak->getCurrentIndex());
set<String> common_keys;
bool has_peak_annotations(false);
// determine meta values common to all hits
Detail::MetaKeyGetter<std::reference_wrapper<const PeptideHit>> getter;
if (create_rows_for_commmon_metavalue_->isChecked())
{
std::vector<std::reference_wrapper<const PeptideHit>> all_hits;
for (auto [spectrum, peptide_id] : *layer_->getPeakData())
{
UInt ms_level = spectrum.getMSLevel();
if (ms_level != 2) // skip non ms2 spectra and spectra with no identification
{
continue;
}
const vector<PeptideHit>& phits = peptide_id.getHits();
all_hits.insert(all_hits.end(), phits.begin(), phits.end());
if (!has_peak_annotations && !phits.empty() && !phits[0].getPeakAnnotations().empty())
{
has_peak_annotations = true;
}
}
common_keys = MetaInfoInterfaceUtils::findCommonMetaKeys<
std::vector<std::reference_wrapper<const PeptideHit>>,
set<String> >(all_hits.begin(), all_hits.end(), 100.0, getter);
}
// create header labels (setting header labels must occur after fill)
QStringList headers = Clmn::HEADER_NAMES;
if (!has_peak_annotations)
{ // remove peak annotations column
headers.pop_back();
}
// add common meta columns (not indexed anymore, but we don't need them to be)
for (const auto& ck : common_keys)
{
headers << ck.toQString();
}
table_widget_->blockSignals(true); // to be safe, that clear does not trigger anything.
table_widget_->clear();
table_widget_->setRowCount(0);
table_widget_->setColumnCount(headers.size());
table_widget_->setSortingEnabled(false);
table_widget_->setUpdatesEnabled(false);
table_widget_->blockSignals(true);
// generate flat list
int selected_row(-1);
// index i is needed, so iterate the old way...
for (Size i = 0; i < layer_->getPeakData()->getMSExperiment().size(); ++i)
{
auto [spectrum, peptide_id] = (*layer_->getPeakData())[i];
const UInt ms_level = spectrum.getMSLevel();
const vector<Precursor> & precursors = spectrum.getPrecursors();
const Size id_count = peptide_id.getHits().size();
// allow only MS2 OR MS1 with peptideIDs (from Mass Fingerprinting)
if (ms_level != 2)
{
continue;
}
// skip
if (hide_no_identification_->isChecked() && id_count == 0)
{
continue;
}
// set row background color
QColor bg_color = (id_count == 0 ? Qt::white : QColor::fromRgb(127,255,148));
// get peptide identifications of current spectrum
if (id_count == 0)
{
// add new row at the end of the table
table_widget_->insertRow(table_widget_->rowCount());
fillRow_(spectrum, i, bg_color);
}
else
{
// get peptide identifications of current spectrum
#ifdef DEBUG_SPECTRA_ID_VIEW
cout << "Peptide hits: " << peptide_id.getHits().size() << endl;
#endif
for (Size ph_idx = 0; ph_idx != peptide_id.getHits().size(); ++ph_idx)
{
#ifdef DEBUG_SPECTRA_ID_VIEW
cout << "Peptide hit index: " << ph_idx << endl;
cout << "Peptide hit: " << peptide_id.getHits()[ph_idx].getSequence().toString() << endl;
#endif
const PeptideHit& ph = peptide_id.getHits()[ph_idx];
// add new row at the end of the table
table_widget_->insertRow(table_widget_->rowCount());
fillRow_(spectrum, i, bg_color);
table_widget_->setAtBottomRow(ph.getScore(), Clmn::SCORE, bg_color);
table_widget_->setAtBottomRow((int)ph.getRank(), Clmn::RANK, bg_color);
table_widget_->setAtBottomRow(ph.getCharge(), Clmn::CHARGE, bg_color);
// sequence
String seq = ph.getSequence().toString();
if (seq.empty())
{
seq = ph.getMetaValue("label");
}
table_widget_->setAtBottomRow(seq.toQString(), Clmn::SEQUENCE, bg_color);
// accession, start and end in protein (note that one peptide might match twice into same protein)
const vector<PeptideEvidence>& pevids = ph.getPeptideEvidences();
vector<String> protein_accessions;
vector<String> protein_starts;
vector<String> protein_ends;
for (const PeptideEvidence& ev : pevids)
{
protein_accessions.push_back(ev.getProteinAccession());
protein_starts.push_back(ev.getStart() + 1);
protein_ends.push_back(ev.getEnd() + 1);
}
String accessions = ListUtils::concatenate(vector<String>(protein_accessions.begin(), protein_accessions.end()), ", ");
String starts = ListUtils::concatenate(vector<String>(protein_starts.begin(), protein_starts.end()), ", ");
String ends = ListUtils::concatenate(vector<String>(protein_ends.begin(), protein_ends.end()), ", ");
table_widget_->setAtBottomRow(accessions.toQString(), Clmn::ACCESSIONS, bg_color);
table_widget_->setAtBottomRow(starts.toQString(), Clmn::START, bg_color);
table_widget_->setAtBottomRow(ends.toQString(), Clmn::END, bg_color);
table_widget_->setAtBottomRow((int) i, Clmn::ID_NR, bg_color); // spectrum index
table_widget_->setAtBottomRow((int)(ph_idx), Clmn::PEPHIT_NR, bg_color);
bool selected(false);
if (ph.metaValueExists("selected"))
{
selected = ph.getMetaValue("selected").toString() == "true";
}
table_widget_->setAtBottomRow(selected, Clmn::CURATED, bg_color);
// additional precursor infos, e.g. ppm error
if (!precursors.empty())
{
const Precursor& first_precursor = precursors.front();
double ppm_error(0);
// Protein:RNA cross-link, Protein-Protein cross-link, or other data with a precomputed precursor error
if (ph.metaValueExists(Constants::UserParam::PRECURSOR_ERROR_PPM_USERPARAM))
{
ppm_error = fabs((double)ph.getMetaValue(Constants::UserParam::PRECURSOR_ERROR_PPM_USERPARAM));
}
else if (ph.metaValueExists("OMS:precursor_mz_error_ppm")) // for legacy reasons added in OpenMS 2.5
{
ppm_error = fabs((double)ph.getMetaValue("OMS:precursor_mz_error_ppm"));
}
else if (!ph.getSequence().empty()) // works for normal linear fragments with the correct modifications included in the AASequence
{
double exp_precursor = first_precursor.getMZ();
int charge = first_precursor.getCharge();
double theo_precursor= ph.getSequence().getMZ(charge);
ppm_error = fabs((exp_precursor - theo_precursor) / exp_precursor / 1e-6);
}
table_widget_->setAtBottomRow(ppm_error, Clmn::PREC_PPM, bg_color);
}
// add additional meta value columns
if (create_rows_for_commmon_metavalue_->isChecked())
{
Int current_col = Clmn::PEAK_ANNOTATIONS;
// add peak annotation column (part of meta-value assessment above)
if (has_peak_annotations)
{
// set hidden data for export to TSV
QString annotation;
for (const PeptideHit::PeakAnnotation& pa : ph.getPeakAnnotations())
{
annotation += String(pa.mz).toQString() + "|" +
String(pa.intensity).toQString() + "|" +
String(pa.charge).toQString() + "|" +
pa.annotation.toQString() + ";";
}
QTableWidgetItem* item = table_widget_->setAtBottomRow("show", current_col, bg_color, Qt::blue);
item->setData(Qt::UserRole, annotation);
++current_col;
}
for (const auto& ck : common_keys)
{
const DataValue& dv = ph.getMetaValue(ck);
if (dv.valueType() == DataValue::DOUBLE_VALUE)
{
table_widget_->setAtBottomRow(double(dv), current_col, bg_color);
}
else
{
table_widget_->setAtBottomRow(dv.toQString(), current_col, bg_color);
}
++current_col;
}
}
}
}
if ((int)restore_spec_index)
{
// get model index of selected spectrum,
// as table_widget_->rowCount() returns rows starting from 1, selected row is 1 less than the returned row
selected_row = table_widget_->rowCount() - 1;
}
}
table_widget_->setHeaders(headers);
String s = headers.join(';');
table_widget_->hideColumns(QStringList() << "accessions"
<< "dissociation"
<< "scan type"
<< "zoom"
<< "rank"
<< "#ID"
<< "#PH");
if (has_peak_annotations) table_widget_->setHeaderExportName(Clmn::PEAK_ANNOTATIONS, "PeakAnnotations(mz|intensity|charge|annotation");
table_widget_->setSortingEnabled(true);
table_widget_->sortByColumn(Clmn::SPEC_INDEX, Qt::AscendingOrder);
if (selected_row != -1) // select and scroll down to item
{
table_widget_->selectRow(selected_row);
QTableWidgetItem* selected_item = table_widget_->item(selected_row, 0);
selected_item->setSelected(true);
table_widget_->setCurrentItem(selected_item);
table_widget_->scrollToItem(selected_item);
currentCellChanged_(selected_row, 0, 0, 0); // simulate cell change to trigger repaint and reannotation of spectrum 1D view
}
table_widget_->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
table_widget_->blockSignals(false);
table_widget_->setUpdatesEnabled(true);
// call this updateProteinEntries_(-1) function after the table_widget data is filled,
// otherwise table_widget_->item(row, clm) returns nullptr;
updateProteinEntries_(selected_row);
}
void SpectraIDViewTab::switchOrientation_()
{
if (tables_splitter_->orientation() == Qt::Vertical)
{
tables_splitter_->setOrientation(Qt::Horizontal);
}
else
{
tables_splitter_->setOrientation(Qt::Vertical);
}
}
void SpectraIDViewTab::saveIDs_()
{
// no valid peak layer attached
if (layer_ == nullptr || layer_->getPeakData()->getMSExperiment().empty() || layer_->type != LayerDataBase::DT_PEAK)
{
return;
}
// synchronize PeptideHits with the annotations in the spectrum
dynamic_cast<LayerData1DPeak*>(layer_)->synchronizePeakAnnotations();
vector<ProteinIdentification> prot_id = layer_->getPeakData()->getProteinIdentifications();
PeptideIdentificationList all_pep_ids;
// collect PeptideIdentifications from each spectrum, while making sure each spectrum is only considered once
// otherwise duplicates will be stored, if more than one PeptideHit is contained in a PeptideIdentification
set<int> added_spectra;
for (int r = 0; r < table_widget_->rowCount(); ++r)
{
// get spectrum index of current table line
int spectrum_index = table_widget_->item(r, Clmn::SPEC_INDEX)->data(Qt::DisplayRole).toInt();
// skip this row, if this spectrum was already processed
if (added_spectra.find(spectrum_index) != added_spectra.end())
{
continue;
}
added_spectra.insert(spectrum_index);
const PeptideIdentification& pep_id = (*layer_->getPeakData())[spectrum_index].second;
all_pep_ids.push_back(pep_id);
}
QString filename = GUIHelpers::getSaveFilename(this, "Save file", "", FileTypeList({FileTypes::IDXML, FileTypes::MZIDENTML}), true, FileTypes::IDXML);
if (filename.isEmpty())
{
return;
}
FileHandler().storeIdentifications(filename, prot_id, all_pep_ids, {FileTypes::IDXML, FileTypes::MZIDENTML});
}
void SpectraIDViewTab::updatedSingleProteinCell_(QTableWidgetItem* /*item*/)
{
}
// Upon changes in the table data (only possible by checking or unchecking a checkbox right now),
// update the corresponding PeptideIdentification / PeptideHits by adding a metavalue: 'selected'
void SpectraIDViewTab::updatedSingleCell_(QTableWidgetItem* item)
{
// extract position of the correct Spectrum, PeptideIdentification and PeptideHit from the table
int row = item->row();
String selected = item->checkState() == Qt::Checked ? "true" : "false";
// int spectrum_index = table_widget_->item(row, Clmn::SPEC_INDEX)->data(Qt::DisplayRole).toInt();
int num_id = table_widget_->item(row, Clmn::ID_NR)->data(Qt::DisplayRole).toInt();
int num_ph = table_widget_->item(row, Clmn::PEPHIT_NR)->data(Qt::DisplayRole).toInt();
// maintain sortability of our checkbox column
TableView::updateCheckBoxItem(item);
PeptideIdentification& pep_id = (*layer_->getPeakDataMuteable())[num_id].second;
// update "selected" value in the correct PeptideHits
vector<PeptideHit>& hits = pep_id.getHits();
// XL-MS specific case, both PeptideHits belong to the same cross-link
if (hits[0].metaValueExists("xl_chain"))
{
hits[0].setMetaValue("selected", selected);
if (hits.size() >= 2)
{
hits[1].setMetaValue("selected", selected);
}
}
else // general case, update only the selected PeptideHit
{
hits[num_ph].setMetaValue("selected", selected);
}
}
void SpectraIDViewTab::fillRow_(const MSSpectrum& spectrum, const int spec_index, const QColor& background_color)
{
// fill spectrum information in columns
const vector<Precursor>& precursors = spectrum.getPrecursors();
#ifdef DEBUG_SPECTRA_ID_VIEW
cout << "Filling row in SpectraIDViewTab" << endl;
cout << spectrum.getMSLevel() << endl
<< "RT: " << spectrum.getRT() << endl
<< "Scan mode: " << spectrum.getInstrumentSettings().getScanMode() << endl
<< "Zoom scan: " << spectrum.getInstrumentSettings().getZoomScan() << endl
<< "Spectrum index: " << spec_index << endl
<< "Precursor MZ: " << (precursors.empty() ? 0 : precursors.front().getMZ()) << endl
<< "Precursor charge: " << (precursors.empty() ? 0 : precursors.front().getCharge()) << endl
<< "Precursor intensity: " << (precursors.empty() ? 0 : precursors.front().getIntensity()) << endl
<< endl;
#endif
table_widget_->setAtBottomRow(QString::number(spectrum.getMSLevel()), Clmn::MS_LEVEL, background_color);
table_widget_->setAtBottomRow(spec_index, Clmn::SPEC_INDEX, background_color);
table_widget_->setAtBottomRow(spectrum.getRT(), Clmn::RT, background_color);
// scan mode
table_widget_->setAtBottomRow(QString::fromStdString(spectrum.getInstrumentSettings().NamesOfScanMode[static_cast<size_t>(spectrum.getInstrumentSettings().getScanMode())]), Clmn::SCANTYPE, background_color);
// zoom scan
table_widget_->setAtBottomRow(spectrum.getInstrumentSettings().getZoomScan() ? "yes" : "no", Clmn::ZOOM, background_color);
// fill precursor information in columns
if (!precursors.empty())
{
const Precursor& first_precursor = precursors.front();
// draw precursor information in blue
table_widget_->setAtBottomRow(first_precursor.getMZ(), Clmn::PRECURSOR_MZ, background_color, Qt::blue);
// set activation method
table_widget_->setAtBottomRow(ListUtils::concatenate(first_precursor.getActivationMethodsAsString(), ",").toQString(), Clmn::DISSOCIATION, background_color);
// set precursor intensity
table_widget_->setAtBottomRow(first_precursor.getIntensity(), Clmn::PREC_INT, background_color);
}
}
void SpectraIDViewTab::SelfResizingTableView_::resizeEvent(QResizeEvent * /*event*/)
{
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/PainterBase.cpp | .cpp | 5,670 | 167 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/PainterBase.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <cassert>
#include <QPainter>
#include <QPen>
#include <QTransform>
using namespace std;
namespace OpenMS
{
ShapeIcon PainterBase::toShapeIcon(const String& icon)
{
if (icon == "diamond") return ShapeIcon::DIAMOND;
if (icon == "square") return ShapeIcon::SQUARE;
if (icon == "circle") return ShapeIcon::CIRCLE;
if (icon == "triangle") return ShapeIcon::TRIANGLE;
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Shape must be one of 'diamond', 'square', 'circle', 'triangle'!", icon);
}
void PainterBase::drawDashedLine(const QPoint& from, const QPoint& to, QPainter* painter, const QColor& color)
{
QPen pen;
QVector<qreal> dashes;
dashes << 5 << 5 << 1 << 5;
pen.setDashPattern(dashes);
pen.setColor(color);
painter->save();
painter->setPen(pen);
painter->drawLine(from, to);
painter->restore();
}
void PainterBase::drawCross(const QPoint& pos, QPainter* painter, const int size)
{
const int half_size = size / 2;
painter->drawLine(pos.x(), pos.y() - half_size, pos.x(), pos.y() + half_size);
painter->drawLine(pos.x() - half_size, pos.y(), pos.x() + half_size, pos.y());
}
void PainterBase::drawCaret(const QPoint& caret, QPainter* painter, const int size)
{
const int half_size = size / 2;
painter->drawLine(caret.x(), caret.y(), caret.x() + half_size, caret.y() + half_size);
painter->drawLine(caret.x(), caret.y(), caret.x() - half_size, caret.y() + half_size);
}
void PainterBase::drawDiamond(const QPoint& center, QPainter* painter, const int size)
{
const int half_size = size / 2;
const auto x = center.x();
const auto y = center.y();
painter->drawLine(x, y + half_size, x + half_size, y);
painter->drawLine(x + half_size, y, x, y - half_size);
painter->drawLine(x, y - half_size, x - half_size, y);
painter->drawLine(x - half_size, y, x, y + half_size);
}
void PainterBase::drawIcon(const QPoint& pos, const QRgb& color, const ShapeIcon icon, Size s, QPainter& p)
{
p.save();
p.setPen(color);
p.setBrush(QBrush(QColor(color), Qt::SolidPattern));
int s_half = (int)s / 2;
switch (icon)
{
break; case ShapeIcon::DIAMOND:
{
QPolygon pol;
pol.putPoints(0, 4, pos.x() + s_half, pos.y(), pos.x(), pos.y() + s_half, pos.x() - (int)s_half, pos.y(), pos.x(), pos.y() - (int)s_half);
p.drawConvexPolygon(pol);
}
break; case ShapeIcon::SQUARE:
{
QPolygon pol;
pol.putPoints(0, 4, pos.x() + s_half, pos.y() + s_half, pos.x() - s_half, pos.y() + s_half, pos.x() - s_half, pos.y() - s_half, pos.x() + s_half, pos.y() - s_half);
p.drawConvexPolygon(pol);
}
break; case ShapeIcon::CIRCLE:
{
p.drawEllipse(QRectF(pos.x() - s_half, pos.y() - s_half, s, s));
}
break; case ShapeIcon::TRIANGLE:
{
QPolygon pol;
pol.putPoints(0, 3, pos.x(), pos.y() + s_half, pos.x() + s_half, pos.y() - (int)s_half, pos.x() - (int)s_half, pos.y() - (int)s_half);
p.drawConvexPolygon(pol);
}
break; default:
assert(false); // should never be reached
}
p.restore();
}
QPainterPath PainterBase::getOpenArrow(int arrow_width)
{ // arrow definition
QPainterPath arrow;
arrow.moveTo(QPointF(0, 0));
arrow.lineTo(QPointF(-arrow_width, 4));
arrow.moveTo(QPointF(0, 0));
arrow.lineTo(QPointF(-arrow_width, -4));
return arrow;
}
QPainterPath PainterBase::getClosedArrow(int arrow_width)
{ // arrow definition
QPainterPath arrow;
arrow.moveTo(QPointF(0, 0));
arrow.lineTo(QPointF(-arrow_width, 4));
arrow.lineTo(QPointF(-arrow_width, -4));
arrow.closeSubpath();
return arrow;
}
QRectF PainterBase::drawLineWithArrows(QPainter* painter, const QPen& pen, const QPoint& start, const QPoint& end, const QPainterPath& arrow_start, const QPainterPath& arrow_end)
{
painter->setPen(pen);
auto line = QLineF(start, end);
// angle of line
qreal angle = -line.angle() + 180; // negate since angle() reports counter-clockwise; +180 since painter.rotate() is more intuitive then
QRectF bounding_rect = QRectF(line.p1(), line.p2()).normalized();
// draw the actual line
painter->drawLine(line);
//painter->save();
// draw arrow heads
if (!arrow_start.isEmpty())
{
//painter->translate(start);
//painter->rotate(angle);
QTransform rotationMatrix;
rotationMatrix.translate(start.x(), start.y());
rotationMatrix.rotate(angle);
QPainterPath path = rotationMatrix.map(arrow_start);
painter->drawPath(path);
bounding_rect = bounding_rect.united(path.boundingRect());
//painter->restore();
}
if (!arrow_end.isEmpty())
{
QTransform rotationMatrix;
rotationMatrix.translate(end.x(), end.y());
rotationMatrix.rotate(angle + 180);
QPainterPath path = rotationMatrix.map(arrow_end);
painter->drawPath(path);
bounding_rect = bounding_rect.united(path.boundingRect());
}
return bounding_rect;
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TVControllerBase.cpp | .cpp | 820 | 32 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/VISUAL/TVControllerBase.h>
using namespace OpenMS;
using namespace std;
namespace OpenMS
{
TVControllerBase::TVControllerBase(TOPPViewBase* parent):
tv_(parent)
{
}
void TVControllerBase::activateBehavior()
{
// no special handling of activation is default
}
void TVControllerBase::deactivateBehavior()
{
// no special handling of deactivation is default
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DataSelectionTabs.cpp | .cpp | 10,069 | 265 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
// OpenMS_GUI config
#include <OpenMS/VISUAL/DataSelectionTabs.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/VISUAL/DIATreeTab.h>
#include <OpenMS/VISUAL/LayerDataBase.h>
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/SpectraTreeTab.h>
#include <OpenMS/VISUAL/SpectraIDViewTab.h>
#include <OpenMS/VISUAL/Plot1DCanvas.h>
#include <OpenMS/VISUAL/Plot2DCanvas.h>
#include <OpenMS/VISUAL/TVDIATreeTabController.h>
#include <OpenMS/VISUAL/TVSpectraViewController.h>
#include <OpenMS/VISUAL/TVIdentificationViewController.h>
namespace OpenMS
{
/// enable and show the @p which tab
/// double-click on disabled identification view
/// --> enables it and creates an empty identification structure
/// Default constructor
DataSelectionTabs::DataSelectionTabs(QWidget* parent, TOPPViewBase* tv)
: QTabWidget(parent),
spectra_view_widget_(new SpectraTreeTab(this)),
id_view_widget_(new SpectraIDViewTab(Param(), this)),
dia_widget_(new DIATreeTab(this)),
tab_ptrs_{ spectra_view_widget_, id_view_widget_, dia_widget_ }, // make sure to add new tabs here!
spectraview_controller_(new TVSpectraViewController(tv)),
idview_controller_(new TVIdentificationViewController(tv, id_view_widget_)),
diatab_controller_(new TVDIATreeTabController(tv)),
tv_(tv)
{
// Hook-up controller and views for spectra
connect(spectra_view_widget_, &SpectraTreeTab::showSpectrumMetaData, tv, &TOPPViewBase::showSpectrumMetaData);
connect(spectra_view_widget_, &SpectraTreeTab::showSpectrumAsNew1D, spectraview_controller_, &TVSpectraViewController::showSpectrumAsNew1D);
connect(spectra_view_widget_, &SpectraTreeTab::showChromatogramsAsNew1D, spectraview_controller_, &TVSpectraViewController::showChromatogramsAsNew1D);
connect(spectra_view_widget_, &SpectraTreeTab::spectrumSelected, spectraview_controller_, CONNECTCAST(TVSpectraViewController, activate1DSpectrum, (int)));
connect(spectra_view_widget_, &SpectraTreeTab::chromsSelected, spectraview_controller_, CONNECTCAST(TVSpectraViewController, activate1DSpectrum, (const std::vector<int>&)));
connect(spectra_view_widget_, &SpectraTreeTab::spectrumDoubleClicked, spectraview_controller_, &TVSpectraViewController::showSpectrumAsNew1D);
connect(spectra_view_widget_, &SpectraTreeTab::chromsDoubleClicked, spectraview_controller_, &TVSpectraViewController::showChromatogramsAsNew1D);
// Hook-up controller and views for identification
connect(id_view_widget_, &SpectraIDViewTab::spectrumDeselected, idview_controller_, &TVIdentificationViewController::deactivate1DSpectrum);
connect(id_view_widget_, &SpectraIDViewTab::spectrumSelected, idview_controller_, CONNECTCAST(TVIdentificationViewController, activate1DSpectrum, (int, int, int)));
connect(id_view_widget_, &SpectraIDViewTab::requestVisibleArea1D, idview_controller_, &TVIdentificationViewController::setVisibleArea1D);
// Hook-up controller and views for DIA
connect(dia_widget_, &DIATreeTab::entityClicked, diatab_controller_, &TVDIATreeTabController::showChromatograms);
connect(dia_widget_, &DIATreeTab::entityDoubleClicked, diatab_controller_, &TVDIATreeTabController::showChromatogramsAsNew1D);
int index;
index = addTab(spectra_view_widget_, spectra_view_widget_->objectName());
if (index != SPECTRA_IDX)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Tab index is expected to be 0");
}
index = addTab(id_view_widget_, id_view_widget_->objectName());
if (index != IDENT_IDX)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Tab index is expected to be 1");
}
index = addTab(dia_widget_, dia_widget_->objectName());
if (index != DIAOSW_IDX)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Tab index is expected to be 2");
}
// make sure initialization was correct
assert(tabBar()->count() == (int)tab_ptrs_.size());
// switch between different view tabs
connect(this, &QTabWidget::currentChanged, this, &DataSelectionTabs::currentTabChanged);
connect(this, &QTabWidget::tabBarDoubleClicked, this, &DataSelectionTabs::tabBarDoubleClicked);
}
DataSelectionTabs::~DataSelectionTabs()
{
delete spectraview_controller_;
delete idview_controller_;
delete diatab_controller_;
}
LayerDataBase* getCurrentLayerData(TOPPViewBase* tv)
{
PlotCanvas* cc = tv->getActiveCanvas();
if (cc == nullptr)
{
return nullptr;
}
if (cc->getCurrentLayerIndex() == Size(-1))
{
return nullptr;
}
return &(cc->getCurrentLayer());
}
// called externally
// and internally by signals
void DataSelectionTabs::callUpdateEntries()
{
// prevent infinite loop when calling 'setTabEnabled' -> currentTabChanged() -> update()
this->blockSignals(true);
RAIICleanup cleanup([&]()
{
this->blockSignals(false);
});
auto layer_ptr = getCurrentLayerData(tv_); // can be nullptr
// becomes true if the currently visible tab has no data
bool auto_select = false;
// the order is important here. On auto-select, we will pick the highest one which has data to show!
Size highest_data_index = 0; // will pick spectra_view_widget_ if layer_ptr==nullptr
for (Size i = 0; i < tab_ptrs_.size(); ++i)
{
auto widget = dynamic_cast<QWidget*>(tab_ptrs_[i]);
bool has_data = tab_ptrs_[i]->hasData(layer_ptr);
setTabEnabled(i, has_data); // enable/disable depending on data
if (has_data)
{
highest_data_index = i;
}
if (!has_data && // the currently visible tab has no data --> select a new tab
widget->isVisible())
{
auto_select = true;
}
}
// pick the highest tab which has data
if (auto_select)
{
setCurrentIndex(highest_data_index);
}
Size current_index = currentIndex();
// update the currently visible tab (might be disabled if no data is shown)
tab_ptrs_[current_index]->updateEntries(layer_ptr);
}
void DataSelectionTabs::currentTabChanged(int tab_index)
{
// set new behavior
switch (tab_index)
{
case SPECTRA_IDX:
idview_controller_->deactivateBehavior(); // finalize old behavior
diatab_controller_->deactivateBehavior();
spectraview_controller_->activateBehavior(); // initialize new behavior
break;
case IDENT_IDX:
spectraview_controller_->deactivateBehavior();
diatab_controller_->deactivateBehavior();
if (tv_->getActive2DWidget()) // currently, 2D window is open
{
idview_controller_->showSpectrumAsNew1D(0);
}
idview_controller_->activateBehavior();
break;
case DIAOSW_IDX:
idview_controller_->deactivateBehavior(); // finalize old behavior
spectraview_controller_->deactivateBehavior();
diatab_controller_->activateBehavior(); // initialize new behavior
break;
default:
std::cerr << "Error: tab_index " << tab_index << " is invalid\n";
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
callUpdateEntries(); //TODO actually this is overkill. Why would you load the entire table again
// when you only switched tabs? The TabView should get notified when the layer data changes, so it only
// updates when necessary...
// The only thing that maybe needs to happen when switching tabs is to sync the index across the tables in the different tabs.
// which is the only reason why we need to actually use callUpdateEntries here.
// At least we reduced it to only updateEntries during tab switch, not EVERY update() [e.g. when resizing, refocussing...]
}
void DataSelectionTabs::showSpectrumAsNew1D(int index)
{
Plot1DWidget* widget_1d = tv_->getActive1DWidget();
Plot2DWidget* widget_2d = tv_->getActive2DWidget();
if (widget_1d || widget_2d)
{
if (spectra_view_widget_->isVisible())
{
spectraview_controller_->showSpectrumAsNew1D(index);
}
if (id_view_widget_->isVisible())
{
idview_controller_->showSpectrumAsNew1D(index);
}
}
}
void DataSelectionTabs::showChromatogramsAsNew1D(const std::vector<int>& indices)
{
Plot1DWidget* widget_1d = tv_->getActive1DWidget();
Plot2DWidget* widget_2d = tv_->getActive2DWidget();
if (widget_1d)
{
if (spectra_view_widget_->isVisible())
{
spectraview_controller_->showChromatogramsAsNew1D(indices);
}
}
else if (widget_2d)
{
if (spectra_view_widget_->isVisible())
{
spectraview_controller_->showChromatogramsAsNew1D(indices);
}
}
}
void DataSelectionTabs::tabBarDoubleClicked(int tab_index)
{
if (!tv_->getActivePlotWidget())
{
return;
}
switch (tab_index)
{
case IDENT_IDX:
if (!isTabEnabled(IDENT_IDX))
{
setTabEnabled(IDENT_IDX, true); // enable identification view
spectraview_controller_->deactivateBehavior();
if (tv_->getActive2DWidget()) // currently 2D window is open
{
idview_controller_->showSpectrumAsNew1D(0);
}
idview_controller_->activateBehavior();
// TODO: check this triggers update!
setCurrentIndex(IDENT_IDX); // switch to identification view --> triggers currentTabChanged() slot
}
case SPECTRA_IDX:
default:
break;
}
// update here?
}
SpectraIDViewTab* DataSelectionTabs::getSpectraIDViewTab()
{
return id_view_widget_;
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/LayerDataConsensus.cpp | .cpp | 2,992 | 92 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/LayerDataConsensus.h>
#include <OpenMS/ANALYSIS/ID/IDMapper.h>
#include <OpenMS/KERNEL/DimMapper.h>
#include <OpenMS/VISUAL/Painter2DBase.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
using namespace std;
namespace OpenMS
{
/// Default constructor
LayerDataConsensus::LayerDataConsensus(ConsensusMapSharedPtrType& map) : LayerDataBase(LayerDataBase::DT_CONSENSUS)
{
consensus_map_ = map;
}
std::unique_ptr<Painter2DBase> LayerDataConsensus::getPainter2D() const
{
return make_unique<Painter2DConsensus>(this);
}
std::unique_ptr<LayerStoreData> LayerDataConsensus::storeVisibleData(const RangeAllType& visible_range, const DataFilters& layer_filters) const
{
auto ret = make_unique<LayerStoreDataConsensusMapVisible>();
ret->storeVisibleCM(*consensus_map_.get(), visible_range, layer_filters);
return ret;
}
std::unique_ptr<LayerStoreData> LayerDataConsensus::storeFullData() const
{
auto ret = make_unique<LayerStoreDataConsensusMapAll>();
ret->storeFullCM(*consensus_map_.get());
return ret;
}
PeakIndex LayerDataConsensus::findHighestDataPoint(const RangeAllType& area) const
{
using IntType = MSExperiment::ConstAreaIterator::PeakType::IntensityType;
auto max_int = numeric_limits<IntType>::lowest();
PeakIndex max_pi;
for (ConsensusMapType::ConstIterator i = getConsensusMap()->begin(); i != getConsensusMap()->end(); ++i)
{
// consensus feature in visible area?
if (area.containsRT(i->getRT()) && area.containsMZ(i->getMZ()) && filters.passes(*i))
{
if (i->getIntensity() > max_int)
{
max_int = i->getIntensity();
max_pi = PeakIndex(i - getConsensusMap()->begin());
}
}
}
return max_pi;
}
PointXYType LayerDataConsensus::peakIndexToXY(const PeakIndex& peak, const DimMapper<2>& mapper) const
{
return mapper.map(peak.getFeature(*getConsensusMap()));
}
/*std::unique_ptr<Painter1DBase> LayerDataConsensus::getPainter1D() const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
} */
std::unique_ptr<LayerStatistics> LayerDataConsensus::getStats() const
{
return make_unique<LayerStatisticsConsensusMap>(*consensus_map_);
}
bool LayerDataConsensus::annotate(const PeptideIdentificationList& identifications, const vector<ProteinIdentification>& protein_identifications)
{
IDMapper mapper;
mapper.annotate(*getConsensusMap(), identifications, protein_identifications);
return true;
}
}// namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPViewMenu.cpp | .cpp | 10,344 | 218 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPViewMenu.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/RecentFilesMenu.h>
#include <QAction>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
using namespace std;
namespace OpenMS
{
FS_TV operator+(const TV_STATUS left, const TV_STATUS right)
{
FS_TV r(left);
r += right;
return r;
}
FS_LAYER OPENMS_GUI_DLLAPI operator+(const LayerDataBase::DataType left, const LayerDataBase::DataType right)
{
FS_LAYER r;
r += left;
r += right;
return r;
}
TOPPViewMenu::TOPPViewMenu(TOPPViewBase* const parent, EnhancedWorkspace* const ws, RecentFilesMenu* const recent_files)
: QObject()
//parent_(parent)
{
QAction* action; ///< for adding tool tips to actions
QMenu* m_file = new QMenu("&File", parent);
m_file->setToolTipsVisible(true);
parent->menuBar()->addMenu(m_file);
// we explicitly pass an empty Path here using a Lambda, since using the default `..., parent, &TOPPViewBase::openFilesByDialog, ...`)
// passes a "0" as argument (Qt bug?)
m_file->addAction("&Open file", parent, [parent]() { parent->openFilesByDialog(""); })->setShortcut(Qt::CTRL | Qt::Key_O);
m_file->addAction("Open &example file", parent, [parent]() { parent->openFilesByDialog(File::getOpenMSDataPath() + "/examples/"); })->setShortcut(Qt::CTRL | Qt::Key_E);
action = m_file->addAction("&Close tab", parent, &TOPPViewBase::closeTab);
action->setShortcut(Qt::CTRL | Qt::Key_W);
addAction_(action, TV_STATUS::HAS_CANVAS);
m_file->addSeparator();
// Meta data
action = m_file->addAction("&Show meta data (file)", parent, &TOPPViewBase::metadataFileDialog);
action->setToolTip("Load a file's meta information without actually loading the data.");
m_file->addSeparator();
// Recent files
m_file->addMenu(recent_files->getMenu()); // updates automatically via RecentFilesMenu class, since this is just a pointer
m_file->addSeparator();
// Specifically set the role of the Preferences item. Additionally we have to avoid adding other action items that are
// called preferences/config/options and have the default TextHeuristicRole because otherwise they will overwrite the macOS specific
// menu entry under Application -> Preferences...
// m_file->addAction("&Preferences", parent, &TOPPViewBase::preferencesDialog);
auto pref = new QAction("&Preferences", parent);
pref->setMenuRole(QAction::PreferencesRole);
pref->setEnabled(true);
m_file->addAction(pref);
connect(pref, &QAction::triggered, parent, &TOPPViewBase::preferencesDialog);
m_file->addAction("&Quit", qApp, SLOT(quit()));
// Tools menu
QMenu* m_tools = new QMenu("&Tools", parent);
m_tools->setToolTipsVisible(true);
parent->menuBar()->addMenu(m_tools);
action = m_tools->addAction("&Select data range", parent, &TOPPViewBase::showGoToDialog);
action->setShortcut(Qt::CTRL | Qt::Key_G);
addAction_(action, TV_STATUS::HAS_LAYER);
action = m_tools->addAction("&Edit meta data", parent, &TOPPViewBase::editMetadata);
action->setShortcut(Qt::CTRL | Qt::Key_M);
addAction_(action, TV_STATUS::HAS_LAYER);
addAction_(m_tools->addAction("&Statistics", parent, &TOPPViewBase::layerStatistics),
TV_STATUS::HAS_LAYER);
m_tools->addSeparator();
action = m_tools->addAction("Apply TOPP tool (whole layer)", parent, &TOPPViewBase::showTOPPDialog);
action->setShortcut(Qt::CTRL | Qt::Key_T);
action->setData(false);
addAction_(action, TV_STATUS::HAS_LAYER + TV_STATUS::TOPP_IDLE);
action = m_tools->addAction("Apply TOPP tool (visible layer data)", parent, &TOPPViewBase::showTOPPDialog);
action->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_T);
action->setData(true);
addAction_(action, TV_STATUS::HAS_LAYER + TV_STATUS::TOPP_IDLE);
action = m_tools->addAction("Rerun TOPP tool", parent, &TOPPViewBase::rerunTOPPTool);
action->setShortcut(Qt::Key_F4);
addAction_(action, TV_STATUS::HAS_LAYER + TV_STATUS::TOPP_IDLE);
m_tools->addSeparator();
action = m_tools->addAction("&Annotate with AccurateMassSearch results", parent, &TOPPViewBase::annotateWithAMS);
action->setShortcut(Qt::CTRL | Qt::Key_A);
action->setToolTip("Annotate Peak layer with a featureXML from the AccurateMassSearch tool");
addAction_(action, TV_STATUS::HAS_LAYER, FS_LAYER(LayerDataBase::DT_PEAK));
action = m_tools->addAction("&Annotate with peptide identifications", parent, &TOPPViewBase::annotateWithID);
action->setShortcut(Qt::CTRL | Qt::Key_I);
action->setToolTip("Annotate a Peak or Feature or Consensus layer with peptide identifications");
addAction_(action, TV_STATUS::HAS_LAYER, LayerDataBase::DT_PEAK + LayerDataBase::DT_FEATURE + LayerDataBase::DT_CONSENSUS);
action = m_tools->addAction("&Annotate with OpenSwath transitions", parent, &TOPPViewBase::annotateWithOSW);
action->setShortcut(Qt::CTRL | Qt::Key_P);
action->setToolTip("Annotate Chromatogram layer with OSW transition id data from OpenSwathWorkflow or pyProphet");
addAction_(action, TV_STATUS::HAS_LAYER, FS_LAYER(LayerDataBase::DT_CHROMATOGRAM));
action = addAction_(m_tools->addAction("Align spectra", parent, &TOPPViewBase::showSpectrumAlignmentDialog),
TV_STATUS::HAS_MIRROR_MODE);
action->setToolTip("Only available in 1D View for mirrored (flipped) spectra. To flip, use the Layer View and right click a layer.");
m_tools->addAction("Generate theoretical spectrum", parent, &TOPPViewBase::showSpectrumGenerationDialog);
// Layer menu
QMenu* m_layer = new QMenu("&Layer", parent);
m_layer->setToolTipsVisible(true);
parent->menuBar()->addMenu(m_layer);
action = m_layer->addAction("Save all data", parent, &TOPPViewBase::saveLayerAll);
action->setShortcut(Qt::CTRL | Qt::Key_S);
addAction_(action, TV_STATUS::HAS_LAYER);
action = m_layer->addAction("Save visible data", parent, &TOPPViewBase::saveLayerVisible);
action->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_S);
addAction_(action, TV_STATUS::HAS_LAYER);
m_layer->addSeparator();
action = m_layer->addAction("Show/hide grid lines", parent, &TOPPViewBase::toggleGridLines);
action->setShortcut(Qt::CTRL | Qt::Key_R);
addAction_(action, TV_STATUS::HAS_LAYER);
action = m_layer->addAction("Show/hide axis legends", parent, &TOPPViewBase::toggleAxisLegends);
action->setShortcut(Qt::CTRL | Qt::Key_L);
addAction_(action, TV_STATUS::HAS_CANVAS);
action = addAction_(m_layer->addAction("Show/hide automated m/z annotations", parent, &TOPPViewBase::toggleInterestingMZs),
TV_STATUS::IS_1D_VIEW);
action->setToolTip("Only available in 1D View");
m_layer->addSeparator();
// Do not call it preferences without disabling text heuristics role.
addAction_(m_layer->addAction("Layer preferences", parent, &TOPPViewBase::showPreferences),
TV_STATUS::HAS_LAYER);
// Windows menu
m_windows_ = new QMenu("&Windows", parent);
m_windows_->setToolTipsVisible(true);
parent->menuBar()->addMenu(m_windows_);
m_windows_->addAction("&Cascade", ws, &EnhancedWorkspace::cascadeSubWindows);
m_windows_->addAction("&Tile automatic", ws, &EnhancedWorkspace::tileSubWindows);
m_windows_->addAction(QIcon(":/tile_vertical.png"), "Tile &vertical", ws, &EnhancedWorkspace::tileVertical);
m_windows_->addAction(QIcon(":/tile_horizontal.png"), "Tile &horizontal", ws, &EnhancedWorkspace::tileHorizontal);
// link / unlink
action = m_windows_->addAction("Link/Unlink &Zoom", parent, &TOPPViewBase::linkZoom);
action->setToolTip("Zoom all open tab windows to the same coordinates concurrently (requires the same view dimension; e.g. all 2D views will show the same RT/mz windows). Most effective when used in tiled Windows view (see Windows -> tiling)");
m_windows_->addSeparator();
// Help menu
QMenu* m_help = new QMenu("&Help", parent);
m_help->setToolTipsVisible(true);
parent->menuBar()->addMenu(m_help);
m_help->addAction(QWhatsThis::createAction(m_help));
m_help->addSeparator();
m_help->addAction("OpenMS website", []() { GUIHelpers::openURL("http://www.OpenMS.de"); });
m_help->addAction("Tutorials and documentation", []() { GUIHelpers::openURL("html/index.html"); })->setShortcut(Qt::Key_F1);
m_help->addSeparator();
// Note: it is important to pass parent by value, since the lambda will be evaluated later,
// even after this function returned and parent reference would be out of scope.
m_help->addAction("&About", [parent]() {QApplicationTOPP::showAboutDialog(parent, "TOPPView"); });
}
void TOPPViewMenu::update(const FS_TV status, const LayerDataBase::DataType layer_type)
{
for (auto& ar : menu_items_)
{ // only disable if not supported by the view. This way, the user can still see the item (greyed out) and its ToolTip (for how to activate the item)
ar.enableAction(status, layer_type);
}
}
void TOPPViewMenu::addWindowToggle(QAction* const window_toggle)
{
m_windows_->addAction(window_toggle);
}
QAction* TOPPViewMenu::addAction_(QAction* action, const TV_STATUS req, const FS_LAYER type)
{
menu_items_.emplace_back(action, req, type);
return action;
}
QAction* TOPPViewMenu::addAction_(QAction* action, const FS_TV req, const FS_LAYER type)
{
menu_items_.emplace_back(action, req, type);
return action;
}
void TOPPViewMenu::ActionRequirement_::enableAction(const FS_TV status, const LayerDataBase::DataType layer_type)
{
bool status_ok = status.isSuperSetOf(needs_);
bool layer_ok = layer_set_.isSuperSetOf(layer_type) || layer_set_.empty();
this->action_->setEnabled(status_ok && layer_ok);
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/HistogramWidget.cpp | .cpp | 9,003 | 324 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// Qt
#include <QResizeEvent>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QtWidgets/QMenu>
// STL
#include <iostream>
// OpenMS
#include <OpenMS/VISUAL/HistogramWidget.h>
#include <OpenMS/VISUAL/AxisWidget.h>
using namespace std;
namespace OpenMS
{
using namespace Math;
HistogramWidget::HistogramWidget(const Histogram<> & distribution, QWidget * parent) :
QWidget(parent),
dist_(distribution),
show_splitters_(false),
moving_splitter_(0),
margin_(30),
buffer_(),
log_mode_(false)
{
left_splitter_ = dist_.minBound();
right_splitter_ = dist_.maxBound();
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
setMinimumSize(600, 450);
bottom_axis_ = new AxisWidget(AxisPainter::BOTTOM, "", this);
bottom_axis_->setMargin(margin_);
bottom_axis_->setTickLevel(2);
bottom_axis_->setAxisBounds(dist_.minBound(), dist_.maxBound());
//signals and slots
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(showContextMenu(const QPoint &)));
}
HistogramWidget::~HistogramWidget()
{
delete(bottom_axis_);
}
double HistogramWidget::getLeftSplitter() const
{
return left_splitter_;
}
double HistogramWidget::getRightSplitter() const
{
return right_splitter_;
}
void HistogramWidget::showSplitters(bool on)
{
show_splitters_ = on;
}
void HistogramWidget::setRightSplitter(double pos)
{
right_splitter_ = min(dist_.maxBound(), pos);
}
void HistogramWidget::setLeftSplitter(double pos)
{
left_splitter_ = max(dist_.minBound(), pos);
}
void HistogramWidget::setLegend(const String & legend)
{
bottom_axis_->setLegend(legend);
}
void HistogramWidget::mousePressEvent(QMouseEvent * e)
{
if (show_splitters_ && e->button() == Qt::LeftButton)
{
//left
Int p = margin_ + UInt(((left_splitter_ - dist_.minBound()) / (dist_.maxBound() - dist_.minBound())) * (width() - 2 * margin_));
//cout << "Mouse: " << e->x() << " p: " << p << " splitter: " << left_splitter_ << endl;
if (e->position().x() >= p && e->position().x() <= p + 5)
{
moving_splitter_ = 1;
}
//right
p = margin_ + UInt(((right_splitter_ - dist_.minBound()) / (dist_.maxBound() - dist_.minBound())) * (width() - 2 * margin_));
if (e->position().x() <= p && e->position().x() >= p - 5)
{
moving_splitter_ = 2;
}
}
else
{
e->ignore();
}
}
void HistogramWidget::mouseMoveEvent(QMouseEvent * e)
{
if (show_splitters_ && (e->buttons() & Qt::LeftButton))
{
//left
if (moving_splitter_ == 1)
{
left_splitter_ = double(Int(e->position().x()) - Int(margin_)) / (width() - 2 * margin_) * (dist_.maxBound() - dist_.minBound()) + dist_.minBound();
//upper bound
if (left_splitter_ > right_splitter_ - (dist_.maxBound() - dist_.minBound()) / 50.0)
{
left_splitter_ = right_splitter_ - (dist_.maxBound() - dist_.minBound()) / 50.0;
}
//lower bound
if (left_splitter_ < dist_.minBound())
{
left_splitter_ = dist_.minBound();
}
update();
}
//right
if (moving_splitter_ == 2)
{
right_splitter_ = double(Int(e->position().x()) - Int(margin_)) / (width() - 2 * margin_ + 2) * (dist_.maxBound() - dist_.minBound()) + dist_.minBound();
//upper bound
if (right_splitter_ < left_splitter_ + (dist_.maxBound() - dist_.minBound()) / 50.0)
{
right_splitter_ = left_splitter_ + (dist_.maxBound() - dist_.minBound()) / 50.0;
}
//lower bound
if (right_splitter_ > dist_.maxBound())
{
right_splitter_ = dist_.maxBound();
}
update();
}
}
else
{
e->ignore();
}
}
void HistogramWidget::mouseReleaseEvent(QMouseEvent * e)
{
if (show_splitters_)
{
moving_splitter_ = 0;
}
else
{
e->ignore();
}
}
void HistogramWidget::paintEvent(QPaintEvent * /*e*/)
{
//histogram from buffer
QPainter painter2(this);
painter2.drawPixmap(margin_, 0, buffer_);
//y-axis label
painter2.rotate(270);
painter2.setPen(Qt::black);
QString label = "count";
if (log_mode_)
{
label = "log ( count )";
}
painter2.drawText(0, 0, -height(), margin_, Qt::AlignHCenter | Qt::AlignVCenter, label);
painter2.end();
//draw splitters
if (show_splitters_)
{
QPainter painter(this);
painter.setPen(Qt::black);
QFont label_font;
label_font.setPointSize(8);
//cout << "Left splitter: " << left_splitter_<< " dist: " << dist_.minBound() << endl;
//cout << "Right splitter: " << right_splitter_<< " dist: " << dist_.maxBound() << endl;
//left
UInt p = UInt(((left_splitter_ - dist_.minBound()) / (dist_.maxBound() - dist_.minBound())) * (width() - 2 * margin_)) + margin_;
//cout << "Left splitter position: " << p << endl;
painter.drawLine(p, margin_ - 8, p, height() - bottom_axis_->height());
painter.drawLine(p, margin_ - 8, p + 5, margin_ - 8);
painter.drawLine(p + 5, margin_ - 8, p, margin_ - 3);
painter.setFont(label_font);
painter.drawText(p, margin_ - 8, "lower boundary");
painter.setFont(QFont());
//right
p = UInt(((right_splitter_ - dist_.minBound()) / (dist_.maxBound() - dist_.minBound())) * (width() - 2 * margin_)) + margin_;
painter.drawLine(p, margin_ - 8, p, height() - bottom_axis_->height());
painter.drawLine(p, margin_ - 8, p - 5, margin_ - 8);
painter.drawLine(p - 5, margin_ - 8, p, margin_ - 3);
painter.setFont(label_font);
painter.drawText(p, margin_ - 8, "upper boundary");
painter.setFont(QFont());
}
}
void HistogramWidget::resizeEvent(QResizeEvent * /*e*/)
{
buffer_ = QPixmap(width() - margin_, height() - bottom_axis_->height());
bottom_axis_->setGeometry(margin_, height() - bottom_axis_->height(), width() - margin_, bottom_axis_->height());
invalidate_();
}
void HistogramWidget::invalidate_()
{
//apply log trafo if needed
Math::Histogram<> dist(dist_);
if (log_mode_)
{
dist.applyLogTransformation(100.0);
}
QPainter painter(&buffer_);
buffer_.fill(palette().window().color());
UInt w = buffer_.width();
UInt h = buffer_.height();
UInt pen_width = std::min(margin_, UInt(0.5 * w / dist.size()));
//draw distribution
QPen pen;
pen.setWidth(pen_width);
pen.setColor(QColor(100, 125, 175));
painter.setPen(pen);
for (Size i = 0; i < dist.size(); ++i)
{
if (dist[i] != 0)
{
UInt bin_pos = UInt((double(i) / (dist.size() - 1)) * (w - margin_));
UInt bin_height = UInt(((double)dist[i] / dist.maxValue()) * (h - margin_));
painter.drawLine(bin_pos + 1, h, bin_pos + 1, h - bin_height);
}
}
//calculate total intensity
double total_sum = 0;
for (Size i = 0; i < dist.size(); ++i)
{
total_sum += dist[i];
}
// draw part of total intensity
painter.setPen(Qt::red);
QPoint last_point(1, h);
QPoint point;
double int_sum = 0;
for (Size i = 0; i < dist.size(); ++i)
{
int_sum += dist[i];
point.setX(UInt((double(i) / (dist.size() - 1)) * (w - margin_)));
point.setY(UInt((1 - (int_sum / total_sum)) * (h - margin_) + margin_));
painter.drawLine(last_point, point);
last_point = point;
}
// draw coord system (on top distribution)
painter.setPen(Qt::black);
painter.drawLine(0, h - 1, w - margin_ + Int(0.5 * pen_width), h - 1);
update();
}
void HistogramWidget::showContextMenu(const QPoint & pos)
{
//create menu
QMenu menu(this);
QAction * action = menu.addAction("Normal mode");
if (!log_mode_)
{
action->setEnabled(false);
}
action = menu.addAction("Log mode");
if (log_mode_)
{
action->setEnabled(false);
}
//execute
QAction * result = menu.exec(mapToGlobal(pos));
//change according to selected value
if (result != nullptr)
{
if (result->text() == "Normal mode")
{
setLogMode(false);
}
else if (result->text() == "Log mode")
{
setLogMode(true);
}
}
}
void HistogramWidget::setLogMode(bool log_mode)
{
log_mode_ = log_mode;
if (!buffer_.isNull())
{
invalidate_();
}
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Plot3DWidget.cpp | .cpp | 1,865 | 70 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <iostream>
//OpenMS
#include <OpenMS/VISUAL/Plot3DWidget.h>
#include <OpenMS/VISUAL/Plot3DOpenGLCanvas.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/DIALOGS/Plot2DGoToDialog.h>
using namespace std;
namespace OpenMS
{
using namespace Internal;
using namespace Math;
Plot3DWidget::Plot3DWidget(const Param & preferences, QWidget * parent) :
PlotWidget(preferences, parent)
{
setCanvas_(new Plot3DCanvas(preferences, this));
x_axis_->hide();
y_axis_->hide();
// delegate signals from canvas
connect(canvas(), SIGNAL(showCurrentPeaksAs2D()), this, SIGNAL(showCurrentPeaksAs2D()));
}
Plot3DWidget::~Plot3DWidget() = default;
void Plot3DWidget::recalculateAxes_()
{
}
void Plot3DWidget::showLegend(bool show)
{
canvas()->showLegend(show);
}
bool Plot3DWidget::isLegendShown() const
{
return static_cast<const Plot3DCanvas *>(canvas_)->isLegendShown();
}
void Plot3DWidget::showGoToDialog()
{
Plot2DGoToDialog goto_dialog(this, canvas_->getMapper().getDim(DIM::X).getDimNameShort(), canvas_->getMapper().getDim(DIM::Y).getDimNameShort());
auto va = canvas()->getVisibleArea().getAreaXY();
goto_dialog.setRange(va);
auto all_area_xy = canvas_->getMapper().mapRange(canvas_->getDataRange());
goto_dialog.setMinMaxOfRange(all_area_xy);
goto_dialog.enableFeatureNumber(false);
if (goto_dialog.exec())
{
canvas()->setVisibleArea(goto_dialog.getRange());
}
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/Plot3DCanvas.cpp | .cpp | 9,503 | 314 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/Plot3DCanvas.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/FileWatcher.h>
#include <OpenMS/VISUAL/ColorSelector.h>
#include <OpenMS/VISUAL/DIALOGS/Plot3DPrefDialog.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/MultiGradientSelector.h>
#include <OpenMS/VISUAL/Plot3DOpenGLCanvas.h>
#include <OpenMS/VISUAL/PlotWidget.h>
#include <QResizeEvent>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QSpinBox>
using namespace std;
namespace OpenMS
{
using namespace Internal;
Plot3DCanvas::Plot3DCanvas(const Param & preferences, QWidget * parent) :
PlotCanvas(preferences, parent)
{
// Parameter handling
defaults_.setValue("dot:shade_mode", 1, "Shade mode: single-color ('flat') or gradient peaks ('smooth').");
defaults_.setMinInt("dot:shade_mode", 0);
defaults_.setMaxInt("dot:shade_mode", 1);
defaults_.setValue("dot:gradient", "Linear|0,#ffea00;6,#ff0000;14,#aa00ff;23,#5500ff;100,#000000", "Peak color gradient.");
defaults_.setValue("dot:interpolation_steps", 1000, "Interpolation steps for peak color gradient precalculation.");
defaults_.setMinInt("dot:interpolation_steps", 1);
defaults_.setMaxInt("dot:interpolation_steps", 1000);
defaults_.setValue("dot:line_width", 2, "Line width for peaks.");
defaults_.setMinInt("dot:line_width", 1);
defaults_.setMaxInt("dot:line_width", 99);
defaults_.setValue("background_color", "#ffffff", "Background color");
setName("Plot3DCanvas");
defaultsToParam_();
setParameters(preferences);
linear_gradient_.fromString(param_.getValue("dot:gradient"));
openglcanvas_ = new Plot3DOpenGLCanvas(this, *this);
setFocusProxy(openglcanvas_);
connect(this, SIGNAL(actionModeChange()), openglcanvas_, SLOT(actionModeChange()));
legend_shown_ = true;
//connect preferences change to the right slot
connect(this, SIGNAL(preferencesChange()), this, SLOT(currentLayerParamtersChanged_()));
}
Plot3DCanvas::~Plot3DCanvas() = default;
void Plot3DCanvas::resizeEvent(QResizeEvent * e)
{
openglcanvas_->resize(e->size().width(), e->size().height());
}
void Plot3DCanvas::showLegend(bool show)
{
legend_shown_ = show;
update_(OPENMS_PRETTY_FUNCTION);
}
bool Plot3DCanvas::isLegendShown() const
{
return legend_shown_;
}
bool Plot3DCanvas::finishAdding_()
{
if (layers_.getCurrentLayer().type != LayerDataBase::DT_PEAK)
{
popIncompleteLayer_("This widget supports peak data only. Aborting!");
return false;
}
// Abort if no data points are contained
auto& layer = dynamic_cast<LayerDataPeak&>(getCurrentLayer());
const MSExperiment& peak_data = layer.getPeakData()->getMSExperiment();
if (peak_data.empty())
{
popIncompleteLayer_("Cannot add a dataset that contains no survey scans. Aborting!");
return false;
}
recalculateRanges_();
resetZoom(false);
//Warn if negative intensities are contained
if (getCurrentMinIntensity() < 0.0)
{
QMessageBox::warning(this, "Warning", "This dataset contains negative intensities. Use it at your own risk!");
}
emit layerActivated(this);
openglwidget()->recalculateDotGradient_(getCurrentLayer());
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
return true;
}
void Plot3DCanvas::activateLayer(Size index)
{
layers_.setCurrentLayer(index);
emit layerActivated(this);
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot3DCanvas::removeLayer(Size layer_index)
{
if (layer_index >= getLayerCount())
{
return;
}
layers_.removeLayer(layer_index);
recalculateRanges_();
if (layers_.empty())
{
overall_data_range_.clearRanges();
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
return;
}
resetZoom();
}
Plot3DOpenGLCanvas * Plot3DCanvas::openglwidget() const
{
return static_cast<Plot3DOpenGLCanvas *>(openglcanvas_);
}
#ifdef DEBUG_TOPPVIEW
void Plot3DCanvas::update_(const char * caller)
{
cout << "BEGIN " << OPENMS_PRETTY_FUNCTION << " caller: " << caller << endl;
#else
void Plot3DCanvas::update_(const char * /* caller */)
{
#endif
// make sure OpenGL already properly initialized
QOpenGLContext *ctx = QOpenGLContext::currentContext();
if (!ctx || !ctx->isValid()) return;
if (update_buffer_)
{
update_buffer_ = false;
if (intensity_mode_ == PlotCanvas::IM_SNAP)
{
openglwidget()->updateIntensityScale();
}
openglwidget()->initializeGL();
}
openglwidget()->resizeGL(width(), height());
openglwidget()->repaint();
}
void Plot3DCanvas::showCurrentLayerPreferences()
{
Internal::Plot3DPrefDialog dlg(this);
LayerDataBase& layer = getCurrentLayer();
// cout << "IN: " << param_ << endl;
ColorSelector * bg_color = dlg.findChild<ColorSelector *>("bg_color");
QComboBox * shade = dlg.findChild<QComboBox *>("shade");
MultiGradientSelector * gradient = dlg.findChild<MultiGradientSelector *>("gradient");
QSpinBox * width = dlg.findChild<QSpinBox *>("width");
bg_color->setColor(QColor(String(param_.getValue("background_color").toString()).toQString()));
shade->setCurrentIndex(layer.param.getValue("dot:shade_mode"));
gradient->gradient().fromString(layer.param.getValue("dot:gradient"));
width->setValue(UInt(layer.param.getValue("dot:line_width")));
if (dlg.exec())
{
param_.setValue("background_color", bg_color->getColor().name().toStdString());
layer.param.setValue("dot:shade_mode", shade->currentIndex());
layer.param.setValue("dot:gradient", gradient->gradient().toString());
layer.param.setValue("dot:line_width", width->value());
emit preferencesChange();
}
}
void Plot3DCanvas::currentLayerParamtersChanged_()
{
openglwidget()->recalculateDotGradient_(layers_.getCurrentLayer());
recalculateRanges_();
update_buffer_ = true;
update_(OPENMS_PRETTY_FUNCTION);
}
void Plot3DCanvas::contextMenuEvent(QContextMenuEvent * e)
{
//Abort of there are no layers
if (layers_.empty())
{
return;
}
QMenu * context_menu = new QMenu(this);
QAction * result = nullptr;
//Display name and warn if current layer invisible
String layer_name = String("Layer: ") + getCurrentLayer().getName();
if (!getCurrentLayer().visible)
{
layer_name += " (invisible)";
}
context_menu->addAction(layer_name.toQString())->setEnabled(false);
context_menu->addSeparator();
context_menu->addAction("Layer meta data");
QMenu * save_menu = new QMenu("Save");
context_menu->addMenu(save_menu);
save_menu->addAction("Layer");
save_menu->addAction("Visible layer data");
QMenu * settings_menu = new QMenu("Settings");
context_menu->addMenu(settings_menu);
settings_menu->addAction("Show/hide grid lines");
settings_menu->addAction("Show/hide axis legends");
settings_menu->addSeparator();
settings_menu->addAction("Preferences");
context_menu->addAction("Switch to 2D view");
//add external context menu
if (context_add_)
{
context_menu->addSeparator();
context_menu->addMenu(context_add_);
}
//evaluate menu
if ((result = context_menu->exec(mapToGlobal(e->pos()))))
{
if (result->text() == "Preferences")
{
showCurrentLayerPreferences();
}
else if (result->text() == "Show/hide grid lines")
{
showGridLines(!gridLinesShown());
}
else if (result->text() == "Show/hide axis legends")
{
emit changeLegendVisibility();
}
else if (result->text() == "Layer" || result->text() == "Visible layer data")
{
saveCurrentLayer(result->text() == "Visible layer data");
}
else if (result->text() == "Layer meta data")
{
showMetaData(true);
}
else if (result->text() == "Switch to 2D view")
{
emit showCurrentPeaksAs2D();
}
}
e->accept();
}
void Plot3DCanvas::updateLayer(Size i)
{
selected_peak_.clear();
recalculateRanges_();
resetZoom(false); // no repaint as this is done in intensityModeChange_() anyway
openglwidget()->recalculateDotGradient_(layers_.getLayer(i));
intensityModeChange_();
modificationStatus_(i, false);
}
void Plot3DCanvas::intensityModeChange_()
{
String gradient_str;
if (intensity_mode_ == IM_LOG)
{
gradient_str = MultiGradient::getDefaultGradientLogarithmicIntensityMode().toString();
}
else // linear
{
gradient_str = linear_gradient_.toString();
}
for (Size i = 0; i < layers_.getLayerCount(); ++i)
{
layers_.getLayer(i).param.setValue("dot:gradient", gradient_str);
openglwidget()->recalculateDotGradient_(layers_.getLayer(i));
}
PlotCanvas::intensityModeChange_();
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASOutputFileListVertex.cpp | .cpp | 8,587 | 226 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/TOPPASEdge.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <QtCore>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtWidgets/QMessageBox>
#include <QCoreApplication>
#include <future>
namespace OpenMS
{
std::unique_ptr<TOPPASVertex> TOPPASOutputFileListVertex::clone() const
{
return std::make_unique<TOPPASOutputFileListVertex>(*this);
}
String TOPPASOutputFileListVertex::getName() const
{
return "OutputFileVertex";
}
void TOPPASOutputFileListVertex::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
TOPPASVertex::paint(painter, option, widget);
QString text = QString::number(files_written_) + "/"
+ QString::number(files_total_) + " output file" + (files_total_ == 1 ? "" : "s");
QRectF text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), (int)(text_boundings.height() / 4.0), text);
// display file type(s)
QStringList text_l = TOPPASVertex::TOPPASFilenames(getFileNames()).getSuffixCounts();
text = text_l.join(" | ");
// might get very long, especially if node was not reached yet, so trim
text = text.left(15) + " ...";
text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), 35 - (int)(text_boundings.height() / 4.0), text);
// output folder name
painter->drawText(painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, output_folder_name_).width()/-2, -25, output_folder_name_);
}
QRectF TOPPASOutputFileListVertex::boundingRect() const
{
return QRectF(-71, -41, 142, 82);
}
void TOPPASOutputFileListVertex::run()
{
__DEBUG_BEGIN_METHOD__
// copy tmp files to output dir
// get incoming edge and preceding vertex
TOPPASEdge* e = *inEdgesBegin();
RoundPackages pkg = e->getSourceVertex()->getOutputFiles();
if (pkg.empty())
{
std::cerr << "A problem occurred while grabbing files from the parent tool. This is a bug, please report it!" << std::endl;
__DEBUG_END_METHOD__
return;
}
String full_dir = createOutputDir(); // create output dir
round_total_ = (int)pkg.size(); // take number of rounds from previous tool(s) - should all be equal
round_counter_ = 0; // once round_counter_ reaches round_total_, we are done
// clear output file list
output_files_.clear();
output_files_.resize(pkg.size()); // #rounds
files_total_ = 0;
files_written_ = 0;
const TOPPASScene* ts = qobject_cast<TOPPASScene*>(scene());
bool dry_run = ts->isDryRun();
int param_index_src = e->getSourceOutParam();
int param_index_me = e->getTargetInParam();
for (Size round = 0; round < pkg.size(); ++round)
{
for (const QString& f : pkg[round][param_index_src].filenames.get())
{
if (! dry_run && ! File::exists(f))
{
OPENMS_LOG_ERROR << "The file '" << String(f) << "' does not exist!" << std::endl;
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, f.toStdString());
}
QString new_file = full_dir.toQString() + QDir::separator() + File::basename(f).toQString();
// remove "_tmp<number>" if its a suffix
QRegularExpression rx("_tmp\\d+$");
int tmp_index = new_file.indexOf(rx);
if (tmp_index != -1)
{
new_file = new_file.left(tmp_index);
}
// get file type and rename
FileTypes::Type ft = FileTypes::UNKNOWN;
if (! dry_run)
{
TOPPASToolVertex* ttv = qobject_cast<TOPPASToolVertex*>(e->getSourceVertex());
if (ttv)
{
QVector<TOPPASToolVertex::IOInfo> source_output_files = ttv->getOutputParameters();
if (e->getSourceOutParam() < source_output_files.size())
{
StringList types = source_output_files[e->getSourceOutParam()].valid_types;
if (types.size() == 1) // if suffix is unambiguous
{
ft = FileTypes::nameToType(types[0]);
}
else
{
ft = FileHandler::getTypeByContent(f); // this will access the file physically
}
// do we know the extension already?
if (ft == FileTypes::UNKNOWN)
{ // if not, try param value of '<name>_type' (more generic, supporting more than just 'out_type')
const Param& p = ttv->getParam();
String out_type = source_output_files[e->getSourceOutParam()].param_name + "_type";
if (p.exists(out_type)) { ft = FileTypes::nameToType(p.getValue(out_type).toString()); }
}
}
}
}
// replace old suffix by new suffix
FileHandler::swapExtension(new_file, ft);
// only scheduled for writing
output_files_[round][param_index_me].filenames.push_back(QDir::toNativeSeparators(new_file));
++files_total_;
}
}
// do the actual copying
if (dry_run) // assume the copy worked
{
files_written_ = files_total_;
update(boundingRect()); // repaint
}
else
{
for (Size round = 0; round < pkg.size(); ++round)
{
round_counter_ = (int)round; // for global update, in case someone asks
for (int i = 0; i < pkg[round][param_index_src].filenames.size(); ++i)
{
String file_from = pkg[round][param_index_src].filenames[i];
String file_to = output_files_[round][param_index_me].filenames[i];
if (File::exists(file_to))
{
if (! QFile::remove(file_to.toQString())) // todo: this goes wrong on first run .... why???
{
String msg = "Error: Could not remove old output file '" + file_to + "' for node '"
+ pkg[round][param_index_src].edge->getTargetVertex()->getName()
+ "' in preparation to write the new one. Please make sure the file is not open in other applications and try again.";
OPENMS_LOG_ERROR << msg << std::endl;
if (ts->isGUIMode()) { QMessageBox::warning(nullptr, tr("File removing failed"), tr(msg.c_str()), QMessageBox::Ok); }
else
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, msg); // fail hard for ExecutePipeline
}
}
}
// running the copy() in an extra thread, such that the GUI stays responsive
auto copyFuture = std::async(std::launch::async, &File::copy, file_from, file_to);
while (copyFuture.wait_for(std::chrono::milliseconds(25)) != std::future_status::ready)
{
qApp->processEvents(); // GUI responsiveness
}
if (copyFuture.get())
{
++files_written_;
emit outputFileWritten(file_to);
}
else
{
String msg = "Error: Could not copy temporary output file '" + file_from + "' for node '"
+ pkg[round][param_index_src].edge->getTargetVertex()->getName() + "' to " + file_to
+ "'. Probably the old file still exists (see earlier errors).";
OPENMS_LOG_ERROR << msg << std::endl;
if (ts->isGUIMode()) { QMessageBox::warning(nullptr, tr("File copy failed"), tr(msg.c_str()), QMessageBox::Ok); }
else
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, msg); // fail hard for ExecutePipeline
}
}
}
update(boundingRect()); // repaint
}
}
finished_ = true;
__DEBUG_END_METHOD__
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/MetaDataBrowser.cpp | .cpp | 27,364 | 960 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/MetaDataBrowser.h>
#include <OpenMS/VISUAL/VISUALIZER/SampleVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/BaseVisualizerGUI.h>
#include <OpenMS/VISUAL/VISUALIZER/HPLCVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/GradientVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/MetaInfoVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/SoftwareVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/SourceFileVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/ContactPersonVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/InstrumentVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/IonSourceVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/IonDetectorVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/MassAnalyzerVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/DataProcessingVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/ProteinIdentificationVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/ProteinHitVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/PeptideHitVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/ExperimentalSettingsVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/AcquisitionVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/AcquisitionInfoVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/MetaInfoDescriptionVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/PrecursorVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/ProductVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/InstrumentSettingsVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/PeptideIdentificationVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/SpectrumSettingsVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/DocumentIdentifierVisualizer.h>
#include <OpenMS/VISUAL/VISUALIZER/ScanWindowVisualizer.h>
#include <QtWidgets/QLabel>
#include <QtWidgets/QStackedWidget>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QSplitter>
class QLayoutItem;
using namespace std;
//class QtWidgets/QLayoutItem;
namespace OpenMS
{
MetaDataBrowser::MetaDataBrowser(bool editable, QWidget * parent, bool modal) :
QDialog(parent),
editable_(editable)
{
setWindowTitle("Meta data");
setModal(modal);
//splitter to hold treewidget and the right part (on a dummy widget)
QGridLayout * grid = new QGridLayout(this);
QSplitter * splitter = new QSplitter(Qt::Horizontal, this);
grid->addWidget(splitter, 0, 0);
//Create the tree for exploring data
treeview_ = new QTreeWidget(this);
treeview_->setColumnCount(3);
treeview_->setHeaderLabel("Browse in Metadata tree");
treeview_->setRootIsDecorated(true);
treeview_->setColumnHidden(1, true);
treeview_->setColumnHidden(2, true);
splitter->addWidget(treeview_);
//create a dummy widget to hold a grid layout and the item stack
QWidget * dummy = new QWidget(splitter);
splitter->addWidget(dummy);
grid = new QGridLayout(dummy);
grid->setColumnStretch(0, 1);
//Create WidgetStack for managing visible metadata
ws_ = new QStackedWidget(dummy);
grid->addWidget(ws_, 0, 0, 1, 3);
if (isEditable())
{
saveallbutton_ = new QPushButton("OK", dummy);
cancelbutton_ = new QPushButton("Cancel", dummy);
grid->addWidget(saveallbutton_, 1, 1);
grid->addWidget(cancelbutton_, 1, 2);
connect(saveallbutton_, SIGNAL(clicked()), this, SLOT(saveAll_()));
connect(cancelbutton_, SIGNAL(clicked()), this, SLOT(reject()));
}
else
{
closebutton_ = new QPushButton("Close", dummy);
grid->addWidget(closebutton_, 1, 2);
connect(closebutton_, SIGNAL(clicked()), this, SLOT(reject()));
}
connect(treeview_, SIGNAL(itemSelectionChanged()), this, SLOT(showDetails_()));
status_list_ = "";
} //end of constructor
void MetaDataBrowser::connectVisualizer_(BaseVisualizerGUI * ptr)
{
connect(ptr, SIGNAL(sendStatus(std::string)), this, SLOT(setStatus(std::string)));
}
bool MetaDataBrowser::isEditable() const
{
return editable_;
}
void MetaDataBrowser::setStatus(const std::string& status)
{
status_list_ = status_list_ + "\n" + status;
}
void MetaDataBrowser::showDetails_()
{
QList<QTreeWidgetItem *> list = treeview_->selectedItems();
if (list.empty())
{
return;
}
ws_->setCurrentIndex(list[0]->text(1).toInt());
}
void MetaDataBrowser::saveAll_()
{
try
{
//call internal store function of all active visualizer objects
for (int i = 0; i < ws_->count(); ++i)
{
dynamic_cast<BaseVisualizerGUI *>(ws_->widget(i))->store();
}
if (status_list_.length() != 0)
{
status_list_ = status_list_ + "\n" + "\n" + "Invalid modifications will not be saved.";
QMessageBox::warning(this, tr("Save warning"), status_list_.c_str());
}
}
catch (exception & e)
{
cout << "Exception while trying to save modifications." << endl << e.what() << endl;
}
//close dialog
accept();
}
//-------------------------------------------------------------------------------
// overloaded visualize functions to call the corresponding data visualizer
// (in alphabetical oeder)
//-------------------------------------------------------------------------------
//Visualizing AcquisitionInfo object
void MetaDataBrowser::visualize_(AcquisitionInfo & meta, QTreeWidgetItem * parent)
{
AcquisitionInfoVisualizer * visualizer = new AcquisitionInfoVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "Acquisition Info" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//Get Aquisition objects
visualizeAll_(meta, item);
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing Acquisition object
void MetaDataBrowser::visualize_(Acquisition & meta, QTreeWidgetItem * parent)
{
AcquisitionVisualizer * visualizer = new AcquisitionVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "Acquisition" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing ContactPerson object
void MetaDataBrowser::visualize_(ContactPerson & meta, QTreeWidgetItem * parent)
{
ContactPersonVisualizer * visualizer = new ContactPersonVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "ContactPerson" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing ExperimentalSettings object
void MetaDataBrowser::visualize_(ExperimentalSettings & meta, QTreeWidgetItem * parent)
{
ExperimentalSettingsVisualizer * visualizer = new ExperimentalSettingsVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "ExperimentalSettings" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<DocumentIdentifier &>(meta), item);
//check for Sample
visualize_(meta.getSample(), item);
//check for Instrument
visualize_(meta.getInstrument(), item);
//check for SourceFiles
visualizeAll_(meta.getSourceFiles(), item);
//check for ContactPersons
visualizeAll_(meta.getContacts(), item);
//check for HPLC
visualize_(meta.getHPLC(), item);
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing Gradient object
void MetaDataBrowser::visualize_(Gradient & meta, QTreeWidgetItem * parent)
{
GradientVisualizer * visualizer = new GradientVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "Gradient" << QString::number(ws_->addWidget(visualizer));
if (parent == nullptr)
{
new QTreeWidgetItem(treeview_, labels);
}
else
{
new QTreeWidgetItem(parent, labels);
}
connectVisualizer_(visualizer);
}
//Visualizing HPLC object
void MetaDataBrowser::visualize_(HPLC & meta, QTreeWidgetItem * parent)
{
HPLCVisualizer * visualizer = new HPLCVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "HPLC" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(meta.getGradient(), item);
connectVisualizer_(visualizer);
}
//Visualizing PeptideIdentification object
void MetaDataBrowser::visualize_(PeptideIdentification & meta, QTreeWidgetItem * parent)
{
PeptideIdentificationVisualizer * visualizer = new PeptideIdentificationVisualizer(isEditable(), this, this);
QStringList labels;
int id = ws_->addWidget(visualizer);
labels << QString("PeptideIdentification %1").arg(meta.getScoreType().c_str()) << QString::number(id);
visualizer->load(meta, id);
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//check for proteins and peptides hits
meta.sort();
//list all peptides hits in the tree
for (Size i = 0; i < meta.getHits().size(); ++i)
{
visualize_(const_cast<PeptideHit &>(meta.getHits()[i]), item);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing ProteinIdentification object
void MetaDataBrowser::visualize_(ProteinIdentification & meta, QTreeWidgetItem * parent)
{
ProteinIdentificationVisualizer * visualizer = new ProteinIdentificationVisualizer(isEditable(), this, this);
QStringList labels;
int id = ws_->addWidget(visualizer);
labels << QString("ProteinIdentification %1").arg(meta.getSearchEngine().c_str()) << QString::number(id);
visualizer->load(meta, id);
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//check for proteinhits objects
meta.sort();
for (Size i = 0; i < meta.getHits().size(); ++i)
{
visualize_(const_cast<ProteinHit &>(meta.getHits()[i]), item);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing InstrumentSettings object
void MetaDataBrowser::visualize_(InstrumentSettings & meta, QTreeWidgetItem * parent)
{
InstrumentSettingsVisualizer * visualizer = new InstrumentSettingsVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "InstrumentSettings" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//ScanWindows
visualizeAll_(meta.getScanWindows(), item);
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing Instrument object
void MetaDataBrowser::visualize_(Instrument & meta, QTreeWidgetItem * parent)
{
InstrumentVisualizer * visualizer = new InstrumentVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "Instrument" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//IonSources
visualizeAll_(meta.getIonSources(), item);
//MassAnalyzers
visualizeAll_(meta.getMassAnalyzers(), item);
//IonDectector
visualizeAll_(meta.getIonDetectors(), item);
//Software
visualize_(meta.getSoftware(), item);
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing IonDetector object
void MetaDataBrowser::visualize_(IonDetector & meta, QTreeWidgetItem * parent)
{
IonDetectorVisualizer * visualizer = new IonDetectorVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "IonDetector" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing IonSource object
void MetaDataBrowser::visualize_(IonSource & meta, QTreeWidgetItem * parent)
{
IonSourceVisualizer * visualizer = new IonSourceVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "IonSource" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing MassAnalyzer object
void MetaDataBrowser::visualize_(MassAnalyzer & meta, QTreeWidgetItem * parent)
{
MassAnalyzerVisualizer * visualizer = new MassAnalyzerVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "MassAnalyzer" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing MetaInfoDescription object
void MetaDataBrowser::visualize_(MetaInfoDescription & meta, QTreeWidgetItem * parent)
{
MetaInfoDescriptionVisualizer * visualizer = new MetaInfoDescriptionVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
String name = String("MetaInfoDescription ") + meta.getName();
labels << name.c_str() << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//check for DataProcessing
visualizeAll_(meta.getDataProcessing(), item);
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing MetaInfoInterface object
void MetaDataBrowser::visualize_(MetaInfoInterface & meta, QTreeWidgetItem * parent)
{
MetaInfoVisualizer * visualizer = new MetaInfoVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "MetaInfo" << QString::number(ws_->addWidget(visualizer));
if (parent == nullptr)
{
new QTreeWidgetItem(treeview_, labels);
}
else
{
new QTreeWidgetItem(parent, labels);
}
connectVisualizer_(visualizer);
}
//Visualizing PeptideHit object
void MetaDataBrowser::visualize_(PeptideHit & meta, QTreeWidgetItem * parent)
{
PeptideHitVisualizer * visualizer = new PeptideHitVisualizer(isEditable(), this);
visualizer->load(meta);
String name = String("Pep ") + meta.getSequence().toString() + " (" + meta.getScore() + ')';
QString qs_name(name.c_str());
QStringList labels;
labels << qs_name << QString::number(ws_->addWidget(visualizer)) << QString::number(meta.getScore());
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing Precursor object
void MetaDataBrowser::visualize_(Precursor & meta, QTreeWidgetItem * parent)
{
PrecursorVisualizer * visualizer = new PrecursorVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "Precursor" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing Product object
void MetaDataBrowser::visualize_(Product & meta, QTreeWidgetItem * parent)
{
ProductVisualizer * visualizer = new ProductVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "Product" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing DataProcessing object
void MetaDataBrowser::visualize_(DataProcessingPtr & meta, QTreeWidgetItem * parent)
{
DataProcessingVisualizer * visualizer = new DataProcessingVisualizer(isEditable(), this);
visualizer->load(*meta);
QStringList labels;
labels << "DataProcessing" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//Software object
visualize_(meta->getSoftware(), item);
visualize_(dynamic_cast<MetaInfoInterface &>(*meta), item);
connectVisualizer_(visualizer);
}
//Visualizing ProteinHit object
void MetaDataBrowser::visualize_(ProteinHit & meta, QTreeWidgetItem * parent)
{
ProteinHitVisualizer * visualizer = new ProteinHitVisualizer(isEditable(), this);
visualizer->load(meta);
String name = String("Prot ") + meta.getAccession() + " (" + meta.getScore() + ')';
QString qs_name(name.c_str());
QStringList labels;
labels << qs_name << QString::number(ws_->addWidget(visualizer)) << QString::number(meta.getScore());
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing ProteinHit object
void MetaDataBrowser::visualize_(ScanWindow & meta, QTreeWidgetItem * parent)
{
ScanWindowVisualizer * visualizer = new ScanWindowVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "Scan window" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing sample object
void MetaDataBrowser::visualize_(Sample & meta, QTreeWidgetItem * parent)
{
SampleVisualizer * visualizer = new SampleVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << (String("Sample ") + meta.getName()).c_str() << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//subsamples
visualizeAll_(meta.getSubsamples(), item);
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing Software object
void MetaDataBrowser::visualize_(Software & meta, QTreeWidgetItem * parent)
{
SoftwareVisualizer * visualizer = new SoftwareVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "Software" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing SourceFile object
void MetaDataBrowser::visualize_(SourceFile & meta, QTreeWidgetItem * parent)
{
SourceFileVisualizer * visualizer = new SourceFileVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "SourceFile" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
visualize_(dynamic_cast<MetaInfoInterface &>(meta), item);
connectVisualizer_(visualizer);
}
//Visualizing SpectrumSettings object
void MetaDataBrowser::visualize_(SpectrumSettings & meta, QTreeWidgetItem * parent)
{
SpectrumSettingsVisualizer * visualizer = new SpectrumSettingsVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "SpectrumSettings" << QString::number(ws_->addWidget(visualizer));
QTreeWidgetItem * item;
if (parent == nullptr)
{
item = new QTreeWidgetItem(treeview_, labels);
}
else
{
item = new QTreeWidgetItem(parent, labels);
}
//check for InstrumentSettings
visualize_(meta.getInstrumentSettings(), item);
//check for DataProcessing
visualizeAll_(meta.getDataProcessing(), item);
//check for Precursors
for (Size i = 0; i < meta.getPrecursors().size(); ++i)
{
visualize_(meta.getPrecursors()[i], item);
}
//check for Products
for (Size i = 0; i < meta.getProducts().size(); ++i)
{
visualize_(meta.getProducts()[i], item);
}
//check for AcquisitionInfo
visualize_(meta.getAcquisitionInfo(), item);
connectVisualizer_(visualizer);
}
//Visualizing tagging object
void MetaDataBrowser::visualize_(DocumentIdentifier & meta, QTreeWidgetItem * parent)
{
DocumentIdentifierVisualizer * visualizer = new DocumentIdentifierVisualizer(isEditable(), this);
visualizer->load(meta);
QStringList labels;
labels << "DocumentIdentifier" << QString::number(ws_->addWidget(visualizer));
if (parent == nullptr)
{
new QTreeWidgetItem(treeview_, labels);
}
else
{
new QTreeWidgetItem(parent, labels);
}
connectVisualizer_(visualizer);
}
void MetaDataBrowser::filterHits_(double threshold, bool higher_better, int tree_item_id)
{
// find item in tree belonging to PeptideIdentification object
QTreeWidgetItem * item = treeview_->findItems(QString::number(tree_item_id), Qt::MatchExactly | Qt::MatchRecursive, 1).first();
//set the items visible or not visible depending to their score and the current threshold
for (int i = 0; i < item->childCount(); ++i)
{
QTreeWidgetItem * child = item->child(i);
if ((higher_better && child->text(2).toFloat() <= threshold) || (!higher_better && child->text(2).toFloat() >= threshold))
{
child->setHidden(true);
}
else
{
child->setHidden(false);
}
}
//parent item must be collapsed and re-expanded so the items will be shown...
treeview_->collapseItem(item);
treeview_->expandItem(item);
}
/// Filters hits according to a score @a threshold. Takes the score orientation into account
void MetaDataBrowser::showAllHits_(int tree_item_id)
{
// find item in tree belonging to PeptideIdentification object
QTreeWidgetItem * item = treeview_->findItems(QString::number(tree_item_id), Qt::MatchExactly | Qt::MatchRecursive, 1).first();
//set the items visible or not visible depending to their score and the current threshold
for (int i = 0; i < item->childCount(); ++i)
{
item->child(i)->setHidden(false);
}
//parent item must be collapsed and re-expanded so the items will be shown...
treeview_->collapseItem(item);
treeview_->expandItem(item);
}
void MetaDataBrowser::add(Feature & feature)
{
//peptide ids
for (PeptideIdentification& pep : feature.getPeptideIdentifications())
{
add(pep);
}
add(static_cast<MetaInfoInterface &>(feature));
treeview_->expandItem(treeview_->findItems(QString::number(0), Qt::MatchExactly, 1).first());
}
void MetaDataBrowser::add(ConsensusFeature & feature)
{
//peptide ids
for (PeptideIdentification& pep : feature.getPeptideIdentifications())
{
add(pep);
}
add(static_cast<MetaInfoInterface &>(feature));
treeview_->expandItem(treeview_->findItems(QString::number(0), Qt::MatchExactly, 1).first());
}
void MetaDataBrowser::add(ConsensusMap & map)
{
//identifier
add(static_cast<DocumentIdentifier &>(map));
// protein identifications
for (Size i = 0; i < map.getProteinIdentifications().size(); ++i)
{
add(map.getProteinIdentifications()[i]);
}
//unassigned peptide ids
for (Size i = 0; i < map.getUnassignedPeptideIdentifications().size(); ++i)
{
add(map.getUnassignedPeptideIdentifications()[i]);
}
add(static_cast<MetaInfoInterface &>(map));
treeview_->expandItem(treeview_->findItems(QString::number(0), Qt::MatchExactly, 1).first());
}
} //end of MetaDataBrowser
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/AxisWidget.cpp | .cpp | 4,430 | 222 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// Qt
#include <QPaintEvent>
#include <QPainter>
#include <QBrush>
// STL
#include <iostream>
#include <algorithm>
// OpenMS
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/VISUAL/AxisTickCalculator.h>
#include <OpenMS/VISUAL/AxisPainter.h>
#include <OpenMS/MATH/MathFunctions.h>
using namespace std;
namespace OpenMS
{
using namespace Math;
AxisWidget::AxisWidget(const AxisPainter::Alignment alignment, const char* legend, QWidget* parent) :
QWidget(parent),
is_log_(false),
show_legend_(true),
alignment_(alignment),
is_inverse_orientation_(false),
margin_(0),
legend_(legend),
tick_level_(2),
allow_short_numbers_(false)
{
setAxisBounds(0.0, 100.0);
if (alignment == AxisPainter::RIGHT || alignment == AxisPainter::LEFT)
{
setMinimumSize(30, 100);
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::MinimumExpanding);
}
else
{
setMinimumSize(100, 30);
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
}
resize(minimumSize());
}
AxisWidget::~AxisWidget() = default;
void AxisWidget::paintEvent(QPaintEvent * e)
{
QPainter painter(this);
paint(&painter, e);
painter.end();
}
void AxisWidget::paint(QPainter * painter, QPaintEvent * e)
{
AxisPainter::paint(painter, e, min_, max_, grid_line_,
width(), height(), alignment_, margin_,
show_legend_, legend_, allow_short_numbers_, is_log_, is_inverse_orientation_);
}
void AxisWidget::setAxisBounds(double min, double max)
{
if (min >= max)
{
return;
}
if (is_log_)
{
// abort if no change
if (min_ == linear2log(min) && max_ == linear2log(max))
return;
min_ = linear2log(min);
max_ = linear2log(max);
AxisTickCalculator::calcLogGridLines(min_, max_, grid_line_);
}
else
{
//abort if no change
if (min_ == min && max_ == max)
return;
min_ = min;
max_ = max;
AxisTickCalculator::calcGridLines(min_, max_, grid_line_);
}
update();
}
void AxisWidget::setLogScale(bool is_log)
{
if (is_log_ != is_log)
{
is_log_ = is_log;
if (is_log_)
{
setAxisBounds(min_, max_);
}
else
{
setAxisBounds(log2linear(min_), log2linear(max_));
}
update();
}
}
bool AxisWidget::isLogScale() const
{
return is_log_;
}
UInt AxisWidget::margin() const
{
return margin_;
}
void AxisWidget::setMargin(UInt margin)
{
if (margin_ != margin)
{
margin_ = margin;
update();
}
}
void AxisWidget::showLegend(bool show_legend)
{
if (show_legend_ != show_legend)
{
show_legend_ = show_legend;
if (show_legend_)
{
setToolTip("");
}
else
{
setToolTip(legend_.c_str());
}
update();
}
}
bool AxisWidget::isLegendShown() const
{
return show_legend_;
}
const String& AxisWidget::getLegend() const
{
return legend_;
}
void AxisWidget::setInverseOrientation(bool inverse_orientation)
{
if (is_inverse_orientation_ != inverse_orientation)
{
is_inverse_orientation_ = inverse_orientation;
update();
}
}
bool AxisWidget::hasInverseOrientation() const
{
return is_inverse_orientation_;
}
void AxisWidget::setLegend(const String & legend)
{
legend_ = legend;
if (!show_legend_)
{
setToolTip(legend_.c_str());
}
}
void AxisWidget::setTickLevel(UInt level)
{
if (level == 1 || level == 2)
{
tick_level_ = level;
}
}
const AxisWidget::GridVector & AxisWidget::gridLines() const
{
return grid_line_;
}
void AxisWidget::setAllowShortNumbers(bool short_nums)
{
allow_short_numbers_ = short_nums;
}
double AxisWidget::getAxisMinimum() const
{
return min_;
}
double AxisWidget::getAxisMaximum() const
{
return max_;
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASEdge.cpp | .cpp | 19,491 | 698 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/DIALOGS/TOPPASIOMappingDialog.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/TOPPASEdge.h>
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASMergerVertex.h>
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASOutputFolderVertex.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/TOPPASSplitterVertex.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <QPainter>
#include <QPainterPath>
#include <QtWidgets/QMessageBox>
#include <QApplication>
namespace OpenMS
{
TOPPASEdge::TOPPASEdge() :
QObject(),
QGraphicsItem(),
from_(nullptr),
to_(nullptr),
hover_pos_(),
color_(),
source_out_param_(-1),
target_in_param_(-1)
{
setFlag(QGraphicsItem::ItemIsSelectable, true);
}
TOPPASEdge::TOPPASEdge(TOPPASVertex* from, const QPointF& hover_pos) :
QObject(),
QGraphicsItem(),
from_(from),
to_(nullptr),
hover_pos_(hover_pos),
color_(),
source_out_param_(-1),
target_in_param_(-1)
{
setFlag(QGraphicsItem::ItemIsSelectable, true);
}
TOPPASEdge::TOPPASEdge(const TOPPASEdge& rhs) :
QObject(),
QGraphicsItem(),
from_(rhs.from_),
to_(rhs.to_),
hover_pos_(rhs.hover_pos_),
color_(rhs.color_),
source_out_param_(rhs.source_out_param_),
target_in_param_(rhs.target_in_param_)
{
setFlag(QGraphicsItem::ItemIsSelectable, true);
}
String TOPPASEdge::toString()
{
String s = String("Edge: ") + getSourceOutParamName() + " target-in: " + getTargetInParamName() + "\n";
return s;
}
TOPPASEdge& TOPPASEdge::operator=(const TOPPASEdge& rhs)
{
from_ = rhs.from_;
to_ = rhs.to_;
hover_pos_ = rhs.hover_pos_;
color_ = rhs.color_;
source_out_param_ = rhs.source_out_param_;
target_in_param_ = rhs.target_in_param_;
setFlag(QGraphicsItem::ItemIsSelectable, true);
return *this;
}
TOPPASEdge::~TOPPASEdge()
{
// notify our childs that we are dying ;)
emit somethingHasChanged();
if (from_)
{
from_->removeOutEdge(this);
disconnect(from_, SIGNAL(somethingHasChanged()), this, SLOT(sourceHasChanged()));
}
if (to_)
{
to_->removeInEdge(this);
disconnect(this, SIGNAL(somethingHasChanged()), to_, SLOT(inEdgeHasChanged()));
}
}
QRectF TOPPASEdge::boundingRect() const
{
qreal min_x = startPos().x() < endPos().x() ? startPos().x() : endPos().x();
qreal min_y = startPos().y() < endPos().y() ? startPos().y() : endPos().y();
qreal max_x = startPos().x() > endPos().x() ? startPos().x() : endPos().x();
qreal max_y = startPos().y() > endPos().y() ? startPos().y() : endPos().y();
return QRectF(QPointF(min_x - 11.0, min_y - 11.0), QPointF(max_x + 11.0, max_y + 11.0));
}
QPainterPath TOPPASEdge::shape() const
{
QPainterPath shape_1;
shape_1.moveTo(startPos() + QPointF(-10, -10));
shape_1.lineTo(endPos() + QPointF(-10, -10));
shape_1.lineTo(endPos() + QPointF(10, 10));
shape_1.lineTo(startPos() + QPointF(10, 10));
shape_1.closeSubpath();
QPainterPath shape_2;
shape_2.moveTo(startPos() + QPointF(-10, 10));
shape_2.lineTo(endPos() + QPointF(-10, 10));
shape_2.lineTo(endPos() + QPointF(10, -10));
shape_2.lineTo(startPos() + QPointF(10, -10));
shape_2.closeSubpath();
return shape_1.united(shape_2);
}
void TOPPASEdge::paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/)
{
painter->setBrush(Qt::white);
QPen pen(color_);
if (isSelected())
{
pen.setWidth(3);
}
else
{
pen.setWidth(2);
}
TOPPASToolVertex* ttv_source = qobject_cast<TOPPASToolVertex*>(this->getSourceVertex());
// when copying parameters (using CTRL); only for incomplete edges drawn from tool nodes
if ((QGuiApplication::keyboardModifiers() & Qt::ControlModifier) && !this->to_ && ttv_source)
{
pen.setColor(Qt::darkMagenta);
pen.setWidth(1);
}
painter->setPen(pen);
// angle of line
qreal angle = -QLineF(endPos(), startPos()).angle() + 180; // negate since angle() reports counter-clockwise; +180 since painter.rotate() is more intuitive then
// draw the actual line
QPainterPath path_line(startPos());
path_line.lineTo(endPos());
painter->drawPath(path_line);
// print names
qreal text_angle = angle;
bool invert_text_direction = endPos().x() < startPos().x();
if (invert_text_direction)
{
text_angle += 180;
}
QPainterPath path_line_short(borderPoint_(false));
path_line_short.lineTo(endPos());
// y offset for printing text; we add -1 to make "_" in param names visible (e.g. in "out_annotation")
// otherwise they are too close to the edge itself
int y_text = -pen.width() - 1;
// source name
QString str = getSourceOutParamName();
if (!str.isEmpty())
{
painter->save(); // hard to avoid multiple calls to save() and restore() since we first translate and then rotate
QPointF point = path_line_short.pointAtPercent(0.05);
painter->translate(point);
painter->rotate(text_angle);
if (invert_text_direction)
{
QFontMetrics fm(painter->fontMetrics());
int text_width = fm.horizontalAdvance(str);
painter->drawText(QPoint(-text_width, y_text), str);
}
else
{
painter->drawText(QPoint(0, y_text), str);
}
painter->restore();
}
// target name
const qreal arrow_width = 10; // required multiple times, so defined here to avoid inconsistencies
str = getTargetInParamName();
if (!str.isEmpty())
{
painter->save();
// qreal pc = path_line_short.percentAtLength(10);
QPointF point = path_line_short.pointAtPercent(0.95);
painter->translate(point);
painter->rotate(text_angle);
QFontMetrics fm(painter->fontMetrics());
int text_width = fm.horizontalAdvance(str);
int text_height = fm.height(); // shift text below the edge by its own height
if (invert_text_direction)
{
painter->drawText(QPoint(arrow_width, text_height + y_text), str);
}
else
{
painter->drawText(QPoint(-text_width - arrow_width, text_height + y_text), str);
}
painter->restore();
}
// draw arrow head
painter->save();
painter->translate(endPos());
painter->rotate(angle);
QPainterPath path;
path.moveTo(QPointF(0, 0));
path.lineTo(QPointF(-arrow_width, 4));
path.lineTo(QPointF(-arrow_width, -4));
path.closeSubpath();
painter->drawPath(path);
painter->restore();
}
QPointF TOPPASEdge::startPos() const
{
if (from_)
{
return mapFromScene(from_->scenePos());
}
else
{
return QPointF();
}
}
QPointF TOPPASEdge::endPos() const
{
if (!to_)
{
// we do not have a target vertex yet
return (hover_pos_);
}
else
{
// we have a target node --> line should end at its border
return (borderPoint_());
}
}
QPointF TOPPASEdge::borderPoint_(bool atTargetVertex) const
{
if (!to_ || !from_)
{
return QPointF(); // both ends need to be fixed; otherwise we have no input/output slots assigned anyways
}
const TOPPASVertex* to = (atTargetVertex ? to_ : from_);
const TOPPASVertex* from = (!atTargetVertex ? to_ : from_);
const QPointF fromP = mapFromScene(from->scenePos());
QRectF target_boundings = mapFromItem(to, to->shape()).boundingRect();
return GUIHelpers::intersectionPoint(target_boundings, fromP);
}
void TOPPASEdge::setHoverPos(const QPointF& pos)
{
prepareResize();
hover_pos_ = pos;
update();
}
void TOPPASEdge::setTargetVertex(TOPPASVertex* tv)
{
to_ = tv;
}
void TOPPASEdge::setSourceVertex(TOPPASVertex* tv)
{
from_ = tv;
}
TOPPASVertex* TOPPASEdge::getSourceVertex()
{
return from_;
}
TOPPASVertex* TOPPASEdge::getTargetVertex()
{
return to_;
}
void TOPPASEdge::prepareResize()
{
prepareGeometryChange();
}
void TOPPASEdge::setColor(const QColor& color)
{
color_ = color;
}
void TOPPASEdge::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* /*e*/)
{
showIOMappingDialog();
}
void TOPPASEdge::showIOMappingDialog()
{
TOPPASIOMappingDialog dialog(this);
if (dialog.exec())
{
emit somethingHasChanged();
}
}
TOPPASEdge::EdgeStatus TOPPASEdge::getToolToolStatus_(TOPPASToolVertex* source_tool, int source_param_index, TOPPASToolVertex* target_tool, int target_param_index)
{
if (source_param_index < 0)
{
return ES_NO_SOURCE_PARAM;
}
if (target_param_index < 0)
{
return ES_NO_TARGET_PARAM;
}
QVector<TOPPASToolVertex::IOInfo> source_output_files = source_tool->getOutputParameters();
if (source_param_index >= source_output_files.size())
{
return ES_TOOL_API_CHANGED;
}
QVector<TOPPASToolVertex::IOInfo> target_input_files = target_tool->getInputParameters();
if (target_param_index >= target_input_files.size())
{
return ES_TOOL_API_CHANGED;
}
const TOPPASToolVertex::IOInfo& source_param = source_output_files[source_param_index];
StringList source_param_types = source_param.valid_types;
const TOPPASToolVertex::IOInfo& target_param = target_input_files[target_param_index];
StringList target_param_types = target_param.valid_types;
if (source_param_types.empty() || target_param_types.empty())
{
// no type specified --> allow edge
return ES_VALID;
}
else
{
// check file type compatibility
bool found_match = false;
for (StringList::iterator s_it = source_param_types.begin(); s_it != source_param_types.end(); ++s_it)
{
String ext_1 = *s_it;
ext_1.toLower();
found_match = false;
for (StringList::iterator t_it = target_param_types.begin(); t_it != target_param_types.end(); ++t_it)
{
String ext_2 = *t_it;
ext_2.toLower();
if (ext_1 == ext_2)
{
found_match = true;
break;
}
}
if (found_match)
{
break;
}
}
if (!found_match)
{
return ES_FILE_EXT_MISMATCH;
}
return ES_VALID;
}
}
TOPPASEdge::EdgeStatus TOPPASEdge::getListToolStatus_(TOPPASInputFileListVertex* source_input_list, TOPPASToolVertex* target_tool, int target_param_index)
{
QVector<TOPPASToolVertex::IOInfo> target_input_files = target_tool->getInputParameters();
if (target_param_index >= target_input_files.size())
{
return ES_TOOL_API_CHANGED;
}
const QStringList& file_names = source_input_list->getFileNames();
if (file_names.empty())
{
// file names are not specified yet
return ES_NOT_READY_YET;
}
if (target_param_index < 0)
{
return ES_NO_TARGET_PARAM;
}
const TOPPASToolVertex::IOInfo& target_param = target_input_files[target_param_index];
StringList target_param_types = target_param.valid_types;
if (target_param_types.empty())
{
// no file types specified --> allow
return ES_VALID;
}
// check file type compatibility
for (const QString& q_file_name : file_names)
{
bool type_mismatch = true;
const String& file_name = String(q_file_name);
String::SizeType extension_start_index = file_name.rfind(".");
if (extension_start_index != String::npos)
{
String extension = file_name.substr(extension_start_index + 1);
extension.toLower();
for (StringList::iterator it = target_param_types.begin(); it != target_param_types.end(); ++it)
{
String other_ext = *it;
other_ext.toLower();
if (extension == other_ext || extension == "gz" || extension == "bz2")
{
type_mismatch = false;
break;
}
}
}
if (type_mismatch)
{
return ES_FILE_EXT_MISMATCH;
}
}
// all file types ok
return ES_VALID;
}
TOPPASEdge::EdgeStatus TOPPASEdge::getEdgeStatus()
{
TOPPASVertex* source = getSourceVertex();
TOPPASVertex* target = getTargetVertex();
TOPPASMergerVertex* source_merger = qobject_cast<TOPPASMergerVertex*>(source);
TOPPASMergerVertex* target_merger = qobject_cast<TOPPASMergerVertex*>(target);
TOPPASSplitterVertex* source_splitter = qobject_cast<TOPPASSplitterVertex*>(source);
TOPPASSplitterVertex* target_splitter = qobject_cast<TOPPASSplitterVertex*>(target);
TOPPASInputFileListVertex* source_input_list = qobject_cast<TOPPASInputFileListVertex*>(source);
TOPPASOutputVertex* target_output = qobject_cast<TOPPASOutputVertex*>(target);
TOPPASToolVertex* source_tool = qobject_cast<TOPPASToolVertex*>(source);
TOPPASToolVertex* target_tool = qobject_cast<TOPPASToolVertex*>(target);
if (source_tool && source_out_param_ < 0)
{
return ES_NO_SOURCE_PARAM;
}
if (target_tool && target_in_param_ < 0)
{
return ES_NO_TARGET_PARAM;
}
if (source_tool)
{
if (target_output) // edges to output vertices are always valid
{
return ES_VALID;
}
if (target_tool)
{
return getToolToolStatus_(source_tool, source_out_param_, target_tool, target_in_param_);
}
}
if (source_input_list && target_tool)
{
return getListToolStatus_(source_input_list, target_tool, target_in_param_);
}
if (source_merger || source_splitter)
{
// check compatibility of source with all target nodes of merger (or splitter)
for (TOPPASVertex::ConstEdgeIterator e_it = source->inEdgesBegin(); e_it != source->inEdgesEnd(); ++e_it)
{
TOPPASEdge* merger_in_edge = *e_it;
TOPPASToolVertex* merger_in_tool = qobject_cast<TOPPASToolVertex*>(merger_in_edge->getSourceVertex());
TOPPASInputFileListVertex * merger_in_list = qobject_cast<TOPPASInputFileListVertex*>(merger_in_edge->getSourceVertex());
if (merger_in_tool && target_tool)
{
EdgeStatus es = getToolToolStatus_(merger_in_tool, merger_in_edge->getSourceOutParam(), target_tool, target_in_param_);
if (es != ES_VALID)
{
return es;
}
}
else if (merger_in_list)
{
if (target_output)
{
// [input] -> [merger] -> [output]) makes no sense
return ES_MERGER_WITHOUT_TOOL;
}
else if (target_tool)
{
EdgeStatus es = getListToolStatus_(merger_in_list, target_tool, target_in_param_);
if (es != ES_VALID)
{
return es;
}
}
}
}
// no incompatible merger target found
return ES_VALID;
}
if (target_merger || target_splitter)
{
// check compatibility of source with all target nodes of merger (or splitter)
for (TOPPASVertex::ConstEdgeIterator e_it = target->outEdgesBegin(); e_it != target->outEdgesEnd(); ++e_it)
{
TOPPASEdge* merger_out_edge = *e_it;
TOPPASToolVertex* merger_out_tool = qobject_cast<TOPPASToolVertex*>(merger_out_edge->getTargetVertex());
TOPPASOutputFileListVertex* merger_out_output = qobject_cast<TOPPASOutputFileListVertex*>(merger_out_edge->getTargetVertex());
if (source_tool)
{
if (merger_out_tool)
{
EdgeStatus es = getToolToolStatus_(source_tool, source_out_param_, merger_out_tool, merger_out_edge->getTargetInParam());
if (es != ES_VALID)
{
return es;
}
}
}
else if (source_input_list)
{
if (merger_out_tool)
{
EdgeStatus es = getListToolStatus_(source_input_list, merger_out_tool, merger_out_edge->getTargetInParam());
if (es != ES_VALID)
{
return es;
}
}
else if (merger_out_output)
{
// [input] -> [merger] -> [output]) makes no sense
return ES_MERGER_WITHOUT_TOOL;
}
}
}
// no incompatible merger target found
return ES_VALID;
}
return ES_UNKNOWN;
}
void TOPPASEdge::setSourceOutParam(int out)
{
source_out_param_ = out;
}
int TOPPASEdge::getSourceOutParam() const
{
return source_out_param_;
}
void TOPPASEdge::setTargetInParam(int in)
{
target_in_param_ = in;
}
int TOPPASEdge::getTargetInParam() const
{
return target_in_param_;
}
QString TOPPASEdge::getTargetInParamName()
{
const EdgeStatus& es = getEdgeStatus();
if (es != ES_TOOL_API_CHANGED)
{
TOPPASVertex* target_o = getTargetVertex();
const TOPPASToolVertex* target = qobject_cast<TOPPASToolVertex*>(target_o);
if (target && target_in_param_>=0)
{
QVector<TOPPASToolVertex::IOInfo> docks = target->getInputParameters();
const TOPPASToolVertex::IOInfo& param = docks[this->target_in_param_];
return param.param_name.toQString();
}
}
return "";
}
QString TOPPASEdge::getSourceOutParamName()
{
const EdgeStatus& es = getEdgeStatus();
if (es != ES_TOOL_API_CHANGED)
{
const auto* source_vertex = getSourceVertex();
const auto* source_tool = qobject_cast<const TOPPASToolVertex*>(source_vertex);
if (source_tool && source_out_param_>=0)
{
return source_tool->getOutputParameters()[this->source_out_param_].param_name.toQString();
}
}
return "";
}
void TOPPASEdge::updateColor()
{
const EdgeStatus& es = getEdgeStatus();
if (es == ES_VALID)
{
setColor(Qt::darkGreen);
}
else if (es == ES_NOT_READY_YET)
{
setColor(QColor(255, 165, 0));
}
else
{
setColor(Qt::red);
}
update(boundingRect());
}
void TOPPASEdge::sourceHasChanged()
{
emit somethingHasChanged();
}
void TOPPASEdge::emitChanged()
{
emit somethingHasChanged();
}
void TOPPASEdge::contextMenuEvent(QGraphicsSceneContextMenuEvent* event)
{
TOPPASScene* ts = qobject_cast<TOPPASScene*>(scene());
ts->unselectAll();
setSelected(true);
QMenu menu;
menu.addAction("Edit I/O mapping");
menu.addAction("Remove");
QAction* selected_action = menu.exec(event->screenPos());
if (selected_action)
{
QString text = selected_action->text();
if (text == "Edit I/O mapping")
{
TOPPASIOMappingDialog dialog(this);
if (dialog.exec())
{
emit somethingHasChanged();
}
}
else if (text == "Remove")
{
ts->removeSelected();
}
event->accept();
}
else
{
event->ignore();
}
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/AxisPainter.cpp | .cpp | 8,175 | 292 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/AxisPainter.h>
#include <OpenMS/MATH/MathFunctions.h>
using namespace std;
namespace OpenMS
{
using namespace Math;
void AxisPainter::paint(QPainter * painter, QPaintEvent *, const double & min, const double & max, const GridVector & grid,
const Int width, const Int height, const AxisPainter::Alignment alignment, const UInt margin,
bool show_legend, const String& legend, bool shorten_number,
bool is_log, bool is_inverse_orientation)
{
// position of the widget
bool horizontal_alignment = (alignment == BOTTOM || alignment == TOP);
// spacing between ticks and text
const UInt tick_spacing = 4;
// determine paintable area without margin
UInt h = height;
UInt w = width;
w = (horizontal_alignment) ? w - margin : w;
h = (horizontal_alignment) ? h : h - margin;
// paint axis lines
switch (alignment)
{
case BOTTOM:
painter->drawLine(0, 0, w - 1, 0);
break;
case TOP:
painter->drawLine(0, h - 1, w - 1, h - 1);
break;
case LEFT:
painter->drawLine(w - 1, 0, w - 1, h - 1);
break;
case RIGHT:
painter->drawLine(0, 0, 0, h - 1);
break;
}
// shrink font size if text does not fit
UInt font_size = painter->font().pointSize();
UInt max_width = 0;
if (!grid.empty()) //check big intervals only
{
QFontMetrics metrics(QFont(painter->font().family(), font_size));
for (Size i = 0; i < grid[0].size(); i++)
{
QString tmp;
if (shorten_number)
{
getShortenedNumber_(tmp, scale_(grid[0][i], is_log));
}
else
{
tmp = QString("%1").arg(scale_(grid[0][i], is_log));
}
QRect rect = metrics.boundingRect(tmp);
max_width = std::max(max_width, (UInt)rect.width());
}
}
//shrink font if too much text it displayed
UInt overall_required_pixels = 0;
if (horizontal_alignment)
{
Size tick_count = 0;
for (Size i = 0; i < grid.size(); i++)
{
tick_count += grid[i].size();
}
overall_required_pixels = (UInt)(max_width * tick_count);
}
else // Shrink font if the largest text is too big
{
overall_required_pixels = UInt(max_width + 0.25 * font_size + tick_spacing);
}
if (w < overall_required_pixels)
{
font_size = UInt(font_size * w / overall_required_pixels);
}
// Painting tick levels
for (Size i = 0; i != grid.size(); i++)
{
// Just draw text on big intervals
if (is_log && i > 0)
{
break;
}
QColor text_color;
UInt tick_size = 0;
QFontMetrics metrics(painter->font());
if (i == 0) // big intervals
{
painter->setFont(QFont(painter->font().family(), UInt(font_size)));
metrics = QFontMetrics(painter->font());
tick_size = UInt(0.33 * font_size);
text_color = QColor(0, 0, 0);
}
else // small intervals
{
painter->setFont(QFont(painter->font().family(), UInt(0.8 * font_size)));
metrics = QFontMetrics(painter->font());
tick_size = UInt(0.25 * font_size);
text_color = QColor(20, 20, 20);
}
// painting all ticks of the level
UInt i_beg = (horizontal_alignment) ? 0 : h;
UInt i_end = (horizontal_alignment) ? w : 0;
for (Size j = 0; j != grid[i].size(); j++)
{
UInt tick_pos;
if (is_inverse_orientation)
{
tick_pos = UInt(intervalTransformation(grid[i][j], min, max, i_end, i_beg)) + ((alignment == LEFT || alignment == RIGHT) ? -1 : 1) * margin;
}
else
{
tick_pos = UInt(intervalTransformation(grid[i][j], min, max, i_beg, i_end));
}
// paint ticks
painter->setPen(QPen(Qt::black));
switch (alignment)
{
case BOTTOM:
painter->drawLine(tick_pos, 0, tick_pos, tick_size);
break;
case TOP:
painter->drawLine(tick_pos, h, tick_pos, h - tick_size);
break;
case LEFT:
painter->drawLine(w - tick_size, tick_pos + margin, w, tick_pos + margin);
break;
case RIGHT:
painter->drawLine(0, tick_pos + margin, tick_size, tick_pos + margin);
break;
}
// values at axis lines
// count number of grid lines
Size gl_count = 0;
for (GridVector::const_iterator it = grid.begin(); it != grid.end(); ++it)
{
gl_count += it->size();
}
// if there are too many grid lines, hide every odd minor grid line value
if (gl_count >= 30 && i == 1)
{
// needed because skips occur in small grid lines at the position of big grid lines
double dist_small = std::min<double>(fabs(grid[1][1] - grid[1][0]), fabs(grid[1][2] - grid[1][1]));
UInt n = Math::round((grid[1][j] - grid[0][0]) / dist_small);
if (n % 2 == 1)
{
continue;
}
}
QString text;
if (shorten_number)
{
getShortenedNumber_(text, scale_(grid[i][j], is_log));
}
else
{
text = QString("%1").arg(scale_(grid[i][j], is_log));
}
painter->setPen(QPen(text_color));
// get bounding rectangle for text we want to layout
QRect textbound = metrics.boundingRect(text);
// Calculate text position
UInt x_pos = 0;
switch (alignment)
{
case BOTTOM:
case TOP:
x_pos = tick_pos - UInt(0.5 * textbound.width());
break;
case LEFT:
x_pos = w - (tick_size + tick_spacing) - textbound.width();
break;
case RIGHT:
x_pos = tick_size + tick_spacing;
break;
}
UInt y_pos = 0;
switch (alignment)
{
case BOTTOM:
y_pos = tick_size + tick_spacing + UInt(0.5 * textbound.height());
break;
case TOP:
y_pos = h - (tick_size + tick_spacing);
break;
case LEFT:
case RIGHT:
y_pos = tick_pos + margin + UInt(0.25 * textbound.height());
break;
}
painter->drawText(x_pos, y_pos, text);
}
}
// Painting legend
painter->setFont(QFont(painter->font().family(), font_size));
if (show_legend && !legend.empty())
{
// style settings
painter->setPen(QPen(Qt::black));
switch (alignment)
{
case BOTTOM:
painter->drawText(0, 0, w, h, Qt::AlignBottom | Qt::AlignHCenter, legend.c_str());
break;
case TOP:
painter->drawText(0, 0, w, h, Qt::AlignTop | Qt::AlignHCenter, legend.c_str());
break;
case LEFT:
painter->rotate(270);
painter->drawText(-(int)h, 0, h, w, Qt::AlignHCenter | Qt::AlignTop, legend.c_str());
break;
case RIGHT:
painter->rotate(270);
painter->drawText(-(int)h, 0, h, w, Qt::AlignHCenter | Qt::AlignBottom, legend.c_str());
break;
}
}
}
void AxisPainter::getShortenedNumber_(QString& short_num, double number)
{
if (number < 1e3)
{
short_num = QString("%1").arg(number);
}
else if (number < 1e6)
{
short_num = QString("%1k").arg(Math::roundDecimal(number /1e3, -2));
}
else if (number < 1e9)
{
short_num = QString("%1M").arg(number / 1e6);
}
else
{
short_num = QString("%1G").arg(number / 1e9);
}
}
double AxisPainter::scale_(double x, bool is_log)
{ //
return (is_log) ? Math::roundDecimal(pow(10, x), -8) : Math::roundDecimal(x, -8);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASScene.cpp | .cpp | 69,576 | 2,374 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/TOPPASVertex.h>
#include <OpenMS/VISUAL/TOPPASWidget.h>
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/VISUAL/TOPPASMergerVertex.h>
#include <OpenMS/VISUAL/TOPPASResources.h>
#include <OpenMS/VISUAL/TOPPASSplitterVertex.h>
#include <OpenMS/VISUAL/DIALOGS/TOPPASIOMappingDialog.h>
#include <OpenMS/VISUAL/DIALOGS/TOPPASOutputFilesDialog.h>
#include <OpenMS/VISUAL/DIALOGS/TOPPASVertexNameDialog.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <QApplication>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QSet>
#include <QtCore/QTextStream>
#include <QtWidgets/QMessageBox>
#include <map>
#include <OpenMS/VISUAL/TOPPASOutputFolderVertex.h>
namespace OpenMS
{
void FakeProcess::start(const QString& /*program*/, const QStringList& /*arguments*/, OpenMode /*mode = ReadWrite*/)
{
// don't do anything...
//std::cout << "fake process " << program.toStdString() << " called.\n";
emit finished(0, QProcess::NormalExit);
}
TOPPASScene::TOPPASScene(QObject* parent, const QString& tmp_path, bool gui) :
QGraphicsScene(parent),
action_mode_(AM_NEW_EDGE),
vertices_(),
edges_(),
hover_edge_(nullptr),
potential_target_(nullptr),
file_name_(),
tmp_path_(tmp_path),
gui_(gui),
out_dir_(File::getUserDirectory().toQString()),
changed_(false),
running_(false),
error_occured_(false),
user_specified_out_dir_(false),
clipboard_(nullptr),
dry_run_(true),
threads_active_(0),
allowed_threads_(1),
resume_source_(nullptr)
{
/* ATTENTION!
The following line is important! Without it, we get
hard-to-reproduce segmentation faults and
"pure virtual method calls" due to a bug in Qt!
(http://lists.trolltech.com/qt4-preview-feedback/2006-09/thread00124-0.html)
*/
setItemIndexMethod(QGraphicsScene::NoIndex);
}
TOPPASScene::~TOPPASScene()
{
// Delete all items in a controlled way:
for (TOPPASVertex* vertex : vertices_)
{
vertex->blockSignals(true); // do not propagate changes, remove output files, etc..
vertex->setSelected(true);
}
for (TOPPASEdge* edge : edges_)
{
edge->blockSignals(true); // do not propagate changes, remove output files, etc..
edge->setSelected(true);
}
removeSelected();
}
void TOPPASScene::setActionMode(ActionMode mode)
{
action_mode_ = mode;
}
TOPPASScene::ActionMode TOPPASScene::getActionMode()
{
return action_mode_;
}
TOPPASScene::VertexIterator TOPPASScene::verticesBegin()
{
return vertices_.begin();
}
TOPPASScene::VertexIterator TOPPASScene::verticesEnd()
{
return vertices_.end();
}
TOPPASScene::EdgeIterator TOPPASScene::edgesBegin()
{
return edges_.begin();
}
TOPPASScene::EdgeIterator TOPPASScene::edgesEnd()
{
return edges_.end();
}
void TOPPASScene::addVertex(TOPPASVertex* tv)
{
vertices_.push_back(tv);
addItem(tv);
}
void TOPPASScene::addEdge(TOPPASEdge* te)
{
edges_.push_back(te);
addItem(te);
}
void TOPPASScene::itemClicked()
{
}
void TOPPASScene::itemReleased()
{
TOPPASVertex* sender = qobject_cast<TOPPASVertex*>(QObject::sender());
if (!sender)
{
return;
}
// deselect all items except for the one under the cursor, but only if no multiple selection
if (selectedItems().size() <= 1)
{
unselectAll();
sender->setSelected(true);
}
snapToGrid();
}
void TOPPASScene::updateHoveringEdgePos(const QPointF& new_pos)
{
if (!hover_edge_)
{
return;
}
hover_edge_->setHoverPos(new_pos);
TOPPASVertex* target = getVertexAt_(new_pos);
if (target)
{
if (target != potential_target_)
{
potential_target_ = target;
bool ev = isEdgeAllowed_(hover_edge_->getSourceVertex(), target);
if (ev)
{
hover_edge_->setColor(Qt::darkGreen);
}
else
{
hover_edge_->setColor(Qt::red);
}
}
}
else
{
hover_edge_->setColor(Qt::black);
potential_target_ = nullptr;
}
}
void TOPPASScene::addHoveringEdge(const QPointF& pos)
{
TOPPASVertex* sender = qobject_cast<TOPPASVertex*>(QObject::sender());
if (!sender)
{
return;
}
TOPPASEdge* new_edge = new TOPPASEdge(sender, pos);
hover_edge_ = new_edge;
addEdge(new_edge);
}
void TOPPASScene::finishHoveringEdge()
{
TOPPASVertex* target = getVertexAt_(hover_edge_->endPos());
bool remove_edge = false;
if (target && target != hover_edge_->getSourceVertex())
{
hover_edge_->setTargetVertex(target);
TOPPASVertex* source = hover_edge_->getSourceVertex();
// check for parameter copy action (only if source is a tool node (--> edge is purple already, user expects this to happen))
TOPPASToolVertex* tv_source = qobject_cast<TOPPASToolVertex*>(source);
if ((QGuiApplication::keyboardModifiers() & Qt::ControlModifier) && tv_source)
{
TOPPASToolVertex* tv_target = qobject_cast<TOPPASToolVertex*>(target);
if (!(tv_source && tv_target))
{
emit messageReady("Copying parameters is only allowed between Tool nodes! No copy was performed!\n");
}
else
{
emit messageReady("Transferring parameters between nodes ...\n");
Param from = tv_source->getParam();
Param to = tv_target->getParam();
Param to_old = to; // backup, to compare
std::stringstream ss;
Logger::LogStream my_log(new Logger::LogStreamBuf("Transfer", nullptr));
my_log.insert(ss);
to.update(from, false, my_log);
if (to == to_old)
{
my_log << "All parameters are up to date! Nothing happened!\n";
}
else // update the target parameters
{
tv_target->setParam(to);
abortPipeline();
setChanged(true); // to allow "Store" of pipeline
resetDownstream(target);
}
//ss << "test test";
my_log << " ---------------------------------- " << std::endl; // this will cause a flush... removing this line might cause loss(!) of log content!
my_log.flush(); // bug! this sometimes does not cause the content to be flushed to the stringstream; the cache seems to be inactive as well. also std::endl does not help
emit messageReady(String(ss.str()).toQString());
//std::cerr << ss.str();
}
remove_edge = true;
}
else if (isEdgeAllowed_(hover_edge_->getSourceVertex(), target))
{
source->addOutEdge(hover_edge_);
target->addInEdge(hover_edge_);
hover_edge_->setColor(QColor(255, 165, 0));
connectEdgeSignals(hover_edge_);
TOPPASIOMappingDialog dialog(hover_edge_);
if (dialog.firstExec())
{
hover_edge_->emitChanged();
}
else
{
remove_edge = true;
}
}
else
{
remove_edge = true;
}
}
else
{
remove_edge = true;
}
if (remove_edge)
{
edges_.removeAll(hover_edge_);
removeItem(hover_edge_);
delete hover_edge_;
hover_edge_ = nullptr;
}
else
{ // edge was added ...
topoSort();
updateEdgeColors();
}
}
TOPPASVertex* TOPPASScene::getVertexAt_(const QPointF& pos)
{
QList<QGraphicsItem*> target_list = items(pos);
// return first item that is a vertex
TOPPASVertex* target = nullptr;
for (QList<QGraphicsItem*>::iterator it = target_list.begin(); it != target_list.end(); ++it)
{
target = dynamic_cast<TOPPASVertex*>(*it);
if (target)
{
break;
}
}
return target;
}
void TOPPASScene::copySelected()
{
TOPPASScene* tmp_scene = new TOPPASScene(nullptr, this->getTempDir(), false);
std::map<TOPPASVertex*, TOPPASVertex*> vertex_map;
for (TOPPASVertex* v : vertices_)
{
if (!v->isSelected())
{
continue;
}
TOPPASVertex* new_v = v->clone().release();
vertex_map[v] = new_v;
tmp_scene->addVertex(new_v);
}
for (TOPPASEdge* e : edges_)
{
if (!e->isSelected())
{
continue;
}
//check if both source and target node were also selected (otherwise don't copy)
TOPPASVertex* old_source = e->getSourceVertex();
TOPPASVertex* old_target = e->getTargetVertex();
if (vertex_map.find(old_source) == vertex_map.end())
{
continue;
}
TOPPASEdge* new_e = new TOPPASEdge();
TOPPASVertex* new_source = vertex_map[old_source];
TOPPASVertex* new_target = vertex_map[old_target];
new_e->setSourceVertex(new_source);
new_e->setTargetVertex(new_target);
new_e->setSourceOutParam(e->getSourceOutParam());
new_e->setTargetInParam(e->getTargetInParam());
new_source->addOutEdge(new_e);
new_target->addInEdge(new_e);
tmp_scene->addEdge(new_e);
}
emit selectionCopied(tmp_scene);
}
void TOPPASScene::paste(QPointF pos)
{
emit requestClipboardContent();
if (clipboard_ != nullptr)
{
include(clipboard_, pos);
}
}
void TOPPASScene::setClipboard(TOPPASScene* clipboard)
{
clipboard_ = clipboard;
}
void TOPPASScene::removeSelected()
{
QList<TOPPASVertex*> vertices_to_be_removed;
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
if ((*it)->isSelected())
{
// also select all in and out edges (will be deleted below)
for (TOPPASVertex::ConstEdgeIterator e_it = (*it)->inEdgesBegin(); e_it != (*it)->inEdgesEnd(); ++e_it)
{
(*e_it)->setSelected(true);
}
for (TOPPASVertex::ConstEdgeIterator e_it = (*it)->outEdgesBegin(); e_it != (*it)->outEdgesEnd(); ++e_it)
{
(*e_it)->setSelected(true);
}
vertices_to_be_removed.push_back(*it);
}
}
QList<TOPPASEdge*> edges_to_be_removed;
for (EdgeIterator it = edgesBegin(); it != edgesEnd(); ++it)
{
if ((*it)->isSelected())
{
edges_to_be_removed.push_back(*it);
}
}
for (TOPPASEdge* edge : edges_to_be_removed)
{
edges_.removeAll(edge);
removeItem(edge); // remove from scene
delete edge;
}
for (TOPPASVertex* vertex : vertices_to_be_removed)
{
vertices_.removeAll(vertex);
removeItem(vertex); // remove from scene
delete vertex;
}
topoSort();
updateEdgeColors();
setChanged(true);
}
bool TOPPASScene::isEdgeAllowed_(TOPPASVertex* u, TOPPASVertex* v)
{
if (u == nullptr || v == nullptr || u == v ||
// edges leading to input files make no sense:
qobject_cast<TOPPASInputFileListVertex*>(v) ||
// neither do edges coming from output files:
qobject_cast<TOPPASOutputFileListVertex*>(u) ||
// or edges coming from output directories:
qobject_cast<TOPPASOutputFolderVertex*>(u) ||
// nor edges from input/merger/splitter directly to output:
((qobject_cast<TOPPASInputFileListVertex*>(u) || qobject_cast<TOPPASMergerVertex*>(u) || qobject_cast<TOPPASSplitterVertex*>(u))
&& (qobject_cast<TOPPASOutputFileListVertex*>(v) || qobject_cast<TOPPASOutputFolderVertex*>(v)))
||
// nor multiple incoming edges for an output or splitter node:
((qobject_cast<TOPPASOutputFileListVertex*>(v) || qobject_cast<TOPPASOutputFolderVertex*>(v) || qobject_cast<TOPPASSplitterVertex*>(v))
&& (v->inEdgesBegin() != v->inEdgesEnd())))
{
return false;
}
// can't have more incoming edges than a tool has inputs:
TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(v);
if (tv)
{
QVector<TOPPASToolVertex::IOInfo> input_infos = tv->getInputParameters();
if (tv->incomingEdgesCount() >= Size(input_infos.size()))
{
return false;
}
// also, no edges from collectors to tools without input file lists:
// @TODO: what if the input file list is already occupied by an edge?
TOPPASMergerVertex* mv = qobject_cast<TOPPASMergerVertex*>(u);
if (mv && !mv->roundBasedMode())
{
bool any_list = TOPPASToolVertex::IOInfo::isAnyList(input_infos);
if (!any_list)
{
return false;
}
}
}
// no edges to splitters from tools without output file lists:
if (qobject_cast<TOPPASSplitterVertex*>(v))
{
TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(u);
if (tv)
{
QVector<TOPPASToolVertex::IOInfo> output_infos = tv->getOutputParameters();
bool any_list = TOPPASToolVertex::IOInfo::isAnyList(output_infos);
if (!any_list)
{
return false;
}
}
}
// does this edge already exist?
for (TOPPASVertex::ConstEdgeIterator it = u->outEdgesBegin(); it != u->outEdgesEnd(); ++it)
{
if ((*it)->getTargetVertex() == v)
{
return false;
}
}
// insert edge between u and v for testing, is removed afterwards
TOPPASEdge* test_edge = new TOPPASEdge(u, QPointF());
test_edge->setTargetVertex(v);
u->addOutEdge(test_edge);
v->addInEdge(test_edge);
addEdge(test_edge);
bool graph_has_cycles = false;
// find back edges via DFS
for (TOPPASVertex* vertex : vertices_)
{
vertex->setDFSColor(TOPPASVertex::DFS_WHITE);
}
for (TOPPASVertex* vertex : vertices_)
{
if (vertex->getDFSColor() == TOPPASVertex::DFS_WHITE)
{
graph_has_cycles = dfsVisit_(vertex);
if (graph_has_cycles)
{
break;
}
}
}
// remove previously inserted edge
edges_.removeAll(test_edge);
removeItem(test_edge);
delete test_edge;
return !graph_has_cycles;
}
void TOPPASScene::updateEdgeColors()
{
for (TOPPASEdge* edge : edges_)
{
edge->updateColor();
}
update(sceneRect());
}
bool TOPPASScene::dfsVisit_(TOPPASVertex* vertex)
{
vertex->setDFSColor(TOPPASVertex::DFS_GRAY);
for (TOPPASVertex::ConstEdgeIterator it = vertex->outEdgesBegin(); it != vertex->outEdgesEnd(); ++it)
{
TOPPASVertex* target = (*it)->getTargetVertex();
if (target->getDFSColor() == TOPPASVertex::DFS_WHITE)
{
if (dfsVisit_(target))
{
// back edge found
return true;
}
}
else if (target->getDFSColor() == TOPPASVertex::DFS_GRAY)
{
// back edge found
return true;
}
}
vertex->setDFSColor(TOPPASVertex::DFS_BLACK);
return false;
}
void TOPPASScene::resetDownstream(TOPPASVertex* vertex)
{
// reset all nodes
vertex->reset(true);
for (TOPPASVertex::ConstEdgeIterator it = vertex->outEdgesBegin(); it != vertex->outEdgesEnd(); ++it)
{
TOPPASVertex* target = (*it)->getTargetVertex();
this->resetDownstream(target);
}
}
void TOPPASScene::runPipeline()
{
error_occured_ = false;
resume_source_ = nullptr; // we are not resuming, so reset the resume node
// reset all nodes
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
(*it)->reset(true);
}
update(sceneRect());
// check if pipeline OK
if (!sanityCheck_(gui_))
{
if (!gui_)
{
emit pipelineExecutionFailed(); // the user cannot interact. End processing.
}
return;
}
// ask for output directory
if (!askForOutputDir(true))
{
return;
}
std::vector<bool> runs;
runs.push_back(true); // iterate through dry run and normal run
runs.push_back(false);
for (bool dry_run_state : runs)
{
this->dry_run_ = dry_run_state;
setPipelineRunning();
std::cout << "current dry-run state: " << dry_run_state << "\n";
// reset all nodes
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
(*it)->reset(true);
}
update(sceneRect());
// reset logfile
QFile logfile(out_dir_ + QDir::separator() + "TOPPAS.log");
if (logfile.exists())
logfile.remove();
// reset processes
topp_processes_queue_.clear();
// start at input nodes
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
if (error_occured_) break; // someone raised an error
TOPPASInputFileListVertex* iflv = qobject_cast<TOPPASInputFileListVertex*>(*it);
if (iflv)
{
iflv->run();
}
}
}
}
bool TOPPASScene::store(const String& file)
{
Param save_param;
save_param.setValue("info:version", VersionInfo::getVersion());
save_param.setValue("info:num_vertices", vertices_.size());
save_param.setValue("info:num_edges", edges_.size());
save_param.setValue("info:description", String("<![CDATA[") + String(this->description_text_) + String("]]>"));
// lambda function to store common parameters of all vertices
auto save_common_params =
[&save_param](const TOPPASVertex* tv, const String& id, const String& type)
{
save_param.setValue("vertices:" + id + ":toppas_type", type);
save_param.setValue("vertices:" + id + ":x_pos", tv->x());
save_param.setValue("vertices:" + id + ":y_pos", tv->y());
save_param.setValue("vertices:" + id + ":recycle_output", tv->isRecyclingEnabled() ? "true" : "false");
};
// store all vertices (together with all parameters)
for (TOPPASVertex * tv : vertices_)
{
String id(tv->getTopoNr() - 1);
// vertex subclasses
if (auto* iflv = qobject_cast<TOPPASInputFileListVertex*>(tv); iflv)
{
// store file names relative to toppas file
QDir save_dir(File::path(file).toQString());
const QStringList& files_qt = iflv->getFileNames();
std::vector<std::string> files;
for (const QString &file_qt : files_qt)
{
files.push_back(save_dir.relativeFilePath(file_qt).toStdString());
}
save_common_params(iflv, id, "input file list");
save_param.setValue("vertices:" + id + ":file_names", files);
continue;
}
if (auto* oflv = qobject_cast<TOPPASOutputFileListVertex*>(tv); oflv)
{
save_common_params(oflv, id, "output file list");
save_param.setValue("vertices:" + id + ":output_folder_name", oflv->getOutputFolderName().toStdString());
continue;
}
if (auto* ofv = qobject_cast<TOPPASOutputFolderVertex*>(tv); ofv)
{
save_common_params(ofv, id, "output folder");
save_param.setValue("vertices:" + id + ":output_folder_name", ofv->getOutputFolderName().toStdString());
continue;
}
if (auto* ttv = qobject_cast<TOPPASToolVertex*>(tv); ttv)
{
save_common_params(ttv, id, "tool");
save_param.setValue("vertices:" + id + ":tool_name", ttv->getName());
save_param.setValue("vertices:" + id + ":tool_type", ttv->getType());
save_param.insert("vertices:" + id + ":parameters:", ttv->getParam());
continue;
}
if (auto* mv = qobject_cast<TOPPASMergerVertex*>(tv); mv)
{
save_common_params(mv, id, "merger");
save_param.setValue("vertices:" + id + ":round_based", mv->roundBasedMode() ? "true" : "false");
continue;
}
if (auto* sv = qobject_cast<TOPPASSplitterVertex*>(tv); sv)
{
save_common_params(sv, id, "splitter");
continue;
}
}
// store all edges
int counter = 0;
for (TOPPASEdge* te : edges_)
{
if (!((te->getEdgeStatus() == TOPPASEdge::ES_VALID) || (te->getEdgeStatus() == TOPPASEdge::ES_NOT_READY_YET)))
{ // do not allow to store an invalid pipeline, e.g., after a "param refresh()", since this might lead to inconsistencies when storing the edge mapping parameters (segfaults even).
// alternatively, we could discard invalid edges during loading, but then the user looses the information where edges were present (currently they become red)
return false;
}
if (!(te->getSourceVertex() && te->getTargetVertex()))
{
continue;
}
save_param.setValue("edges:" + String(counter) + ":source/target:", String(te->getSourceVertex()->getTopoNr() - 1) + "/" + String(te->getTargetVertex()->getTopoNr() - 1));
//save_param.setValue("edges:"+String(counter)+":source_out_param:", te->getSourceOutParam()));
//save_param.setValue("edges:"+String(counter)+":target_in_param:", te->getTargetInParam()));
String v = "__no_name__";
if (te->getSourceOutParam() >= 0)
{
TOPPASToolVertex* tv_src = qobject_cast<TOPPASToolVertex*>(te->getSourceVertex());
if (tv_src)
{
QVector<TOPPASToolVertex::IOInfo> files = tv_src->getOutputParameters();
//std::cout << "#p: " << files.size() << " . " << te->getSourceOutParam() << "\n";
v = files[te->getSourceOutParam()].param_name;
}
}
save_param.setValue("edges:" + String(counter) + ":source_out_param:", v);
v = "__no_name__";
if (te->getTargetInParam() >= 0)
{
TOPPASToolVertex* tv_src = qobject_cast<TOPPASToolVertex*>(te->getTargetVertex());
if (tv_src)
{
QVector<TOPPASToolVertex::IOInfo> files = tv_src->getInputParameters();
//std::cout << "#p: " << files.size() << " . " << te->getTargetInParam() << "\n";
v = files[te->getTargetInParam()].param_name;
}
}
save_param.setValue("edges:" + String(counter) + ":target_in_param:", v);
++counter;
}
// save file
ParamXMLFile paramFile;
paramFile.store(file, save_param);
setChanged(false);
file_name_ = file;
return true; // success
}
QString TOPPASScene::getDescription() const
{
return description_text_;
}
///
void TOPPASScene::setDescription(const QString& desc)
{
description_text_ = desc;
}
void TOPPASScene::load(const String& file)
{
file_name_ = file;
if (File::empty(file)) // allow opening of 0-byte files as pretend they are empty, new TOPPAS files
{
return;
}
Param load_param;
ParamXMLFile paramFile;
paramFile.load(file, load_param);
// check for TOPPAS file version. Deny loading if too old or too new
// get version of TOPPAS file
String file_version = "1.8.0"; // default (were we did not have the tag)
if (load_param.exists("info:version"))
{
file_version = load_param.getValue("info:version").toString();
}
VersionInfo::VersionDetails v_file = VersionInfo::VersionDetails::create(file_version);
VersionInfo::VersionDetails v_this_low = VersionInfo::VersionDetails::create("1.9.0"); // last compatible TOPPAS file version
VersionInfo::VersionDetails v_this_high = VersionInfo::VersionDetails::create(VersionInfo::getVersion()); // last compatible TOPPAS file version
if (v_file < v_this_low)
{
if (!this->gui_)
{
std::cerr << "The TOPPAS file is too old! Please update the file using TOPPAS or INIUpdater!" << std::endl;
}
else if (this->gui_)
{
if (QMessageBox::warning(nullptr, tr("Old TOPPAS file -- convert and override?"), tr("The TOPPAS file you downloaded was created with an old incompatible version of TOPPAS.\nShall we try to convert the file?! The original file will be overridden, but a backup file will be saved in the same directory.\n"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
// only update in GUI mode, as in non-GUI mode, we'd create infinite recursive calls when instantiating TOPPASScene in INIUpdater
#ifdef OPENMS_WINDOWSPLATFORM
String extra_quotes = "\""; // note: double quoting required for Windows, as outer quotes are required by cmd.exe (arghh)...
#else
String extra_quotes = "";
#endif
String cmd = extra_quotes + "\"" + File::findSiblingTOPPExecutable("INIUpdater") + "\" -in \"" + file + "\" -i " + extra_quotes;
std::cerr << cmd << "\n\n";
if (std::system(cmd.c_str()))
{
QMessageBox::warning(nullptr, tr("INIUpdater failed"), tr("Updating using the INIUpdater tool failed. Please submit a bug report!\n"), QMessageBox::Ok);
return;
}
// reload updated file
ParamXMLFile paramFile;
paramFile.load(file, load_param);
}
}
else if (v_file > v_this_high)
{
if (this->gui_ && QMessageBox::warning(nullptr, tr("TOPPAS file too new"), tr("The TOPPAS file you downloaded was created with a more recent version of TOPPAS. Shall we will try to open it?\nIf this fails, update to the new TOPPAS version.\n"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
}
Param vertices_param = load_param.copy("vertices:", true);
Param edges_param = load_param.copy("edges:", true);
bool pre_1_9_toppas = true;
if (load_param.exists("info:version"))
{
pre_1_9_toppas = false; // using param names instead of indices for connecting edges
}
if (load_param.exists("info:description"))
{
String text = String(load_param.getValue("info:description").toString()).toQString();
text.substitute("<![CDATA[", "");
text.substitute("]]>", "");
description_text_ = text.trim().toQString();
}
String current_type, current_id;
TOPPASVertex* current_vertex = nullptr;
QVector<TOPPASVertex*> vertex_vector;
vertex_vector.resize((Size)(int)load_param.getValue("info:num_vertices"));
// load all vertices
for (Param::ParamIterator it = vertices_param.begin(); it != vertices_param.end(); ++it)
{
StringList substrings;
String(it.getName()).split(':', substrings);
if (substrings.back() == "toppas_type") // next node (all nodes have a "toppas_type")
{
current_vertex = nullptr;
current_type = (it->value).toString();
current_id = substrings[0];
Int index = current_id.toInt();
if (current_type == "input file list")
{
StringList file_names = ListUtils::toStringList<std::string>(vertices_param.getValue(current_id + ":file_names"));
QStringList file_names_qt;
for (StringList::const_iterator str_it = file_names.begin(); str_it != file_names.end(); ++str_it)
{
QString f = str_it->toQString();
if (QDir::isRelativePath(f)) // prepend path of toppas file to relative path of the input files
{
f = File::path(file).toQString() + "/" + f;
}
file_names_qt.push_back(QDir::cleanPath(f));
}
TOPPASInputFileListVertex* iflv = new TOPPASInputFileListVertex(file_names_qt);
current_vertex = iflv;
}
else if (current_type == "output file list")
{
TOPPASOutputFileListVertex* oflv = new TOPPASOutputFileListVertex();
// custom output folder
if (vertices_param.exists(current_id + ":output_folder_name"))
{
oflv->setOutputFolderName(String(vertices_param.getValue(current_id + ":output_folder_name").toString()).toQString());
}
connectOutputVertexSignals(oflv); // todo
current_vertex = oflv;
}
else if (current_type == "output folder")
{
auto* ofv = new TOPPASOutputFolderVertex();
// custom output folder
if (vertices_param.exists(current_id + ":output_folder_name"))
{
ofv->setOutputFolderName(String(vertices_param.getValue(current_id + ":output_folder_name").toString()).toQString());
}
connectOutputVertexSignals(ofv);
current_vertex = ofv;
}
else if (current_type == "tool")
{
String tool_name = vertices_param.getValue(current_id + ":tool_name").toString();
String tool_type = vertices_param.getValue(current_id + ":tool_type").toString();
Param param_param = vertices_param.copy(current_id + ":parameters:", true);
TOPPASToolVertex* tv = new TOPPASToolVertex(tool_name, tool_type);
tv->setParam(param_param);
connectToolVertexSignals(tv);
current_vertex = tv;
}
else if (current_type == "merger")
{
String rb = "true";
if (vertices_param.exists(current_id + ":round_based"))
{
rb = vertices_param.getValue(current_id + ":round_based").toString();
}
TOPPASMergerVertex* mv = new TOPPASMergerVertex(rb == "true");
connectMergerVertexSignals(mv);
current_vertex = mv;
}
else if (current_type == "splitter")
{
TOPPASSplitterVertex* sv = new TOPPASSplitterVertex();
current_vertex = sv;
}
else
{
std::cerr << "Unknown vertex type '" << current_type << "'" << std::endl;
}
if (current_vertex)
{
float x = vertices_param.getValue(current_id + ":x_pos");
float y = vertices_param.getValue(current_id + ":y_pos");
current_vertex->setPos(QPointF(x, y));
// vertex parameters:
if (vertices_param.exists(current_id + ":recycle_output")) // only since TOPPAS 1.9, so does not need to exist
{
String recycle = vertices_param.getValue(current_id + ":recycle_output").toString();
current_vertex->setRecycling(recycle == "true" ? true : false);
}
addVertex(current_vertex);
connectVertexSignals(current_vertex);
// temporarily block signals in order that the first topo sort does not set the changed flag
current_vertex->blockSignals(true);
if (index >= vertex_vector.size())
{
std::cerr << "Unexpected vertex ID!" << std::endl;
}
else
{
if (vertex_vector[index] != 0)
{
std::cerr << "Vertex occupied!" << std::endl;
}
else
{
vertex_vector[index] = current_vertex;
}
}
}
else
{
std::cerr << "Current vertex not available." << std::endl;
}
}
}
// load all edges
for (Param::ParamIterator it = edges_param.begin(); it != edges_param.end(); ++it)
{
const String& edge = (it->value).toString();
StringList edge_substrings;
edge.split('/', edge_substrings);
if (edge_substrings.size() != 2)
{
std::cerr << "Invalid edge format" << std::endl;
break;
}
Int index_1 = edge_substrings[0].toInt();
Int index_2 = edge_substrings[1].toInt();
if (index_1 >= vertex_vector.size() || index_2 >= vertex_vector.size())
{
std::cerr << "Invalid vertex index" << std::endl;
}
else
{
TOPPASVertex* tv_1 = vertex_vector[index_1];
TOPPASVertex* tv_2 = vertex_vector[index_2];
// future TOPPAS files may contain new nodes, which may leave `vertex_vector[i]` empty
if (tv_1 == nullptr || tv_2 == nullptr)
{
std::cerr << "Invalid edge" << std::endl;
continue;
}
TOPPASEdge* edge = new TOPPASEdge();
edge->setSourceVertex(tv_1);
edge->setTargetVertex(tv_2);
tv_1->addOutEdge(edge);
tv_2->addInEdge(edge);
connectEdgeSignals(edge);
addEdge(edge);
String source_out_param = (++it)->value.toString();
String target_in_param = (++it)->value.toString();
if (pre_1_9_toppas) // just indices stored - no way we can check
{
edge->setSourceOutParam(source_out_param.toInt());
edge->setTargetInParam(target_in_param.toInt());
}
else
{
Int src_index = -1;
Int tgt_index = -1;
TOPPASToolVertex* tv_src = qobject_cast<TOPPASToolVertex*>(tv_1);
if (source_out_param != "__no_name__" && tv_src)
{
QVector<TOPPASToolVertex::IOInfo> files = tv_src->getOutputParameters();
// search for the name
for (int i = 0; i < files.size(); ++i)
{
if (files[i].param_name == source_out_param)
{
src_index = i;
break;
}
}
if (src_index == -1)
logTOPPOutput(String("Could not find output parameter called '" + source_out_param + "'. Check edge!").toQString());
}
tv_src = qobject_cast<TOPPASToolVertex*>(tv_2);
if (target_in_param != "__no_name__" && tv_src)
{
QVector<TOPPASToolVertex::IOInfo> files = tv_src->getInputParameters();
// search for the name
for (int i = 0; i < files.size(); ++i)
{
if (files[i].param_name == target_in_param)
{
tgt_index = i;
break;
}
}
if (tgt_index == -1)
logTOPPOutput(String("Could not find input parameter called '" + target_in_param + "'. Check edge!").toQString());
}
edge->setSourceOutParam(src_index);
edge->setTargetInParam(tgt_index);
}
}
}
if (pre_1_9_toppas) // just indices stored - no way we can check
{
logTOPPOutput(String("Your TOPPAS file was build with an old version of TOPPAS and is susceptible to errors when used with new versions of OpenMS. Check every edge for correct input/output parameter names and store the workflow using the current version of TOPPAS (e.g using the \"Save as ...\" functionality) to make the workflow more robust to changes in future versions of TOPP tools!").toQString());
}
/*
if (!views().empty())
{
TOPPASWidget* tw = qobject_cast<TOPPASWidget*>(views().first());
if (tw)
{
QRectF scene_rect = itemsBoundingRect();
tw->fitInView(scene_rect, Qt::KeepAspectRatio);
tw->scale(0.75, 0.75);
setSceneRect(tw->mapToScene(tw->rect()).boundingRect());
}
}
*/
topoSort();
// unblock signals again
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
(*it)->blockSignals(false);
}
updateEdgeColors();
}
void TOPPASScene::include(TOPPASScene* tmp_scene, QPointF pos)
{
qreal x_offset, y_offset;
if (pos == QPointF()) // pasted via Ctrl-V (no mouse position given)
{
x_offset = 30.0; // move just a tad (in relation to old content)
y_offset = 30.0;
}
else
{
QRectF new_bounding_rect = tmp_scene->itemsBoundingRect();
x_offset = pos.x() - new_bounding_rect.left();
y_offset = pos.y() - new_bounding_rect.top();
}
std::map<TOPPASVertex*, TOPPASVertex*> vertex_map;
for (VertexIterator it = tmp_scene->verticesBegin(); it != tmp_scene->verticesEnd(); ++it)
{
TOPPASVertex* v = *it;
TOPPASVertex* new_v = nullptr;
TOPPASInputFileListVertex* iflv = qobject_cast<TOPPASInputFileListVertex*>(v);
if (iflv)
{
TOPPASInputFileListVertex* new_iflv = new TOPPASInputFileListVertex(*iflv);
new_v = new_iflv;
}
TOPPASOutputFileListVertex* oflv = qobject_cast<TOPPASOutputFileListVertex*>(v);
if (oflv)
{
TOPPASOutputFileListVertex* new_oflv = new TOPPASOutputFileListVertex(*oflv);
new_v = new_oflv;
connectOutputVertexSignals(new_oflv);
}
TOPPASOutputFolderVertex* ofv = qobject_cast<TOPPASOutputFolderVertex*>(v);
if (ofv)
{
TOPPASOutputFolderVertex* new_ofv = new TOPPASOutputFolderVertex(*ofv);
new_v = new_ofv;
connectOutputVertexSignals(new_ofv);
}
TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(v);
if (tv)
{
TOPPASToolVertex* new_tv = new TOPPASToolVertex(*tv);
new_v = new_tv;
connectToolVertexSignals(new_tv);
}
TOPPASMergerVertex* mv = qobject_cast<TOPPASMergerVertex*>(v);
if (mv)
{
TOPPASMergerVertex* new_mv = new TOPPASMergerVertex(*mv);
new_v = new_mv;
connectMergerVertexSignals(new_mv);
}
TOPPASSplitterVertex* sv = qobject_cast<TOPPASSplitterVertex*>(v);
if (sv)
{
TOPPASSplitterVertex* new_sv = new TOPPASSplitterVertex(*sv);
new_v = new_sv;
}
if (!new_v)
{
std::cerr << "Unknown vertex type! Aborting." << std::endl;
return;
}
vertex_map[v] = new_v;
new_v->moveBy(x_offset, y_offset);
connectVertexSignals(new_v);
addVertex(new_v);
// temporarily block signals in order that the first topo sort does not set the changed flag
new_v->blockSignals(true);
}
// add all edges (are not copied by copy constructors of vertices)
for (EdgeIterator it = tmp_scene->edgesBegin(); it != tmp_scene->edgesEnd(); ++it)
{
TOPPASVertex* old_source = (*it)->getSourceVertex();
TOPPASVertex* old_target = (*it)->getTargetVertex();
TOPPASVertex* new_source = vertex_map[old_source];
TOPPASVertex* new_target = vertex_map[old_target];
TOPPASEdge* new_e = new TOPPASEdge();
new_e->setSourceVertex(new_source);
new_e->setTargetVertex(new_target);
new_e->setSourceOutParam((*it)->getSourceOutParam());
new_e->setTargetInParam((*it)->getTargetInParam());
new_source->addOutEdge(new_e);
new_target->addInEdge(new_e);
connectEdgeSignals(new_e);
addEdge(new_e);
}
// select new items (so the user can move them); edges do not need to be selected, only vertices
unselectAll();
for (std::map<TOPPASVertex*, TOPPASVertex*>::iterator it = vertex_map.begin(); it != vertex_map.end(); ++it)
{
it->second->setSelected(true);
}
topoSort();
// unblock signals again
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
(*it)->blockSignals(false);
}
updateEdgeColors();
}
const String& TOPPASScene::getSaveFileName()
{
return file_name_;
}
void TOPPASScene::setSaveFileName(const String& name)
{
file_name_ = name;
}
void TOPPASScene::unselectAll()
{
const QList<QGraphicsItem*>& all_items = items();
for (QGraphicsItem * item : all_items)
{
item->setSelected(false);
}
update(sceneRect());
}
void TOPPASScene::checkIfWeAreDone()
{
if (dry_run_)
return;
if (resume_source_)
{
switch (resume_source_->getSubtreeStatus())
{
case TOPPASVertex::TV_UNFINISHED:
return; // still processing
break;
case TOPPASVertex::TV_ALLFINISHED:
break; // ok, go to bottom
case TOPPASVertex::TV_UNFINISHED_INBRANCH:
setPipelineRunning(false);
emit pipelineErrorSlot(-1, "Resume cannot continue due to missing subtree.");
break;
}
}
else
{
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it) // check if all nodes are done
{
if (!(*it)->isFinished())
{
return;
}
}
}
setPipelineRunning(false);
emit entirePipelineFinished();
}
void TOPPASScene::pipelineErrorSlot(int return_code, const QString& msg)
{
logTOPPOutput(msg); // print to log window or console
error_occured_ = true;
setPipelineRunning(false);
abortPipeline();
emit pipelineExecutionFailed(return_code);
}
void TOPPASScene::writeToLogFile_(const QString& text)
{
QFile logfile(out_dir_ + QDir::separator() + "TOPPAS.log");
if (!logfile.open(QIODevice::Append | QIODevice::Text))
{
std::cerr << "Could not write to logfile '" << String(logfile.fileName()) << "'" << std::endl;
return;
}
QTextStream ts(&logfile);
ts << "\n" << text << "\n";
logfile.close();
}
void TOPPASScene::logTOPPOutput(const QString& out)
{
TOPPASToolVertex* sender = qobject_cast<TOPPASToolVertex*>(QObject::sender());
if (!sender)
{
//return;
}
String text = String(out);
if (!gui_)
{
std::cout << std::endl << text << std::endl;
}
emit messageReady(out); // let TOPPAS know about it
writeToLogFile_(text.toQString());
}
void TOPPASScene::logToolStarted()
{
TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(QObject::sender());
if (tv)
{
String text = tv->getName();
String type = tv->getType();
if (!type.empty())
{
text += " (" + type + ")";
}
text += " started. Processing ...";
if (!gui_)
{
std::cout << '\n' << text << std::endl;
}
writeToLogFile_(text.toQString());
}
}
void TOPPASScene::logToolFinished()
{
TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(QObject::sender());
if (tv)
{
String text = tv->getName();
String type = tv->getType();
if (!type.empty())
{
text += " (" + type + ")";
}
text += " finished!";
if (!gui_)
{
std::cout << '\n' << text << std::endl;
}
writeToLogFile_(text.toQString());
}
}
void TOPPASScene::logToolFailed()
{
TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(QObject::sender());
if (tv)
{
String text = tv->getName();
String type = tv->getType();
if (!type.empty())
{
text += " (" + type + ")";
}
text += " failed!";
if (!gui_)
{
std::cout << '\n' << text << std::endl;
}
writeToLogFile_(text.toQString());
}
}
void TOPPASScene::logToolCrashed()
{
TOPPASToolVertex* tv = qobject_cast<TOPPASToolVertex*>(QObject::sender());
if (tv)
{
String text = tv->getName();
String type = tv->getType();
if (!type.empty())
{
text += " (" + type + ")";
}
text += " crashed!";
if (!gui_)
{
std::cout << '\n' << text << std::endl;
}
writeToLogFile_(text.toQString());
}
}
void TOPPASScene::logOutputFileWritten(const String& file)
{
String text = "Output file '" + file + "' written.";
if (!gui_)
{
std::cout << std::endl << text << std::endl;
}
writeToLogFile_(text.toQString());
}
void TOPPASScene::topoSort(bool resort_all)
{
UInt topo_counter {1};
for (TOPPASVertex* tv : vertices_)
{
if (resort_all)
{
tv->setTopoSortMarked(false);
}
else if (tv->isTopoSortMarked())
{
++topo_counter; // count number of existing/sorted vertices to get correct offset for new vertices
}
}
while (true)
{
bool some_vertex_not_finished = false;
for (TOPPASVertex* tv : vertices_)
{
if (tv->isTopoSortMarked())
{
continue;
}
bool has_unmarked_predecessors = false;
for (TOPPASVertex::ConstEdgeIterator e_it = tv->inEdgesBegin(); e_it != tv->inEdgesEnd(); ++e_it)
{
TOPPASVertex* v = (*e_it)->getSourceVertex();
if (!(v->isTopoSortMarked()))
{
has_unmarked_predecessors = true;
break;
}
}
if (has_unmarked_predecessors)
{ // needs to be revisited in the next round (where we hopefully have found the predecessors)
some_vertex_not_finished = true;
}
else
{ // mark this node
// update name of input node
TOPPASInputFileListVertex* iflv = qobject_cast<TOPPASInputFileListVertex*>(tv);
if (iflv)
{
//check if key was modified by user. if yes, don't update it
QString old_topo_nr = QString::number(tv->getTopoNr());
if (old_topo_nr == iflv->getKey() || iflv->getKey() == "")
{
iflv->setKey(QString::number(topo_counter));
}
}
tv->setTopoNr(topo_counter);
tv->setTopoSortMarked(true);
++topo_counter;
}
}
if (!some_vertex_not_finished)
{
break; // all sorted
}
}
// sort vertices in list by their TopoNr, so that they keep their numbering when deleting edges
std::sort(vertices_.begin(), vertices_.end(), [](TOPPASVertex* a, TOPPASVertex* b) { return a->getTopoNr() < b->getTopoNr();});
update(sceneRect());
}
const QString& TOPPASScene::getOutDir() const
{
return out_dir_;
}
const QString& TOPPASScene::getTempDir() const
{
return tmp_path_;
}
void TOPPASScene::setOutDir(const QString& dir)
{
QDir d(dir);
out_dir_ = d.absolutePath();
user_specified_out_dir_ = true;
}
void TOPPASScene::moveSelectedItems(qreal dx, qreal dy)
{
setActionMode(AM_MOVE);
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
if (!(*it)->isSelected())
{
continue;
}
for (TOPPASVertex::ConstEdgeIterator e_it = (*it)->inEdgesBegin(); e_it != (*it)->inEdgesEnd(); ++e_it)
{
(*e_it)->prepareResize();
}
for (TOPPASVertex::ConstEdgeIterator e_it = (*it)->outEdgesBegin(); e_it != (*it)->outEdgesEnd(); ++e_it)
{
(*e_it)->prepareResize();
}
(*it)->moveBy(dx, dy);
}
setChanged(true);
}
void TOPPASScene::snapToGrid()
{
int grid_step = 20;
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
//only make selected nodes snap (those might have been moved)
if (!(*it)->isSelected())
{
continue;
}
int x_int = (int)((*it)->x());
int y_int = (int)((*it)->y());
int prev_grid_x = x_int - (x_int % grid_step);
int prev_grid_y = y_int - (y_int % grid_step);
int new_x = prev_grid_x;
int new_y = prev_grid_y;
if (x_int - prev_grid_x > (grid_step / 2))
{
new_x += grid_step;
}
if (y_int - prev_grid_y > (grid_step / 2))
{
new_y += grid_step;
}
(*it)->setPos(QPointF(new_x, new_y));
}
update(sceneRect());
}
bool TOPPASScene::saveIfChanged()
{
// Save changes
if (gui_ && changed_)
{
QString name = file_name_.empty() ? "Untitled" : File::basename(file_name_).toQString();
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(views().first(), "Save changes?", "'" + name + "' has been modified.\n\nDo you want to save your changes?", QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
if (ret == QMessageBox::Save)
{
emit saveMe();
if (changed_)
{
//user has not saved the file (aborted save dialog)
return false;
}
}
else if (ret == QMessageBox::Cancel)
{
return false;
}
}
return true;
}
void TOPPASScene::setChanged(bool b)
{
if (changed_ != b)
{
changed_ = b;
emit mainWindowNeedsUpdate();
}
}
bool TOPPASScene::wasChanged() const
{
return changed_;
}
bool TOPPASScene::isPipelineRunning() const
{
return running_;
}
void TOPPASScene::abortPipeline()
{
emit terminateCurrentPipeline();
resetProcessesQueue();
setPipelineRunning(false);
}
void TOPPASScene::resetProcessesQueue()
{
topp_processes_queue_.clear();
}
void TOPPASScene::setPipelineRunning(bool b)
{
running_ = b;
if (!running_) // whenever we stop the pipeline and user is not looking, the icon should flash
{
resume_source_ = nullptr;
QApplication::alert(nullptr); // flash Taskbar || Dock
}
}
void TOPPASScene::processFinished()
{
--threads_active_;
// try to run next in line
runNextProcess();
}
bool TOPPASScene::askForOutputDir(bool always_ask)
{
if (gui_)
{
if (always_ask || !user_specified_out_dir_)
{
TOPPASOutputFilesDialog tofd(out_dir_, allowed_threads_);
if (tofd.exec())
{
setOutDir(tofd.getDirectory());
setAllowedThreads(tofd.getNumJobs());
}
else
{
return false;
}
}
}
return true;
}
void TOPPASScene::contextMenuEvent(QGraphicsSceneContextMenuEvent* event)
{
QPointF scene_pos = event->scenePos();
QGraphicsItem* clicked_item = itemAt(scene_pos, QTransform());
QMenu menu;
if (clicked_item == nullptr)
{
QAction* new_action = menu.addAction("Paste");
emit requestClipboardContent();
if (clipboard_ == nullptr)
{
new_action->setEnabled(false);
}
}
else
{
if (!clicked_item->isSelected())
{
unselectAll();
}
clicked_item->setSelected(true);
// check which kinds of items are selected and display a context menu containing only actions compatible with all of them
bool found_tool = false;
bool found_input = false;
bool found_output = false, found_output_files = false;
bool found_merger = false;
bool found_splitter = false;
bool found_edge = false;
bool disable_resume = this->isPipelineRunning();
//bool disable_toppview = true;
for (TOPPASEdge* edge : edges_)
{
if (edge->isSelected())
{
found_edge = true;
break;
}
}
for (TOPPASVertex* tv : vertices_)
{
if (!tv->isSelected())
{
continue;
}
if (qobject_cast<TOPPASToolVertex*>(tv))
{
found_tool = true;
// all predecessor nodes finished successfully? if not, disable resuming
for (ConstEdgeIterator it = tv->inEdgesBegin(); it != tv->inEdgesEnd(); ++it)
{
TOPPASToolVertex* pred_ttv = qobject_cast<TOPPASToolVertex*>((*it)->getSourceVertex());
if (pred_ttv && (pred_ttv->getStatus() != TOPPASToolVertex::TOOL_SUCCESS))
{
disable_resume = true;
break;
}
}
continue;
}
if (qobject_cast<TOPPASInputFileListVertex*>(tv))
{
found_input = true;
continue;
}
if (qobject_cast<TOPPASOutputVertex*>(tv))
{
found_output = true;
// no continue here; derived classes below
}
if (qobject_cast<TOPPASOutputFileListVertex*>(tv))
{
found_output_files = true;
continue;
}
if (qobject_cast<TOPPASMergerVertex*>(tv))
{
found_merger = true;
continue;
}
if (qobject_cast<TOPPASSplitterVertex*>(tv))
{
found_splitter = true;
continue;
}
}
QSet<QString> action;
if (found_tool)
{
action.insert("Edit parameters");
action.insert("Resume");
action.insert("Open files in TOPPView");
action.insert("Open containing folder");
//action.insert("Toggle breakpoint");
}
if (found_input)
{
action.insert("Change name");
action.insert("Change files");
action.insert("Open files in TOPPView");
action.insert("Open containing folder");
}
if (found_output)
{
action.insert("Set output folder name");
action.insert("Open containing folder");
}
if (found_output_files)
{
action.insert("Open files in TOPPView");
}
if (found_edge)
{
action.insert("Edit I/O mapping");
}
if (found_input || found_tool || found_merger || found_splitter)
{
action.insert("Toggle recycling mode");
}
QList<QSet<QString> > all_actions;
all_actions.push_back(action);
QSet<QString> supported_actions_set = all_actions.first();
for (const QSet<QString>&action_set : all_actions)
{
supported_actions_set.intersect(action_set);
}
QList<QString> supported_actions = supported_actions_set.values();
supported_actions << "Copy" << "Cut" << "Remove";
for (const QString &supported_action : supported_actions)
{
QAction* new_action = menu.addAction(supported_action);
if (supported_action == "Resume" && disable_resume)
{
new_action->setEnabled(false);
}
}
}
// ------ execute action ------
QAction* selected_action = menu.exec(event->screenPos());
if (selected_action)
{
QString text = selected_action->text();
if (text == "Remove")
{
removeSelected();
event->accept();
return;
}
if (text == "Copy")
{
copySelected();
event->accept();
return;
}
if (text == "Cut")
{
copySelected();
removeSelected();
event->accept();
return;
}
if (text == "Paste")
{
paste(event->scenePos());
event->accept();
return;
}
for (QGraphicsItem* gi : selectedItems())
{
if (text == "Toggle recycling mode")
{
if (auto* tv = dynamic_cast<TOPPASVertex*>(gi); tv)
{
tv->invertRecylingMode();
tv->update(tv->boundingRect());
}
continue;
}
if (auto* edge = dynamic_cast<TOPPASEdge*>(gi); edge)
{
if (text == "Edit I/O mapping")
{
edge->showIOMappingDialog();
}
continue;
}
if (auto* ttv = dynamic_cast<TOPPASToolVertex*>(gi); ttv)
{
if (text == "Edit parameters")
{
ttv->editParam();
}
else if (text == "Resume")
{
if (askForOutputDir(false))
{
setPipelineRunning();
resume_source_ = ttv;
resetDownstream(ttv);
ttv->run();
}
}
else if (text == "Toggle breakpoint")
{
ttv->toggleBreakpoint();
ttv->update(ttv->boundingRect());
}
else if (text == "Open files in TOPPView")
{
QStringList all_out_files = ttv->getFileNames();
emit openInTOPPView(all_out_files);
}
else if (text == "Open containing folder")
{
ttv->openContainingFolder();
}
continue;
}
if (auto* ifv = dynamic_cast<TOPPASInputFileListVertex*>(gi); ifv)
{
if (text == "Open files in TOPPView")
{
QStringList in_files = ifv->getFileNames();
emit openInTOPPView(in_files);
}
else if (text == "Open containing folder")
{
ifv->openContainingFolder();
}
else if (text == "Change files")
{
ifv->showFilesDialog();
}
else if (text == "Change name")
{
TOPPASVertexNameDialog dlg(ifv->getKey());
if (dlg.exec())
{
ifv->setKey(dlg.getName());
}
}
continue;
}
if (auto* ov = dynamic_cast<TOPPASOutputVertex*>(gi); ov)
{
if (text == "Open containing folder")
{
ov->openContainingFolder();
}
else if (text == "Set output folder name")
{
TOPPASVertexNameDialog dlg(ov->getOutputFolderName(), "[a-zA-Z0-9_-]*");
if (dlg.exec())
{ ov->setOutputFolderName(dlg.getName());
}
}
// no continue - derived classes below
}
if (auto* ofv = dynamic_cast<TOPPASOutputFileListVertex*>(gi); ofv)
{
if (text == "Open files in TOPPView")
{
QStringList out_files = ofv->getFileNames();
emit openInTOPPView(out_files);
}
continue;
}
}
}
event->accept();
}
void TOPPASScene::enqueueProcess(const TOPPProcess& process)
{
topp_processes_queue_ << process;
}
void TOPPASScene::runNextProcess()
{
static bool used = false;
if (used)
return;
used = true;
while (!topp_processes_queue_.empty() && threads_active_ < allowed_threads_)
{
++threads_active_; // will be decreased, once the tool finishes
TOPPProcess tp = topp_processes_queue_.first();
topp_processes_queue_.pop_front();
FakeProcess* p = qobject_cast<FakeProcess*>(tp.proc);
if (p)
{
p->start(tp.command, tp.args);
}
else
{
tp.tv->emitToolStarted();
tp.proc->start(tp.command, tp.args);
}
}
used = false;
checkIfWeAreDone();
}
bool TOPPASScene::sanityCheck_(bool allowUserOverride)
{
QStringList strange_vertices;
// ----- are there any input nodes and are files specified? ----
/// check if we have any input nodes
QVector<TOPPASInputFileListVertex*> input_nodes;
for (TOPPASVertex* tv : vertices_)
{
TOPPASInputFileListVertex* iflv = qobject_cast<TOPPASInputFileListVertex*>(tv);
if (iflv)
{
input_nodes.push_back(iflv);
}
}
if (input_nodes.empty())
{
if (allowUserOverride)
{
QMessageBox::warning(nullptr, "No input files", "The pipeline does not contain any input file nodes!");
}
else
{
std::cerr << "The pipeline does not contain any input file nodes!" << std::endl;
}
return false;
}
/// warn about empty input nodes
for (TOPPASInputFileListVertex* iflv : input_nodes)
{
if ((iflv->outgoingEdgesCount() > 0) && (iflv->getFileNames().empty())) // allow disconnected input node with empty file list
{
strange_vertices.push_back(QString::number(iflv->getTopoNr()));
}
}
if (!strange_vertices.empty())
{
if (allowUserOverride)
{
QMessageBox::warning(views().first(), "Empty input file nodes",
QString("Node")
+ (strange_vertices.size() > 1 ? "s " : " ")
+ strange_vertices.join(", ")
+ (strange_vertices.size() > 1 ? " have " : " has ")
+ " an empty input file list!");
}
else
{
std::cerr << "Pipeline contains input file nodes without specified files!" << std::endl;
}
return false;
}
/// check if input files exist
strange_vertices.clear();
for (TOPPASInputFileListVertex* iflv : input_nodes)
{
if ((iflv->outgoingEdgesCount() > 0) && (!iflv->fileNamesValid())) // allow disconnected input node with invalid files
{
strange_vertices.push_back(QString::number(iflv->getTopoNr()));
}
}
if (!strange_vertices.empty())
{
if (allowUserOverride)
{
QMessageBox::warning(views().first(), "Input file names wrong",
QString("Node")
+ (strange_vertices.size() > 1 ? "s " : " ")
+ strange_vertices.join(", ")
+ (strange_vertices.size() > 1 ? " have " : " has ")
+ " invalid (non-existing or duplicate) input files!");
}
else
{
std::cerr << "Pipeline contains input file nodes with invalid (non-existing or duplicate) input files!" << std::endl;
}
return false;
}
// ----- are there nodes without parents (besides input nodes)? -----
strange_vertices.clear();
for (TOPPASVertex* tv : vertices_)
{
if (qobject_cast<TOPPASInputFileListVertex*>(tv)) // input nodes don't need a parent
{
continue;
}
if (tv->inEdgesBegin() == tv->inEdgesEnd())
{
strange_vertices << QString::number(tv->getTopoNr());
tv->markUnreachable();
}
}
if (!strange_vertices.empty())
{
if (allowUserOverride)
{
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(views().first(), "Nodes without incoming edges", QString("Node") + (strange_vertices.size() > 1 ? "s " : " ") + strange_vertices.join(", ") + " will never be reached.\n\nDo you still want to run the pipeline?", QMessageBox::Yes | QMessageBox::No);
if (ret == QMessageBox::No)
{
return false;
}
}
//else
//{
// assume the pipeline was tested in the gui, continue
//}
}
// ----- are there nodes without children (besides output nodes)? -----
strange_vertices.clear();
for (TOPPASVertex* tv : vertices_)
{
if (qobject_cast<TOPPASOutputVertex*>(tv))
{
continue;
}
if (tv->outEdgesBegin() == tv->outEdgesEnd())
{
strange_vertices << QString::number(tv->getTopoNr());
}
}
if (!strange_vertices.empty())
{
if (allowUserOverride)
{
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(views().first(), "Nodes without outgoing edges", QString("Node") +
(strange_vertices.size() > 1 ? "s " : " ") + strange_vertices.join(", ") +
(strange_vertices.size() > 1 ? " have " : " has ") +
"no outgoing edges.\n\nDo you still want to run the pipeline?", QMessageBox::Yes | QMessageBox::No);
if (ret == QMessageBox::No)
{
return false;
}
}
//else
//{
// assume the pipeline was tested in the gui, continue
//}
}
// check edges
bool edges_ok = true;
for (TOPPASEdge* edge : edges_)
{
if (edge->getEdgeStatus() != TOPPASEdge::ES_VALID)
{
edges_ok = false;
break;
}
}
if (!edges_ok)
{
if (allowUserOverride)
{
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(views().first(), "Invalid edges detected", "Invalid edges detected. Do you still want to run the pipeline?",
QMessageBox::Yes | QMessageBox::No);
if (ret == QMessageBox::No)
{
return false;
}
}
else
{ // do not allow silent execution with invalid edges
return false;
}
}
return true;
}
void TOPPASScene::connectVertexSignals(TOPPASVertex* tv)
{
connect(tv, SIGNAL(clicked()), this, SLOT(itemClicked()));
connect(tv, SIGNAL(released()), this, SLOT(itemReleased()));
connect(tv, SIGNAL(hoveringEdgePosChanged(const QPointF &)), this, SLOT(updateHoveringEdgePos(const QPointF &)));
connect(tv, SIGNAL(newHoveringEdge(const QPointF &)), this, SLOT(addHoveringEdge(const QPointF &)));
connect(tv, SIGNAL(finishHoveringEdge()), this, SLOT(finishHoveringEdge()));
connect(tv, SIGNAL(itemDragged(qreal, qreal)), this, SLOT(moveSelectedItems(qreal, qreal)));
connect(tv, SIGNAL(parameterChanged(const bool)), this, SLOT(changedParameter(const bool)));
}
void TOPPASScene::connectToolVertexSignals(TOPPASToolVertex* ttv)
{
connect(ttv, &TOPPASToolVertex::toppOutputReady, this, &TOPPASScene::logTOPPOutput);
connect(ttv, &TOPPASToolVertex::toolStarted, this, &TOPPASScene::logToolStarted);
connect(ttv, &TOPPASToolVertex::toolFinished, this, &TOPPASScene::logToolFinished);
connect(ttv, &TOPPASToolVertex::toolFailed, this, &TOPPASScene::logToolFailed);
connect(ttv, &TOPPASToolVertex::toolCrashed, this, &TOPPASScene::logToolCrashed);
connect(ttv, &TOPPASToolVertex::toolFailed, this, &TOPPASScene::pipelineErrorSlot);
connect(ttv, &TOPPASToolVertex::toolCrashed, [&]() { this->pipelineErrorSlot(); });
connect(ttv, &TOPPASToolVertex::somethingHasChanged, this, &TOPPASScene::abortPipeline);
}
void TOPPASScene::connectMergerVertexSignals(TOPPASMergerVertex* tmv)
{
connect(tmv, SIGNAL(mergeFailed(QString)), this, SLOT(pipelineErrorSlot(QString)));
connect(tmv, SIGNAL(somethingHasChanged()), this, SLOT(abortPipeline()));
}
void TOPPASScene::connectOutputVertexSignals(TOPPASOutputVertex* oflv)
{
connect(oflv, SIGNAL(outputFileWritten(const String &)), this, SLOT(logOutputFileWritten(const String&)));
connect(oflv, SIGNAL(outputFolderNameChanged()), this, SLOT(changedOutputFolder()));
}
void TOPPASScene::connectEdgeSignals(TOPPASEdge* e)
{
TOPPASVertex* source = e->getSourceVertex();
TOPPASVertex* target = e->getTargetVertex();
connect(e, SIGNAL(somethingHasChanged()), source, SLOT(outEdgeHasChanged()));
connect(e, SIGNAL(somethingHasChanged()), target, SLOT(inEdgeHasChanged()));
connect(e, SIGNAL(somethingHasChanged()), this, SLOT(abortPipeline()));
}
void TOPPASScene::changedOutputFolder()
{
abortPipeline();
setChanged(true); // to allow "Store" of pipeline
}
void TOPPASScene::changedParameter(const bool invalidates_running_pipeline)
{
if (invalidates_running_pipeline) // abort only if TTV's new parameters invalidate the results
{
abortPipeline();
}
setChanged(true); // to allow "Store" of pipeline
resetDownstream(dynamic_cast<TOPPASVertex*>(sender()));
}
void TOPPASScene::loadResources(const TOPPASResources& resources)
{
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
TOPPASInputFileListVertex* iflv = qobject_cast<TOPPASInputFileListVertex*>(*it);
if (iflv)
{
const QString& key = iflv->getKey();
const QList<TOPPASResource>& resource_list = resources.get(key);
QStringList files;
for (const TOPPASResource& res : resource_list)
{
files << res.getLocalFile();
}
iflv->setFilenames(files);
}
}
}
void TOPPASScene::createResources(TOPPASResources& resources)
{
resources.clear();
QStringList used_keys;
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
TOPPASInputFileListVertex* iflv = qobject_cast<TOPPASInputFileListVertex*>(*it);
if (iflv)
{
QString key = iflv->getKey();
if (used_keys.contains(key))
{
if (gui_)
{
QMessageBox::warning(nullptr, "Non-unique input node names", "Some of the input nodes have the same names. Cannot create resource file.");
}
else
{
std::cerr << "Some of the input nodes have the same names. Cannot create resource file." << std::endl;
}
return;
}
used_keys << key;
QList<TOPPASResource> resource_list;
QStringList files = iflv->getFileNames();
for (const QString& file : files)
{
resource_list << TOPPASResource(file);
}
resources.add(key, resource_list);
}
}
}
TOPPASScene::RefreshStatus TOPPASScene::refreshParameters()
{
bool sane_before = sanityCheck_(false);
bool change = false;
for (VertexIterator it = verticesBegin(); it != verticesEnd(); ++it)
{
TOPPASToolVertex* ttv = qobject_cast<TOPPASToolVertex*>(*it);
if (ttv && ttv->refreshParameters())
{
change = true;
}
}
TOPPASScene::RefreshStatus result;
if (!change)
{
result = ST_REFRESH_NOCHANGE;
}
else if (!sanityCheck_(false))
{
if (sane_before)
{
result = ST_REFRESH_CHANGEINVALID;
}
else
{
result = ST_REFRESH_REMAINSINVALID;
}
}
else result = ST_REFRESH_CHANGED;
return result;
}
void TOPPASScene::setAllowedThreads(int num_jobs)
{
if (num_jobs < 1)
{
return;
}
allowed_threads_ = num_jobs;
}
bool TOPPASScene::isGUIMode() const
{
return gui_;
}
bool TOPPASScene::isDryRun() const
{
return dry_run_;
}
void TOPPASScene::quitWithError(int exit_code)
{
exit(exit_code);
}
TOPPASEdge* TOPPASScene::getHoveringEdge()
{
return hover_edge_;
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/TOPPASOutputFolderVertex.cpp | .cpp | 8,634 | 212 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/TOPPASOutputFolderVertex.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/TOPPASEdge.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <QtCore>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtWidgets/QMessageBox>
#include <QCoreApplication>
#include <future>
namespace OpenMS
{
std::unique_ptr<TOPPASVertex> TOPPASOutputFolderVertex::clone() const
{
return std::make_unique<TOPPASOutputFolderVertex>(*this);
}
String TOPPASOutputFolderVertex::getName() const
{
return "OutputFolderVertex";
}
void TOPPASOutputFolderVertex::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
TOPPASVertex::paint(painter, option, widget);
QString text = "output folder";
QRectF text_boundings = painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, text);
painter->drawText(-(int)(text_boundings.width() / 2.0), (int)(text_boundings.height() / 4.0), text);
// display file type(s) -- not implemented for output folder (we would need to inspect the directory)
// ...
// output folder name
painter->drawText(painter->boundingRect(QRectF(0, 0, 0, 0), Qt::AlignCenter, output_folder_name_).width()/-2, -25, output_folder_name_);
}
QRectF TOPPASOutputFolderVertex::boundingRect() const
{
return QRectF(-71, -41, 142, 82);
}
void TOPPASOutputFolderVertex::run()
{
// copy tmp files to output dir
// get incoming edge and preceding vertex
TOPPASEdge* e = *inEdgesBegin();
RoundPackages pkg = e->getSourceVertex()->getOutputFiles(); // this will be output folders
if (pkg.empty())
{
std::cerr << "A problem occurred while grabbing files from the parent tool. This is a bug, please report it!" << std::endl;
return;
}
String full_dir = createOutputDir(); // create output dir
round_total_ = (int) pkg.size(); // take number of rounds from previous tool(s) - should all be equal
round_counter_ = 0; // once round_counter_ reaches round_total_, we are done
// clear output file list
output_files_.clear();
output_files_.resize(pkg.size()); // #rounds
files_total_ = 0;
files_written_ = 0;
const TOPPASScene* ts = qobject_cast<TOPPASScene*>(scene());
bool dry_run = ts->isDryRun();
int param_index_src = e->getSourceOutParam();
int param_index_me = e->getTargetInParam();
for (Size round = 0; round < static_cast<Size>(round_total_); ++round)
{
for (const QString &src_dir : pkg[round][param_index_src].filenames.get())
{
if (!dry_run && !File::isDirectory(src_dir))
{
OPENMS_LOG_ERROR << "The directory '" << String(src_dir) << "' does not exist!" << std::endl;
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, src_dir.toStdString());
}
String new_dir = full_dir;
// if its only one round, do not create a subfolder
if (round_total_ > 1)
{ // the previous TOPP tool node should have placed all files in a subfolder for each round. Use that name
String last_subfolder = QDir(src_dir).dirName();
new_dir += last_subfolder.ensureLastChar('/');
}
output_files_[round][param_index_me].filenames.push_back(new_dir.toQString());
// find number of files in 'src_dir'
QDir dir(src_dir);
auto nr_of_files = dir.entryInfoList(QDir::Files).size();
if (!dry_run && nr_of_files == 0)
{
String msg = "Output directory '" + e->getSourceOutParamName() + "' did not yield any files!";
if (ts->isGUIMode())
{
QMessageBox::warning(nullptr, tr("No files found"), msg.toQString(), QMessageBox::Ok);
}
else
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, msg); // fail hard for ExecutePipeline
}
}
files_total_ += nr_of_files; // count number of files in 'src_dir'
}
}
// do the actual copying
if (dry_run) // assume the copy worked
{
files_written_ = files_total_;
update(boundingRect()); // repaint
}
else
{
for (Size round = 0; round < pkg.size(); ++round)
{
round_counter_ = (int)round; // for global update, in case someone asks
for (int i = 0; i < pkg[round][param_index_src].filenames.size(); ++i)
{
String dir_from = pkg[round][param_index_src].filenames[i];
String dir_to = output_files_[round][param_index_me].filenames[i];
// create the output directory (if it does not exist)
if (!File::makeDir(dir_to))
{
String msg = "Could not create output directory '" + dir_to + "' for node '"
+ pkg[round][param_index_src].edge->getTargetVertex()->getName() + "' . Please make sure the path is writable.";
OPENMS_LOG_ERROR << msg << std::endl;
if (ts->isGUIMode())
{
QMessageBox::warning(nullptr, tr("Directory creation failed"), tr(msg.c_str()), QMessageBox::Ok);
}
else
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, msg); // fail hard for ExecutePipeline
}
}
const auto& src_files_to_copy = QDir(dir_from.toQString()).entryInfoList(QDir::Files);
for (const auto& src_file : src_files_to_copy)
{
String file_from = src_file.absoluteFilePath();
String file_to = dir_to + '/' + src_file.fileName();
if (File::exists(file_to) // someone may have deleted the file in the meantime, which is fine
&& !QFile::remove(file_to.toQString())) // remove old file (would fail if file does not exist)
{
String msg = "Error: Could not remove old output file '" + file_to + "' for node '"
+ pkg[round][param_index_src].edge->getTargetVertex()->getName()
+ "' in preparation to write the new one. Please make sure the file is not open in other applications and try again.";
OPENMS_LOG_ERROR << msg << std::endl;
if (ts->isGUIMode())
{
QMessageBox::warning(nullptr, tr("File removing failed"), tr(msg.c_str()), QMessageBox::Ok);
}
else
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, msg); // fail hard for ExecutePipeline
}
}
// running the copy() in an extra thread, such that the GUI stays responsive
auto copyFuture = std::async(std::launch::async, &File::copy, file_from, file_to);
while (copyFuture.wait_for(std::chrono::milliseconds(25)) != std::future_status::ready)
{
qApp->processEvents(); // GUI responsiveness
}
if (copyFuture.get())
{
++files_written_;
emit outputFileWritten(file_to);
}
else
{
String msg = "Error: Could not copy temporary output file '" + file_from + "' for node '"
+ pkg[round][param_index_src].edge->getTargetVertex()->getName() + "' to " + file_to
+ "'. Probably the old file still exists (see earlier errors).";
OPENMS_LOG_ERROR << msg << std::endl;
if (ts->isGUIMode()) { QMessageBox::warning(nullptr, tr("File copy failed"), tr(msg.c_str()), QMessageBox::Ok); }
else
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, msg); // fail hard for ExecutePipeline
}
}
}
}
update(boundingRect()); // repaint after each round
} // end of round loop
} // end of dry_run check
finished_ = true;
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIATreeTab.cpp | .cpp | 12,322 | 334 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/DIATreeTab.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/FORMAT/OSWFile.h>
#include <OpenMS/VISUAL/LayerDataChrom.h>
#include <OpenMS/VISUAL/TreeView.h>
namespace OpenMS
{
// Use a namespace to encapsulate names, yet use c-style 'enum' for fast conversion to int.
// So we can write: 'Clmn::MS_LEVEL', but get implicit conversion to int
namespace Clmn
{
enum HeaderNames
{ // indices into QTableWidget's columns (which start at index 0)
ENTITY, INDEX, CHARGE, FULL_NAME, RT_DELTA, QVALUE, /* last entry --> */ SIZE_OF_HEADERNAMES
};
// keep in SYNC with enum HeaderNames
const QStringList HEADER_NAMES = QStringList()
<< "entity" << "index" << "charge" << "full name" << "rt delta" << "q-value";
}
/// given an item, goes up the tree to the root and collects indices in to the OSWData for each level
OSWIndexTrace getTrace(QTreeWidgetItem* current)
{
OSWIndexTrace trace;
while (current != nullptr)
{
OSWHierarchy::Level level = OSWHierarchy::Level(current->data(Clmn::INDEX, Qt::UserRole).toInt());
int index = current->data(Clmn::INDEX, Qt::DisplayRole).toInt();
if (trace.lowest == OSWHierarchy::Level::SIZE_OF_VALUES)
{ // set to level of first current
trace.lowest = level;
}
switch (level)
{
case OSWHierarchy::Level::PROTEIN:
trace.idx_prot = index;
break;
case OSWHierarchy::Level::PEPTIDE:
trace.idx_pep = index;
break;
case OSWHierarchy::Level::FEATURE:
trace.idx_feat = index;
break;
case OSWHierarchy::Level::TRANSITION:
trace.idx_trans = index;
break;
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
// up one level
current = current->parent();
}
return trace;
}
DIATreeTab::DIATreeTab(QWidget* parent) :
QWidget(parent)
{
setObjectName("DIA OSW View");
QVBoxLayout* spectra_widget_layout = new QVBoxLayout(this);
dia_treewidget_ = new TreeView(this);
dia_treewidget_->setWhatsThis("Protein/Peptide/Transition selection bar<BR><BR>Here all XICs of a DIA experiment are shown. Left-click on a chrom to show it. "
"Double-clicking might be implemented as well, depending on the data. "
"Context-menus for both the column header and data rows are available by right-clicking.");
//~ no good for huge experiments - omitted:
//~ spectrum_selection_->setSortingEnabled(true);
//~ spectrum_selection_->sortByColumn ( 1, Qt::AscendingOrder);
dia_treewidget_->setDragEnabled(true);
dia_treewidget_->setContextMenuPolicy(Qt::CustomContextMenu);
connect(dia_treewidget_, &QTreeWidget::currentItemChanged, this, &DIATreeTab::rowSelectionChange_);
connect(dia_treewidget_, &QTreeWidget::itemClicked, this, &DIATreeTab::rowClicked_);
connect(dia_treewidget_, &QTreeWidget::itemDoubleClicked, this, &DIATreeTab::rowDoubleClicked_);
spectra_widget_layout->addWidget(dia_treewidget_);
QHBoxLayout* tmp_hbox_layout = new QHBoxLayout();
spectra_search_box_ = new QLineEdit(this);
spectra_search_box_->setPlaceholderText("<search text>");
spectra_search_box_->setWhatsThis("Search in a certain column. Hits are shown as you type. Press <Enter> to display the first hit.");
spectra_search_box_->setToolTip(spectra_search_box_->whatsThis());
spectra_combo_box_ = new QComboBox(this);
spectra_combo_box_->setWhatsThis("Sets the column in which to search.");
spectra_combo_box_->setToolTip(spectra_combo_box_->whatsThis());
// search whenever text is typed (and highlight the hits)
connect(spectra_search_box_, &QLineEdit::textEdited, this, &DIATreeTab::spectrumSearchText_);
// .. show hit upon pressing Enter (internally we search again, since the user could have activated another layer with different selections after last search)
connect(spectra_search_box_, &QLineEdit::returnPressed, this, &DIATreeTab::searchAndShow_);
tmp_hbox_layout->addWidget(spectra_search_box_);
tmp_hbox_layout->addWidget(spectra_combo_box_);
spectra_widget_layout->addLayout(tmp_hbox_layout);
}
/// adds a subtree (with peptides ...) to a given protein
void fillProt(const OSWProtein& prot, QTreeWidgetItem* item_prot)
{
for (size_t idx_pep = 0; idx_pep < prot.getPeptidePrecursors().size(); ++idx_pep)
{
const auto& pep = prot.getPeptidePrecursors()[idx_pep];
QTreeWidgetItem* item_pep = new QTreeWidgetItem(item_prot);
item_pep->setData(Clmn::ENTITY, Qt::DisplayRole, OSWHierarchy::LevelName[OSWHierarchy::PEPTIDE]);
item_pep->setData(Clmn::INDEX, Qt::DisplayRole, (int)idx_pep);
item_pep->setData(Clmn::INDEX, Qt::UserRole, OSWHierarchy::PEPTIDE); // mark as peptide, so we know how to interpret the display role
item_pep->setData(Clmn::CHARGE, Qt::DisplayRole, pep.getCharge());
item_pep->setText(Clmn::FULL_NAME, pep.getSequence().c_str());
for (size_t idx_feat = 0; idx_feat < pep.getFeatures().size(); ++idx_feat)
{
const auto& feat = pep.getFeatures()[idx_feat];
QTreeWidgetItem* item_feat = new QTreeWidgetItem(item_pep);
item_feat->setData(Clmn::ENTITY, Qt::DisplayRole, OSWHierarchy::LevelName[OSWHierarchy::FEATURE]);
item_feat->setData(Clmn::INDEX, Qt::DisplayRole, (int)idx_feat);
item_feat->setData(Clmn::INDEX, Qt::UserRole, OSWHierarchy::FEATURE); // mark as feature, so we know how to interpret the display role
item_feat->setData(Clmn::RT_DELTA, Qt::DisplayRole, feat.getRTDelta());
item_feat->setData(Clmn::QVALUE, Qt::DisplayRole, feat.getQValue());
for (size_t idx_trans = 0; idx_trans < feat.getTransitionIDs().size(); ++idx_trans)
{
QTreeWidgetItem* item_trans = new QTreeWidgetItem(item_feat);
item_trans->setData(Clmn::ENTITY, Qt::DisplayRole, OSWHierarchy::LevelName[OSWHierarchy::TRANSITION]);
item_trans->setData(Clmn::INDEX, Qt::DisplayRole, (int)idx_trans);
item_trans->setData(Clmn::INDEX, Qt::UserRole, OSWHierarchy::TRANSITION); // mark as transition, so we know how to interpret the display role
}
}
//item_prot->addChild(item_pep);
}
}
/// creates a protein subtree (with peptides etc, if available)
QTreeWidgetItem* createProt(const OSWProtein& prot, int prot_index)
{
QTreeWidgetItem* item_prot = new QTreeWidgetItem();
item_prot->setData(Clmn::ENTITY, Qt::DisplayRole, "protein");
item_prot->setData(Clmn::INDEX, Qt::DisplayRole, prot_index);
item_prot->setData(Clmn::INDEX, Qt::UserRole, OSWHierarchy::PROTEIN); // mark as protein, so we know how to interpret the display role
item_prot->setText(Clmn::FULL_NAME, prot.getAccession().c_str());
// if possible, fill it already
fillProt(prot, item_prot);
return item_prot;
}
void DIATreeTab::spectrumSearchText_()
{
const QString& text = spectra_search_box_->text(); // get text from QLineEdit
if (!text.isEmpty())
{
Qt::MatchFlags matchflags = Qt::MatchFixedString;
matchflags |= Qt::MatchRecursive; // match subitems (below top-level)
matchflags |= Qt::MatchStartsWith;
QList<QTreeWidgetItem*> searched = dia_treewidget_->findItems(text, matchflags, spectra_combo_box_->currentIndex());
if (!searched.isEmpty())
{
dia_treewidget_->clearSelection();
searched.first()->setSelected(true);
dia_treewidget_->update();
dia_treewidget_->scrollToItem(searched.first());
}
}
}
OSWIndexTrace DIATreeTab::prepareSignal_(QTreeWidgetItem* item)
{
OSWIndexTrace tr;
if (item == nullptr || current_data_ == nullptr)
{
return tr;
}
tr = getTrace(item);
switch (tr.lowest)
{
case OSWHierarchy::Level::PROTEIN:
if (item->childCount() == 0)
{ // no peptides... load them
OSWFile f(current_data_->getSqlSourceFile());
f.readProtein(*current_data_, tr.idx_prot);
fillProt(current_data_->getProteins()[tr.idx_prot], item);
}
// do nothing else -- showing all transitions for a protein is overwhelming...
break;
case OSWHierarchy::Level::PEPTIDE:
case OSWHierarchy::Level::FEATURE:
case OSWHierarchy::Level::TRANSITION:
break;
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
return tr;
}
void DIATreeTab::rowSelectionChange_(QTreeWidgetItem* current, QTreeWidgetItem* /*previous*/)
{
auto tr = prepareSignal_(current);
if (tr.isSet()) emit entityClicked(tr);
}
void DIATreeTab::rowClicked_(QTreeWidgetItem* item, int /*col*/)
{
auto tr = prepareSignal_(item);
if (tr.isSet()) emit entityClicked(tr);
}
void DIATreeTab::rowDoubleClicked_(QTreeWidgetItem* item, int /*col*/)
{
auto tr = prepareSignal_(item);
if (tr.isSet())
{
entityDoubleClicked(tr);
}
}
void DIATreeTab::searchAndShow_()
{
spectrumSearchText_(); // update selection first (we might be in a new layer)
QList<QTreeWidgetItem*> selected = dia_treewidget_->selectedItems();
// show the first selected item
if (selected.size() > 0) rowSelectionChange_(selected.first(), selected.first());
}
bool DIATreeTab::hasData(const LayerDataBase* layer)
{
if (auto* lp = dynamic_cast<const LayerDataChrom*>(layer))
{
OSWData* data = lp->getChromatogramAnnotation().get();
return (data != nullptr && !data->getProteins().empty());
}
return false;
}
void DIATreeTab::updateEntries(LayerDataBase* layer)
{
if (layer == nullptr)
{
clear();
return;
}
if (!dia_treewidget_->isVisible() || dia_treewidget_->signalsBlocked())
{
return;
}
auto* lp = dynamic_cast<const LayerDataChrom*>(layer);
if (!lp) return;
OSWData* data = lp->getChromatogramAnnotation().get();
if (current_data_ == data)
{
// layer data is still the same as last time ..
// do not repopulate the table for now, since the data should not have changed
// Note: If we ever need to redraw, the tree's state (which subtress are expanded, which items are selected) will need to be remembered and restored
return;
}
// update last data pointer
current_data_ = data;
dia_treewidget_->blockSignals(true);
RAIICleanup clean([&]() { dia_treewidget_->blockSignals(false); });
dia_treewidget_->clear();
dia_treewidget_->setHeaders(Clmn::HEADER_NAMES);
if (data == nullptr // DIA tab is active, but the layer has no data to show...
|| data->getProteins().empty())
{
dia_treewidget_->setHeaders(QStringList() << "No data");
}
else
{
for (size_t prot_index = 0; prot_index < data->getProteins().size(); ++prot_index)
{
const auto& prot = data->getProteins()[prot_index];
auto item_prot = createProt(prot, (int)prot_index);
dia_treewidget_->addTopLevelItem(item_prot);
}
}
populateSearchBox_();
// automatically set column width, depending on data
dia_treewidget_->header()->setStretchLastSection(false);
dia_treewidget_->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
}
void DIATreeTab::populateSearchBox_()
{
QStringList headers = dia_treewidget_->getHeaderNames(WidgetHeader::WITH_INVISIBLE);
int current_index = spectra_combo_box_->currentIndex(); // when repainting we want the index to stay the same
spectra_combo_box_->clear();
spectra_combo_box_->addItems(headers);
spectra_combo_box_->setCurrentIndex(current_index);
}
void DIATreeTab::clear()
{
dia_treewidget_->clear();
spectra_combo_box_->clear();
current_data_ = nullptr;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ParamEditor.cpp | .cpp | 32,519 | 1,008 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ParamEditor.h>
#include <ui_ParamEditor.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/DATASTRUCTURES/ListUtilsIO.h>
#include <OpenMS/VISUAL/ListEditor.h>
#include <OpenMS/VISUAL/DIALOGS/ListFilterDialog.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMenu>
#include <QItemSelection>
#include <QtCore/QStringList>
#include <QtWidgets/QLabel>
#include <QtWidgets/QFileDialog>
#include <stack>
#include <limits>
#include <sstream>
using namespace std;
/*
Description of the data stored in the items:
| Column 0 | Column 1 | Column 2 | Column 3 |
---------------------------------------------------------------------
DisplayRole | name | value | type | restr. (display) |
UserRole | NODE/ITEM | description | restr. | |
*/
namespace OpenMS
{
namespace Internal
{
void OpenMSLineEdit::focusInEvent ( QFocusEvent * /* e */)
{
//std::cerr << "got focus";
}
void OpenMSLineEdit::focusOutEvent ( QFocusEvent * /* e */ )
{
//std::cerr << "lost focus";
emit lostFocus();
}
ParamEditorDelegate::ParamEditorDelegate(QObject* parent) :
QItemDelegate(parent)
{
}
QWidget* ParamEditorDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex& index) const
{
Int type = index.sibling(index.row(), 0).data(Qt::UserRole).toInt();
// only create editor for first column (value column)
if (index.column() != 1 || type == ParamEditor::NODE)
{
return nullptr;
}
has_uncommited_data_ = false; // by default all data is committed
QString dtype = index.sibling(index.row(), 2).data(Qt::DisplayRole).toString();
QString restrictions = index.sibling(index.row(), 2).data(Qt::UserRole).toString();
QString value = index.sibling(index.row(), 1).data(Qt::DisplayRole).toString();
if (dtype == "string" && restrictions != "") //Drop-down list for enums
{
QComboBox* editor = new QComboBox(parent);
QStringList list;
list.append("");
list += restrictions.split(",");
editor->addItems(list);
connect(editor, SIGNAL(activated(int)), this, SLOT(commitAndCloseEditor_()));
return editor;
}
else if (dtype == "output file")
{
QLineEdit* editor = new QLineEdit(parent);
QString dir = ""; // = index.sibling(index.row(),0).data(Qt::DisplayRole).toString();
if (File::isDirectory(value) || File::writable(value))
{
dir = File::absolutePath(value).toQString();
}
fileName_ = QFileDialog::getSaveFileName(editor, tr("Output File"), dir);
return editor;
}
else if (dtype == "output dir")
{
QLineEdit* editor = new QLineEdit(parent);
QString dir = ""; // = index.sibling(index.row(),0).data(Qt::DisplayRole).toString();
if (File::isDirectory(value) || File::writable(value)) { dir = File::absolutePath(value).toQString(); }
dirName_ = QFileDialog::getExistingDirectory(editor, tr("Output Directory"), dir);
return editor;
}
else if (dtype == "input file")
{
QLineEdit* editor = new QLineEdit(parent);
QString dir = ""; // = index.sibling(index.row(),0).data(Qt::DisplayRole).toString();
if (File::isDirectory(value) || File::exists(value))
{
dir = File::absolutePath(value).toQString();
}
fileName_ = QFileDialog::getOpenFileName(editor, tr("Input File"), dir);
return editor;
}
else if (dtype == "string list" && !restrictions.isEmpty())
{
ListFilterDialog* editor = new ListFilterDialog(nullptr);
connect(editor, SIGNAL(accepted()), this, SLOT(commitAndCloseEditor_()));
connect(editor, SIGNAL(rejected()), this, SLOT(closeEditor_()));
return editor;
}
else if (dtype == "string list" || dtype == "int list" || dtype == "double list" || dtype == "input file list" || dtype == "output file list") // for lists
{
QString title = "<" + index.sibling(index.row(), 0).data(Qt::DisplayRole).toString() + "> " + "(<" + dtype + ">)";
ListEditor* editor = new ListEditor(nullptr, title);
editor->setTypeName(index.sibling(index.row(), 0).data(Qt::DisplayRole).toString());
editor->setModal(true);
connect(editor, SIGNAL(accepted()), this, SLOT(commitAndCloseEditor_()));
connect(editor, SIGNAL(rejected()), this, SLOT(closeEditor_()));
return editor;
}
else
{ // LineEditor for rest
OpenMSLineEdit* editor = new OpenMSLineEdit(parent);
editor->setFocusPolicy(Qt::StrongFocus);
connect(editor, &Internal::OpenMSLineEdit::lostFocus, this, &Internal::ParamEditorDelegate::commitAndCloseLineEdit_);
has_uncommited_data_ = true;
return editor;
}
}
void ParamEditorDelegate::setEditorData(QWidget * editor, const QModelIndex & index) const
{
QString str = index.data(Qt::DisplayRole).toString();
// only set editor data for first column (value column)
if (index.column() != 1)
{
return;
}
if (qobject_cast<QComboBox *>(editor)) //Drop-down list for enums
{
int index = static_cast<QComboBox *>(editor)->findText(str);
if (index == -1)
{
index = 0;
}
static_cast<QComboBox *>(editor)->setCurrentIndex(index);
}
else if (qobject_cast<QLineEdit *>(editor)) // LineEdit for other values
{
QString dtype = index.sibling(index.row(), 2).data(Qt::DisplayRole).toString();
if (dtype == "output file" || dtype == "input file") /// for output/input file
{
if (!fileName_.isNull())
{
static_cast<QLineEdit *>(editor)->setText(fileName_);
}
}
else if (dtype == "output dir") // output directory
{
if (!dirName_.isNull())
{
static_cast<QLineEdit*>(editor)->setText(dirName_);
}
}
else
{
if (str == "" && (dtype == "int" || dtype == "float"))
{
if (dtype == "int")
static_cast<QLineEdit *>(editor)->setText("0");
else if (dtype == "float")
static_cast<QLineEdit *>(editor)->setText("nan");
}
else
{
static_cast<QLineEdit *>(editor)->setText(str);
}
}
}
else // for lists
{
String list = str.mid(1, str.length() - 2);
StringList rlist = ListUtils::create<String>(list);
for (auto& item : rlist)
{
item.trim(); // remove '\n'
}
String restrictions = index.sibling(index.row(), 2).data(Qt::UserRole).toString();
if (qobject_cast<ListEditor*>(editor))
{
QString type = index.sibling(index.row(), 2).data(Qt::DisplayRole).toString();
if (type == "int list")
{
static_cast<ListEditor *>(editor)->setList(rlist, ListEditor::INT);
}
else if (type == "double list")
{
static_cast<ListEditor *>(editor)->setList(rlist, ListEditor::FLOAT);
}
else if (type == "string list")
{
static_cast<ListEditor *>(editor)->setList(rlist, ListEditor::STRING);
}
else if (type == "input file list")
{
static_cast<ListEditor *>(editor)->setList(rlist, ListEditor::INPUT_FILE);
}
else if (type == "output file list")
{
static_cast<ListEditor *>(editor)->setList(rlist, ListEditor::OUTPUT_FILE);
}
static_cast<ListEditor *>(editor)->setListRestrictions(restrictions);
}
else if (qobject_cast<ListFilterDialog*>(editor)) // for StringLists with restrictions
{
static_cast<ListFilterDialog*>(editor)->setItems(restrictions.toQString().split(','));
static_cast<ListFilterDialog*>(editor)->setPrechosenItems(GUIHelpers::convert(rlist));
}
}
}
void ParamEditorDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
// only set model data for first column (value column)
if (index.column() != 1)
{
return;
}
QVariant present_value = index.data(Qt::DisplayRole);
QVariant new_value;
//extract new value
if (qobject_cast<QComboBox *>(editor)) //Drop-down list for enums
{
new_value = QVariant(static_cast<QComboBox *>(editor)->currentText());
}
else if (qobject_cast<QLineEdit *>(editor))
{
QString dtype = index.sibling(index.row(), 2).data(Qt::DisplayRole).toString();
if (dtype == "output file" || dtype == "input file") // input/output file
{
new_value = QVariant(static_cast<QLineEdit *>(editor)->text());
fileName_ = "\0";
}
if (dtype == "output dir") // output directory
{
new_value = QVariant(static_cast<QLineEdit*>(editor)->text());
dirName_ = "\0";
}
else if (static_cast<QLineEdit*>(editor)->text() == "" && ((dtype == "int") || (dtype == "float"))) // numeric
{
if (dtype == "int")
{
new_value = QVariant("0");
}
else if (dtype == "float")
{
new_value = QVariant("nan");
}
}
else
{
new_value = QVariant(static_cast<QLineEdit *>(editor)->text());
}
}
else if (qobject_cast<ListEditor*>(editor))
{
new_value = QString("[%1]").arg(ListUtils::concatenate(static_cast<ListEditor *>(editor)->getList(), ",\n").toQString());
}
else if (qobject_cast<ListFilterDialog*>(editor))
{
new_value = QString("[%1]").arg(static_cast<ListFilterDialog*>(editor)->getChosenItems().join(",\n"));
}
else
{
// some new editor ...
}
// check if it matches the restrictions or is empty
if (new_value.toString() != "")
{
QString type = index.sibling(index.row(), 2).data(Qt::DisplayRole).toString();
bool restrictions_met = true;
String restrictions = index.sibling(index.row(), 2).data(Qt::UserRole).toString();
if (type == "int") //check if valid integer
{
bool ok(true);
new_value.toString().toLong(&ok);
if (!ok)
{
QMessageBox::warning(nullptr, "Invalid value", QString("Cannot convert '%1' to integer number!").arg(new_value.toString()));
return;
}
//restrictions
vector<String> parts;
if (restrictions.split(' ', parts))
{
if (!parts[0].empty() && new_value.toInt() < parts[0].toInt())
{
restrictions_met = false;
}
if (!parts[1].empty() && new_value.toInt() > parts[1].toInt())
{
restrictions_met = false;
}
}
}
else if (type == "float") //check if valid float
{
bool ok(true);
new_value.toString().toDouble(&ok);
if (!ok)
{
QMessageBox::warning(nullptr, "Invalid value", QString("Cannot convert '%1' to floating point number!").arg(new_value.toString()));
return;
}
//restrictions
vector<String> parts;
if (restrictions.split(' ', parts))
{
if (!parts[0].empty() && new_value.toDouble() < parts[0].toDouble())
{
restrictions_met = false;
}
if (!parts[1].empty() && new_value.toDouble() > parts[1].toDouble())
{
restrictions_met = false;
}
}
}
if (!restrictions_met)
{
QMessageBox::warning(nullptr, "Invalid value", QString("Value restrictions not met: %1").arg(index.sibling(index.row(), 3).data(Qt::DisplayRole).toString()));
return;
}
}
// check if modified
if (new_value != present_value)
{
model->setData(index, new_value);
model->setData(index, QBrush(Qt::yellow), Qt::BackgroundRole);
emit modified(true); // let parent know that we changed something
}
}
void ParamEditorDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex &) const
{
editor->setGeometry(option.rect);
}
bool ParamEditorDelegate::eventFilter(QObject* editor, QEvent* event)
{
// NEVER EVER commit data (which calls setModelData()), without explicit calls to commit() for non-embedded Dialogs ;
if (qobject_cast<ListEditor*>(editor) || qobject_cast<ListFilterDialog*>(editor))
{
return false;
}
// default: will call commit(), if the event was handled (e.g. a press of 'Enter')
return QItemDelegate::eventFilter(editor, event);
}
void ParamEditorDelegate::commitAndCloseEditor_()
{
QWidget* editor = qobject_cast<QWidget*>(sender());
emit commitData(editor); // calls .setModelData(...)
emit closeEditor(editor);
}
void ParamEditorDelegate::closeEditor_()
{
QWidget* editor = qobject_cast<QWidget*>(sender());
emit closeEditor(editor);
}
void ParamEditorDelegate::commitAndCloseLineEdit_()
{
has_uncommited_data_ = false;
OpenMSLineEdit * editor = qobject_cast<OpenMSLineEdit *>(sender());
emit commitData(editor);
emit closeEditor(editor);
}
bool ParamEditorDelegate::hasUncommittedData() const
{
return has_uncommited_data_;
}
///////////////////ParamTree/////////////////////////////////
ParamTree::ParamTree(QWidget * parent) :
QTreeWidget(parent)
{
}
void ParamTree::selectionChanged(const QItemSelection & s, const QItemSelection &)
{
if (!s.empty())
{
emit selected(s.indexes().first());
}
}
bool ParamTree::edit(const QModelIndex & index, EditTrigger trigger, QEvent * event)
{ // allow F2 or double click on any column in the current row
if (trigger == QAbstractItemView::EditKeyPressed || trigger == QAbstractItemView::DoubleClicked)
{ // --> re-route to actual value column
return QAbstractItemView::edit(index.sibling(index.row(), 1), trigger, event);
}
return QAbstractItemView::edit(index, trigger, event);
}
}
///////////////////ParamEditor/////////////////////////////////
ParamEditor::ParamEditor(QWidget * parent) :
QWidget(parent),
param_(nullptr),
modified_(false),
advanced_mode_(false),
ui_(new Ui::ParamEditorTemplate)
{
ui_->setupUi(this);
tree_ = new Internal::ParamTree(this);
//tree_->setMinimumSize(450, 200);
tree_->setAllColumnsShowFocus(true);
tree_->setColumnCount(4);
tree_->setHeaderLabels(QStringList() << "parameter" << "value" << "type" << "restrictions");
dynamic_cast<QVBoxLayout *>(layout())->insertWidget(0, tree_, 1);
tree_->setItemDelegate(new Internal::ParamEditorDelegate(tree_)); // the delegate from above is set
connect(tree_->itemDelegate(), SIGNAL(modified(bool)), this, SLOT(setModified(bool)));
connect(ui_->advanced_, SIGNAL(toggled(bool)), this, SLOT(toggleAdvancedMode(bool)));
connect(tree_, SIGNAL(selected(const QModelIndex &)), this, SLOT(showDocumentation(const QModelIndex &)));
}
ParamEditor::~ParamEditor()
{
delete ui_;
}
void ParamEditor::showDocumentation(const QModelIndex & index)
{
ui_->doc_->setText(index.sibling(index.row(), 1).data(Qt::UserRole).toString());
}
void ParamEditor::load(Param & param)
{
param_ = ¶m;
tree_->clear();
QTreeWidgetItem * parent = tree_->invisibleRootItem();
QTreeWidgetItem * item = nullptr;
bool has_advanced_item = false; // will be true if @p param has any advanced items; if still false, we disable the 'show advanced checkbox'
for (Param::ParamIterator it = param.begin(); it != param.end(); ++it)
{
//********handle opened/closed nodes********
const std::vector<Param::ParamIterator::TraceInfo> & trace = it.getTrace();
for (const Param::ParamIterator::TraceInfo& par : trace)
{
if (par.opened) //opened node
{
item = new QTreeWidgetItem(parent);
//name
item->setText(0, String(par.name).toQString());
item->setForeground(0, Qt::darkGray); // color of nodes with children
//description
item->setData(1, Qt::UserRole, String(par.description).toQString());
//role
item->setData(0, Qt::UserRole, NODE);
//flags
if (param_ != nullptr)
{
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);
}
else
{
item->setFlags(Qt::ItemIsEnabled);
}
parent = item;
}
else //closed node
{
parent = parent->parent();
if (parent == nullptr)
{
parent = tree_->invisibleRootItem();
}
}
}
//********handle item********
item = new QTreeWidgetItem(parent);
// grey out non-editable columns (leaf nodes)
bool is_required = it->tags.find("required") != it->tags.end();
if (is_required) // special color for required parameters
{
item->setForeground(0, QColor(255, 140, 0, 255)); // orange
item->setForeground(2, QColor(255, 140, 0, 255));
item->setForeground(3, QColor(255, 140, 0, 255));
}
else
{
item->setForeground(0, Qt::darkGray);
item->setForeground(2, Qt::darkGray);
item->setForeground(3, Qt::darkGray);
}
// advanced parameter
if (it->tags.count("advanced"))
{
item->setData(0, Qt::UserRole, ADVANCED_ITEM);
has_advanced_item = true;
}
else
{
item->setData(0, Qt::UserRole, NORMAL_ITEM);
}
// name
item->setText(0, String(it->name).toQString());
// value
if (it->value.valueType() == ParamValue::STRING_LIST)
{
item->setText(1, QString("[%1]").arg(GUIHelpers::convert(ListUtils::toStringList<std::string>(it->value.toStringVector())).join(",\n")));
}
else if (it->value.valueType() == ParamValue::INT_LIST)
{
item->setText(1, QString("[%1]").arg(GUIHelpers::convert(ListUtils::toStringList(it->value.toIntVector())).join(",\n")));
}
else if (it->value.valueType() == ParamValue::DOUBLE_LIST)
{
item->setText(1, QString("[%1]").arg(GUIHelpers::convert(ListUtils::toStringList(it->value.toDoubleVector())).join(",\n")));
}
else
{
item->setText(1, String(it->value.toString()).toQString());
}
// type
switch (it->value.valueType())
{
case ParamValue::INT_VALUE:
item->setText(2, "int");
break;
case ParamValue::DOUBLE_VALUE:
item->setText(2, "float");
break;
case ParamValue::STRING_VALUE:
if (it->tags.count("input file"))
{
item->setText(2, "input file");
}
else if (it->tags.count("output file"))
{
item->setText(2, "output file");
}
else if (it->tags.count("output dir"))
{
item->setText(2, "output dir");
}
else
{
item->setText(2, "string");
}
break;
case ParamValue::STRING_LIST:
if (it->tags.count("input file"))
{
item->setText(2, "input file list");
}
else if (it->tags.count("output file"))
{
item->setText(2, "output file list");
}
else
{
item->setText(2, "string list");
}
break;
case ParamValue::INT_LIST:
item->setText(2, "int list");
break;
case ParamValue::DOUBLE_LIST:
item->setText(2, "double list");
break;
default:
break;
}
//restrictions (displayed and internal for easier parsing)
switch (it->value.valueType())
{
case ParamValue::INT_VALUE:
case ParamValue::INT_LIST:
{
String drest = "", irest = "";
bool min_set = (it->min_int != -numeric_limits<Int>::max());
bool max_set = (it->max_int != numeric_limits<Int>::max());
if (max_set || min_set)
{
if (min_set)
{
drest += String("min: ") + it->min_int;
irest += it->min_int;
}
irest += " ";
if (max_set)
{
if (min_set && max_set)
drest += " ";
drest += String("max: ") + it->max_int;
irest += it->max_int;
}
item->setText(3, drest.toQString());
}
item->setData(2, Qt::UserRole, irest.toQString());
}
break;
case ParamValue::DOUBLE_VALUE:
case ParamValue::DOUBLE_LIST:
{
String drest = "", irest = "";
bool min_set = (it->min_float != -numeric_limits<double>::max());
bool max_set = (it->max_float != numeric_limits<double>::max());
if (max_set || min_set)
{
if (min_set)
{
drest += String("min: ") + it->min_float;
irest += it->min_float;
}
irest += " ";
if (max_set)
{
if (min_set && max_set)
drest += " ";
drest += String("max: ") + it->max_float;
irest += it->max_float;
}
item->setText(3, drest.toQString());
}
item->setData(2, Qt::UserRole, irest.toQString());
}
break;
case ParamValue::STRING_VALUE:
case ParamValue::STRING_LIST:
{
String irest = ListUtils::concatenate(it->valid_strings, ",");
if (!irest.empty())
{
String r_text = irest;
if (r_text.size() > 255) // truncate restriction text, as some QT versions (4.6 & 4.7) will crash if text is too long
{
r_text = irest.prefix(251) + "...";
}
item->setText(3, r_text.toQString());
}
item->setData(2, Qt::UserRole, irest.toQString());
}
break;
default:
break;
}
//description
item->setData(1, Qt::UserRole, String(it->description).toQString());
//flags
if (param_ != nullptr)
{
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);
}
else
{
item->setFlags(Qt::ItemIsEnabled);
}
}
ui_->advanced_->setVisible(has_advanced_item);
tree_->expandAll();
toggleAdvancedMode(advanced_mode_);
tree_->resizeColumnToContents(0);
tree_->resizeColumnToContents(1);
tree_->resizeColumnToContents(2);
tree_->resizeColumnToContents(3);
}
void ParamEditor::store()
{
//std::cerr << "store entered ...\n";
// store only if no line-edit is opened (in which case data is uncommitted and will not be saved)
// this applies only to INIFileEditor, where pressing Ctrl-s results in saving the current (but outdated) param
if (param_ != nullptr &&
!static_cast<Internal::ParamEditorDelegate*>(this->tree_->itemDelegate())->hasUncommittedData())
{
//std::cerr << "and done!...\n";
QTreeWidgetItem * parent = tree_->invisibleRootItem();
//param_->clear();
for (Int i = 0; i < parent->childCount(); ++i)
{
map<String, String> section_descriptions;
storeRecursive_(parent->child(i), "", section_descriptions); //whole tree recursively
}
setModified(false);
}
//else std::cerr << "store aborted!\n";
}
void ParamEditor::clear()
{
tree_->clear();
}
void ParamEditor::storeRecursive_(QTreeWidgetItem * child, String path, map<String, String> & section_descriptions)
{
/**
@todo: why would we "recreate" (setting restrictions etc) the the param object from scratch?
updating everything that changed seems the better option, as
this is more robust against additions to Param
*/
child->setData(1, Qt::BackgroundRole, QBrush(Qt::white));
if (path.empty())
{
path = child->text(0).toStdString();
}
else
{
path += String(":") + String(child->text(0).toStdString());
}
String description = child->data(1, Qt::UserRole).toString();
if (child->text(2) == "") // node
{
if (!description.empty())
{
section_descriptions.insert(make_pair(path, description));
}
}
else //item + section descriptions
{
std::vector<std::string> tag_list;
try // might throw ElementNotFound
{
tag_list = param_->getTags(path);
}
catch (...)
{
}
if (child->text(2) == "float")
{
param_->setValue(path, child->text(1).toDouble(), description, tag_list);
String restrictions = child->data(2, Qt::UserRole).toString();
vector<String> parts;
if (restrictions.split(' ', parts))
{
if (!parts[0].empty())
{
param_->setMinFloat(path, parts[0].toDouble());
}
if (!parts[1].empty())
{
param_->setMaxFloat(path, parts[1].toDouble());
}
}
}
else if (std::unordered_set<QString> {"string", "input file", "output file", "output dir"}.count(child->text(2)))
{
param_->setValue(path, child->text(1).toStdString(), description, tag_list);
String restrictions = child->data(2, Qt::UserRole).toString();
if (!restrictions.empty())
{
std::vector<std::string> parts = ListUtils::create<std::string>(restrictions);
param_->setValidStrings(path, parts);
}
}
else if (child->text(2) == "int")
{
param_->setValue(path, child->text(1).toInt(), description, tag_list);
String restrictions = child->data(2, Qt::UserRole).toString();
vector<String> parts;
if (restrictions.split(' ', parts))
{
if (!parts[0].empty())
{
param_->setMinInt(path, parts[0].toInt());
}
if (!parts[1].empty())
{
param_->setMaxInt(path, parts[1].toInt());
}
}
}
String list;
list = child->text(1).mid(1, child->text(1).length() - 2);
std::vector<std::string> rlist = ListUtils::create<std::string>(list);
if (child->text(2) == "string list")
{
param_->setValue(path, rlist, description, tag_list);
String restrictions = child->data(2, Qt::UserRole).toString();
if (!restrictions.empty())
{
vector<std::string> parts = ListUtils::create<std::string>(restrictions);
param_->setValidStrings(path, parts);
}
}
else if (child->text(2) == "input file list")
{
param_->setValue(path, rlist, description, tag_list);
String restrictions = child->data(2, Qt::UserRole).toString();
if (!restrictions.empty())
{
std::vector<std::string> parts = ListUtils::create<std::string>(restrictions);
param_->setValidStrings(path, parts);
}
}
else if (child->text(2) == "output file list")
{
param_->setValue(path, rlist, description, tag_list);
String restrictions = child->data(2, Qt::UserRole).toString();
if (!restrictions.empty())
{
std::vector<std::string> parts = ListUtils::create<std::string>(restrictions);
param_->setValidStrings(path, parts);
}
}
else if (child->text(2) == "double list")
{
param_->setValue(path, ListUtils::create<double>(ListUtils::toStringList<std::string>(rlist)), description, tag_list);
String restrictions = child->data(2, Qt::UserRole).toString();
vector<String> parts;
if (restrictions.split(' ', parts))
{
if (!parts[0].empty())
{
param_->setMinFloat(path, parts[0].toFloat());
}
if (!parts[1].empty())
{
param_->setMaxFloat(path, parts[1].toFloat());
}
}
}
else if (child->text(2) == "int list")
{
param_->setValue(path, ListUtils::create<Int>(ListUtils::toStringList<std::string>(rlist)), description, tag_list);
String restrictions = child->data(2, Qt::UserRole).toString();
vector<String> parts;
if (restrictions.split(' ', parts))
{
if (!parts[0].empty())
{
param_->setMinInt(path, parts[0].toInt());
}
if (!parts[1].empty())
{
param_->setMaxInt(path, parts[1].toInt());
}
}
}
// set description node description if the prefix matches
for (map<String, String>::const_iterator it = section_descriptions.begin(); it != section_descriptions.end(); ++it)
{
if (path.hasPrefix(it->first))
{
param_->setSectionDescription(it->first, it->second);
}
}
section_descriptions.clear();
}
for (Int i = 0; i < child->childCount(); ++i)
{
storeRecursive_(child->child(i), path, section_descriptions); //whole tree recursively
}
}
void ParamEditor::setModified(bool is_modified)
{
if (is_modified != modified_)
{
modified_ = is_modified;
emit modified(modified_);
}
}
bool ParamEditor::isModified() const
{
return modified_;
}
void ParamEditor::toggleAdvancedMode(bool advanced)
{
advanced_mode_ = advanced;
stack<QTreeWidgetItem *> stack, node_stack;
//show/hide items
stack.push(tree_->invisibleRootItem());
while (!stack.empty())
{
QTreeWidgetItem * current = stack.top();
stack.pop();
Int type = current->data(0, Qt::UserRole).toInt();
if (type != NODE) //ITEM
{
if (advanced_mode_ && type == ADVANCED_ITEM) //advanced mode
{
current->setHidden(false);
}
else if (!advanced_mode_ && type == ADVANCED_ITEM) //Normal mode
{
current->setHidden(true);
}
}
else //NODE
{
for (Int i = 0; i < current->childCount(); ++i)
{
stack.push(current->child(i));
}
if (advanced_mode_)
{
current->setHidden(false); //show all nodes in advanced mode
}
else
{
node_stack.push(current); //store node pointers in normal mode
}
}
}
//hide sections that have no visible items in normal mode
while (!node_stack.empty())
{
QTreeWidgetItem * current = node_stack.top();
node_stack.pop();
bool has_visible_children = false;
for (Int i = 0; i < current->childCount(); ++i)
{
if (!current->child(i)->isHidden())
{
has_visible_children = true;
break;
}
}
if (!has_visible_children)
{
current->setHidden(true);
}
}
//resize columns
tree_->resizeColumnToContents(0);
tree_->resizeColumnToContents(1);
tree_->resizeColumnToContents(2);
tree_->resizeColumnToContents(3);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/MISC/FilterableList.cpp | .cpp | 3,510 | 118 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/MISC/FilterableList.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/Qt5Port.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <ui_FilterableList.h>
using namespace std;
namespace OpenMS
{
namespace Internal
{
FilterableList::FilterableList(QWidget *parent) :
QWidget(parent),
ui_(new Ui::FilterableList)
{
ui_->setupUi(this);
connect(ui_->filter_text, &QLineEdit::textChanged, this, &FilterableList::filterEdited_);
// forward double-clicked signal to outside
connect(ui_->list_items, &QListWidget::itemDoubleClicked, [&](QListWidgetItem* item) {
emit itemDoubleClicked(item);
});
}
FilterableList::~FilterableList()
{
delete ui_;
}
void FilterableList::setItems(const QStringList& items)
{
items_ = items;
updateInternalList_();
}
void FilterableList::setBlacklistItems(const QStringList& bl_items)
{
blacklist_ = toQSet(bl_items);
updateInternalList_();
}
void FilterableList::addBlackListItems(const QStringList& items)
{
blacklist_.unite(toQSet(items));
updateInternalList_();
}
void FilterableList::removeBlackListItems(const QStringList& outdated_blacklist_items)
{
for (const auto& bl : outdated_blacklist_items)
{
if (!blacklist_.contains(bl))
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value '" + String(bl) + "' cannot be taken from blacklist. Does not belong to set!", bl.toStdString());
}
}
// remove all items from blacklist
blacklist_.subtract(toQSet(outdated_blacklist_items));
updateInternalList_();
}
QStringList FilterableList::getSelectedItems() const
{
QStringList items;
for (const auto& item : ui_->list_items->selectedItems()) items << item->text();
return items;
}
QStringList FilterableList::getAllVisibleItems() const
{
QStringList items;
for (int row = 0; row < ui_->list_items->count(); ++row) items << ui_->list_items->item(row)->text();
return items;
}
void FilterableList::filterEdited_(const QString& filter_text)
{
// update list of visible items
updateVisibleList_();
// let outside world know about it
emit filterChanged(filter_text);
}
void FilterableList::updateInternalList_()
{
items_wo_bl_ = items_;
// quadratic runtime, but maintains order of items (as opposed to converting to set)
for (const auto& bl : blacklist_)
{
if (items_wo_bl_.removeAll(bl) == 0)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value does not belong to set!", bl.toStdString());
}
}
updateVisibleList_();
}
void FilterableList::updateVisibleList_()
{
QRegularExpression regex(ui_->filter_text->text(), QRegularExpression::CaseInsensitiveOption);
ui_->list_items->clear();
ui_->list_items->addItems(items_wo_bl_.filter(regex));
}
} //namespace Internal
} //namspace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/MISC/GUIHelpers.cpp | .cpp | 9,629 | 325 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/SYSTEM/File.h>
#include <QDesktopServices>
#include <QGuiApplication>
#include <QMessageBox>
#include <QPainter>
#include <QPoint>
#include <QPointF>
#include <QProcess>
#include <QRectF>
#include <QString>
#include <QStringList>
#include <QtWidgets/QFileDialog>
#include <QUrl>
namespace OpenMS
{
void GUIHelpers::openFolder(const QString& folder)
{
#if defined(__APPLE__)
QProcess p;
p.setProcessChannelMode(QProcess::ForwardedChannels);
p.start("/usr/bin/open", QStringList() << folder);
if (!p.waitForStarted())
{
// execution failed
QMessageBox::warning(0, "Open Folder Error", "The folder '" + folder + "' could not be opened!");
OPENMS_LOG_ERROR << "Failed to open folder '" << folder.toStdString() << "'" << std::endl;
OPENMS_LOG_ERROR << p.errorString().toStdString() << std::endl;
}
#else
if (!QDir(folder).exists() || (!QDesktopServices::openUrl(QUrl("file:///" + folder, QUrl::TolerantMode))))
{
QMessageBox::warning(nullptr, "Open Folder Error", "The folder '" + folder + "' could not be opened!");
}
#endif
}
OPENMS_GUI_DLLAPI QString GUIHelpers::getSaveFilename(QWidget* parent, const QString& caption, const QString& dir, const FileTypeList& supported_file_types, bool add_all_filter,
const FileTypes::Type fallback_extension)
{
QString selected_filter;
QString file_name = QFileDialog::getSaveFileName(parent, caption, dir, supported_file_types.toFileDialogFilter(FilterLayout::ONE_BY_ONE, add_all_filter).toQString(), &selected_filter);
if (file_name.isEmpty())
{
return file_name;
}
// check whether a file type suffix has been given, or fall back to @p fallback_extension (if 'all filter' was used)
file_name = FileHandler::swapExtension(file_name, supported_file_types.fromFileDialogFilter(selected_filter, fallback_extension)).toQString();
return file_name;
}
bool GUIHelpers::startTOPPView(QStringList args)
{
QString app_path;
#if defined(__APPLE__)
// check if we can find the TOPPView.app
app_path = (File::getExecutablePath() + "../../../TOPPView.app").toQString();
if (File::exists(app_path))
{
// we found the app
QStringList app_args;
app_args.append("-a");
app_args.append(app_path);
app_args.append("--args");
app_args.append(args);
args = app_args;
app_path = "/usr/bin/open";
}
else
{ // we could not find the app, try it the Linux way
app_path = (File::findSiblingTOPPExecutable("TOPPView")).toQString();
}
#else
// LINUX+WIN
app_path = (File::findSiblingTOPPExecutable("TOPPView")).toQString();
#endif
if (!QProcess::startDetached(app_path, args))
{
// execution failed
OPENMS_LOG_ERROR << "Could not start '" << app_path.toStdString() << "'. Please see above for error messages." << std::endl;
#if defined(__APPLE__)
OPENMS_LOG_ERROR << "Please check if TOPPAS and TOPPView are located in the same directory" << std::endl;
#endif
return false;
}
return true;
}
void GUIHelpers::openURL(const QString& target)
{
QUrl url_target;
// add protocol handler if none is given
if (!(target.startsWith("http://") || target.startsWith("https://")))
{
// we expect all unqualified urls to be file urls
try
{
String local_url = File::findDoc(target);
url_target = QUrl::fromLocalFile(local_url.toQString());
}
catch (Exception::FileNotFound&)
{
// we fall back to the web url
url_target = QUrl(QString("http://www.openms.de/current_doxygen/%1").arg(target), QUrl::TolerantMode);
}
}
else
{
url_target = QUrl(target, QUrl::TolerantMode);
}
if (!QDesktopServices::openUrl(url_target))
{
QMessageBox::warning(nullptr,
QObject::tr("Error"),
QObject::tr("Unable to open\n") + target +
QObject::tr("\n\nPossible reason: security settings or misconfigured Operating System"));
}
}
void GUIHelpers::drawText(QPainter& painter, const QStringList& text, const QPoint& where, const QColor& col_fg, const QColor& col_bg, const QFont& f)
{
painter.save();
// font
painter.setFont(f);
int line_spacing;
QRectF dim = getTextDimension(text, painter.font(), line_spacing);
// draw background for text
if (col_bg.isValid()) painter.fillRect(where.x(), where.y(), dim.width(), dim.height(), col_bg);
// draw text
if (col_fg.isValid()) painter.setPen(col_fg);
for (int i = 0; i < text.size(); ++i)
{
painter.drawText(where.x() + 1, where.y() + (i + 1) * line_spacing, text[i]);
}
painter.restore();
}
QRectF GUIHelpers::getTextDimension(const QStringList& text, const QFont& f, int& line_spacing)
{
// determine width and height of the box we need
QFontMetrics metrics(f);
line_spacing = metrics.lineSpacing();
int height = 6 + text.size() * line_spacing;
int width = 4;
for (int i = 0; i < text.size(); ++i)
{
width = std::max(width, 4 + metrics.horizontalAdvance(text[i]));
}
return QRectF(0, 0, width, height);
}
QPointF GUIHelpers::nearestPoint(const QPointF& origin, const QList<QPointF>& list)
{
if (list.empty())
{
return QPointF();
}
QPointF nearest = list.first();
qreal min_distance = (std::numeric_limits<qreal>::max)();
for (QList<QPointF>::const_iterator it = list.begin(); it != list.end(); ++it)
{
qreal sqr_distance = (it->x() - origin.x()) * (it->x() - origin.x()) + (it->y() - origin.y()) * (it->y() - origin.y());
if (sqr_distance < min_distance)
{
min_distance = sqr_distance;
nearest = *it;
}
}
return nearest;
}
QPointF GUIHelpers::intersectionPoint(const QRectF& rect, const QPointF& p)
{
if (rect.contains(p))
return rect.center();
QPointF delta = rect.center() - p;
qreal slope;
if (delta.x() == 0)
{
slope = std::numeric_limits<qreal>::infinity();
}
else
{
slope = delta.y() / delta.x();
}
qreal y_1 = p.y() + slope * (rect.left() - p.x());
qreal y_2 = p.y() + slope * (rect.right() - p.x());
slope = 1.0 / slope;
qreal x_3 = p.x() + slope * (rect.top() - p.y());
qreal x_4 = p.x() + slope * (rect.bottom() - p.y());
QList<QPointF> point_list;
if (y_1 <= rect.bottom() && y_1 >= rect.top())
{
point_list.push_back(QPointF(rect.left(), y_1));
}
if (y_2 <= rect.bottom() && y_2 >= rect.top())
{
point_list.push_back(QPointF(rect.right(), y_2));
}
if (x_3 <= rect.right() && x_3 >= rect.left())
{
point_list.push_back(QPointF(x_3, rect.top()));
}
if (x_4 <= rect.right() && x_4 >= rect.left())
{
point_list.push_back(QPointF(x_4, rect.bottom()));
}
return nearestPoint(p, point_list);
}
StringList GUIHelpers::convert(const QStringList& in)
{
StringList out;
for (const auto& s : in) out.push_back(s);
return out;
}
QStringList GUIHelpers::convert(const StringList& in)
{
QStringList out;
for (const auto& s : in) out.push_back(s.toQString());
return out;
}
GUIHelpers::GUILock::GUILock(QWidget* gui)
: locked_widget_(gui)
{
lock();
}
GUIHelpers::GUILock::~GUILock()
{
unlock();
}
void GUIHelpers::GUILock::lock()
{
if (currently_locked_) return;
if (locked_widget_ == nullptr) return;
was_enabled_ = locked_widget_->isEnabled();
locked_widget_->setEnabled(false);
QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
currently_locked_ = true;
}
void GUIHelpers::GUILock::unlock()
{
if (!currently_locked_) return;
if (locked_widget_ == nullptr) return;
locked_widget_->setEnabled(was_enabled_);
QGuiApplication::restoreOverrideCursor();
currently_locked_ = false;
}
GUIHelpers::OverlapDetector::OverlapDetector(int levels)
{
if (levels <= 0)
throw Exception::InvalidSize(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, levels, "levels must be positive");
rows_.resize(levels, 0);
}
size_t GUIHelpers::OverlapDetector::placeItem(double x_start, double x_end)
{
if (x_start < 0)
OPENMS_LOG_WARN << "Warning: x coordinates should be positive!\n";
if (x_start > x_end)
OPENMS_LOG_WARN << "Warning: x-end is larger than x-start!\n";
size_t best_index = 0;
double best_distance = std::numeric_limits<double>::max();
for (size_t i = 0; i < rows_.size(); ++i)
{
if (rows_[i] < x_start)
{ // easy win; row[i] does not overlap; take it
rows_[i] = x_end; // update space for next call
return i;
}
// x_start is smaller than row's end...
if ((rows_[i] - x_start) < best_distance)
{
best_distance = rows_[i] - x_start;
best_index = i;
}
}
rows_[best_index] = x_end; // update space for next call
return best_index;
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/MISC/ExternalProcessMBox.cpp | .cpp | 1,904 | 53 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/VISUAL/MISC/ExternalProcessMBox.h>
#include <QMessageBox>
#include <utility>
namespace OpenMS
{
/// default Ctor; callbacks for stdout/stderr are empty
ExternalProcessMBox::ExternalProcessMBox() = default;
ExternalProcessMBox::ExternalProcessMBox(std::function<void(const String&)> callbackStdOut, std::function<void(const String&)> callbackStdErr)
: ep_(std::move(callbackStdOut), std::move(callbackStdErr))
{
}
ExternalProcessMBox::~ExternalProcessMBox() = default;
/// re-wire the callbacks used using run()
void ExternalProcessMBox::setCallbacks(std::function<void(const String&)> callbackStdOut, std::function<void(const String&)> callbackStdErr)
{
ep_.setCallbacks(std::move(callbackStdOut), std::move(callbackStdErr));
}
ExternalProcess::RETURNSTATE ExternalProcessMBox::run(QWidget* parent, const QString& exe, const QStringList& args, const QString& working_dir, const bool verbose, String& error_msg)
{
auto rs = ep_.run(exe, args, working_dir, verbose, error_msg);
QMessageBox::critical(parent, "Error", error_msg.toQString());
return rs;
}
ExternalProcess::RETURNSTATE ExternalProcessMBox::run(QWidget* parent, const QString& exe, const QStringList& args, const QString& working_dir, const bool verbose)
{
String error_msg;
auto rs = ep_.run(exe, args, working_dir, verbose, error_msg);
if (!error_msg.empty()) QMessageBox::critical(parent, "Error", error_msg.toQString());
return rs;
}
} // ns OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/MISC/CommonDefs.cpp | .cpp | 465 | 18 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/MISC/CommonDefs.h>
namespace OpenMS
{
// nothing to see here (yet)
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/INTERFACES/IPeptideIds.cpp | .cpp | 515 | 19 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/INTERFACES/IPeptideIds.h>
using namespace std;
namespace OpenMS
{
// just an interface. No implementation here...
} // namespace OpenMS
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.