diff --git a/plasmoid/applet/bodr/kalzium_plasma.cpp b/plasmoid/applet/bodr/kalzium_plasma.cpp index fd41dc0e..bb522da6 100644 --- a/plasmoid/applet/bodr/kalzium_plasma.cpp +++ b/plasmoid/applet/bodr/kalzium_plasma.cpp @@ -1,183 +1,196 @@ /*************************************************************************** copyright : (C) 2008 by Carsten Niehaus email : cniehaus@kde.org Copyright 2008 Frederik Gladhorn ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "kalzium_plasma.h" -#include #include #include -#include +#include +#include #include #include #include #include +#include +#include +#include KalziumPlasma::KalziumPlasma(QObject *parent, const QVariantList &args) : Plasma::Applet(parent, args), m_dialog(0), m_font(QFont()) { m_theme.setImagePath("widgets/testtube"), m_engine = dataEngine("kalzium"); m_dialog = 0; m_label1 = 0; m_lineedit = new Plasma::LineEdit(this); m_lineedit->setDefaultText(i18n("Enter the atomic number.")); connect(m_lineedit, SIGNAL(editingFinished()), this, SLOT(textChanged())); setHasConfigurationInterface(true); setAcceptDrops(false); setAcceptsHoverEvents(true); // setDrawStandardBackground(false); resize(385,177); } void KalziumPlasma::init() { qDebug() << "initializing Kalzium"; configChanged(); m_currentSource = "BlueObelisk:RandomElement"; // connect to random source and update ever 5 seconds m_engine->connectSource(m_currentSource, this, 5000); m_theme.setContainsMultipleImages(false); m_label1 = new QGraphicsTextItem(this); m_label1->setPos(m_theme.elementRect("name").topLeft()); m_label1->setFont(m_font); m_label1->setDefaultTextColor(Qt::white); } void KalziumPlasma::configChanged() { KConfigGroup cg = config(); m_font = cg.readEntry("font",QFont()); } void KalziumPlasma::constraintsUpdated(Plasma::Constraints constraints) { // setDrawStandardBackground(false); prepareGeometryChange(); if (constraints & Plasma::SizeConstraint) { //m_theme.resize(contentSize().toSize()); m_theme.resize(size()); } m_label1->setPos(m_theme.elementRect("canvas").topLeft()); } KalziumPlasma::~KalziumPlasma() { delete m_dialog; } void KalziumPlasma::dataUpdated(const QString& source, const Plasma::DataEngine::Data &data) { qDebug() << "dataUpdated" << source; if (source != m_currentSource) { return; } QString bp = data["bp"].toString(); QString mp = data["mp"].toString(); QString mass = data["mass"].toString(); QString symbol = data["symbol"].toString(); QString name = data["name"].toString(); QString text; text = QString(i18n("\nName: %1", name)); text.append(QString(i18n("\nSymbol: %1", symbol))); text.append(QString(i18n("\nBoiling point: %1", bp))); text.append(QString(i18n("\nMelting point: %1", mp))); text.append(QString(i18n("\nMass: %1", mass))); if (m_label1) { // m_label1->setAlignment(Qt::AlignLeft); m_label1->setPlainText(text); } } void KalziumPlasma::paintInterface(QPainter *p, const QStyleOptionGraphicsItem *option, const QRect &contentsRect) { Q_UNUSED(option); p->setRenderHint(QPainter::SmoothPixmapTransform); p->setRenderHint(QPainter::Antialiasing); // Now we draw the applet, starting with our svg //m_theme.resize((int)contentsRect.width(), (int)contentsRect.height()); m_theme.resize(size()); //m_theme.paint(p, (int)contentsRect.left(), (int)contentsRect.top()); m_theme.paint(p, 0, 0); m_lineedit->setPos(0, 150); } void KalziumPlasma::showConfigurationInterface() { if (m_dialog == 0) { - m_dialog = new KDialog; + m_dialog = new QDialog; m_dialog->setWindowIcon(QIcon::fromTheme("kalzium")); - m_dialog->setCaption(i18n("KalziumPlasma Configuration")); + m_dialog->setWindowTitle(i18n("KalziumPlasma Configuration")); ui.setupUi(m_dialog->mainWidget()); m_dialog->mainWidget()->layout()->setMargin(0); - m_dialog->setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Apply); - connect(m_dialog, SIGNAL(applyClicked()), - this, SLOT(configAccepted())); - connect(m_dialog, SIGNAL(okClicked()), - this, SLOT(configAccepted())); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Apply); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + m_dialog->setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + m_dialog->connect(buttonBox, &QDialogButtonBox::accepted, this, &KalziumPlasma::accept); + m_dialog->connect(buttonBox, &QDialogButtonBox::rejected, this, &KalziumPlasma::reject); + mainLayout->addWidget(buttonBox); + connect(okButton, &QPushButton::clicked, + this, &KalziumPlasma::configAccepted); + connect(buttonBox, &QDialogButtonBox::Apply::clicked, + this, &KalziumPlasma::configAccepted); connect(ui.fontSelectButton, SIGNAL(clicked()), this, SLOT(showFontSelectDlg())); } m_dialog->show(); } void KalziumPlasma::showFontSelectDlg() { KFontDialog::getFont(m_font); } void KalziumPlasma::configAccepted() { prepareGeometryChange(); KConfigGroup cg = config(); cg.writeEntry("font", m_font); m_label1->setFont(m_font); emit configNeedsSaving(); } void KalziumPlasma::textChanged() { m_engine->disconnectSource(m_currentSource, this); QString currentText = m_lineedit->toPlainText(); if (!currentText.isEmpty()) { // simply assume the user entered the atomic number of the element m_currentSource = QString("BlueObelisk:Element:") + currentText; } else { m_currentSource = QString("BlueObelisk:RandomElement"); } m_engine->connectSource(m_currentSource, this, 5000); } #include "kalzium_plasma.moc" diff --git a/plasmoid/applet/bodr/kalzium_plasma.h b/plasmoid/applet/bodr/kalzium_plasma.h index 94083e2b..62061cfb 100644 --- a/plasmoid/applet/bodr/kalzium_plasma.h +++ b/plasmoid/applet/bodr/kalzium_plasma.h @@ -1,68 +1,68 @@ /*************************************************************************** copyright : (C) 2008 by Carsten Niehaus email : cniehaus@kde.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef KALZIUM_PLASMA_H #define KALZIUM_PLASMA_H #include #include #include #include #include #include "ui_config.h" -class KDialog; +class QDialog; class QFont; class KalziumPlasma : public Plasma::Applet { Q_OBJECT public: KalziumPlasma(QObject *parent, const QVariantList &args); ~KalziumPlasma(); void init(); void paintInterface(QPainter *painter, const QStyleOptionGraphicsItem *option, const QRect& contentsRect); void constraintsUpdated(Plasma::Constraints constraints); public slots: void showConfigurationInterface(); void configAccepted(); void showFontSelectDlg(); void dataUpdated(const QString &name, const Plasma::DataEngine::Data &data); void textChanged(); void configChanged(); private: Plasma::Svg m_theme; QGraphicsTextItem *m_label1; Plasma::LineEdit *m_lineedit; Plasma::DataEngine* m_engine; QString m_currentSource; Ui::config ui; - KDialog *m_dialog; + QDialog *m_dialog; QFont m_font; }; K_EXPORT_PLASMA_APPLET(data_kalzium, KalziumPlasma) #endif // KALZIUM_PLASMA_H diff --git a/plasmoid/applet/concentrationPlasmoid/concentrationCalculator.cpp b/plasmoid/applet/concentrationPlasmoid/concentrationCalculator.cpp index ac7f55ba..e9cc1869 100644 --- a/plasmoid/applet/concentrationPlasmoid/concentrationCalculator.cpp +++ b/plasmoid/applet/concentrationPlasmoid/concentrationCalculator.cpp @@ -1,1308 +1,1311 @@ /*************************************************************************** copyright : (C) 2009 by Kashyap R Puranik email : kashthealien@gmail.com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "concentrationCalculator.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include using namespace KUnitConversion; concentrationCalculator::concentrationCalculator(QObject *parent, const QVariantList &args) : Plasma::PopupApplet(parent, args) , m_widget(0) { m_converter = new Converter(this); setAspectRatioMode(Plasma::IgnoreAspectRatio); setPopupIcon("accessories-calculator"); setHasConfigurationInterface(true); setAssociatedApplication("kalzium"); resize(700, 400); } concentrationCalculator::~concentrationCalculator() { if (hasFailedToLaunch()) { // Do some cleanup here } else { // Save settings } } void concentrationCalculator::init() { configChanged(); } void concentrationCalculator::configChanged() { KConfigGroup cg = config(); m_soluteMass = cg.readEntry("soluteMass",true); m_solventVolume = cg.readEntry("solventVolume",true); } QGraphicsWidget *concentrationCalculator::graphicsWidget() { //FIXME: // 1.> Currently the spin boxes are integer, please convert them into double // and uncomment certain lines of code which say 'setDecimals(4)' if (!m_widget) { m_widget = new QGraphicsWidget(this); m_widget->setMinimumSize(600, 350); // setup the label Plasma::Frame *pHeader = new Plasma::Frame(this); pHeader->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); pHeader->setText(i18n("Concentration Calculator")); //setup the layout QGraphicsLinearLayout *pVLayout = new QGraphicsLinearLayout(Qt::Vertical,m_widget); Plasma::GroupBox *pGroupBox1 = new Plasma::GroupBox(this); QGraphicsGridLayout *pGridLayout = new QGraphicsGridLayout(pGroupBox1); pGridLayout->addItem(pHeader, 0, 0, 1, 4); pVLayout->addItem(pGroupBox1); // Set up the user interface // 1 Calculation mode Plasma::Label *calcModeLabel = new Plasma::Label(this); calcModeLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); calcModeLabel->setText(i18n("Calculation Mode:")); m_calculationMode = new Plasma::ComboBox(this); m_calculationMode->setZValue(3); m_calculationMode->nativeWidget()->insertItems(0, QStringList() << i18n("Amount Solute") << i18n("Molar Mass of Solute") << i18n("Equivalent Mass") << i18n("Amount Solvent") << i18n("Molar Mass of Solvent") << i18n("Concentration") ); pGridLayout->addItem(calcModeLabel, 1, 0); pGridLayout->addItem(m_calculationMode, 1, 1); // 2 amount solute Plasma::Label *amtSltLabel = new Plasma::Label(this); amtSltLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); amtSltLabel->setText(i18n("Amount of solute:")); m_amountSolute = new Plasma::SpinBox(this); m_amountSolute->nativeWidget()->setMaximum(1000000000); //amtSolute->setDecimals(4); m_amountSolute->setMaximum(1e+09); m_amountSoluteType = new Plasma::ComboBox(this); m_amountSoluteType->setZValue(2); m_amountSoluteType->nativeWidget()->insertItems(0, QStringList() << i18n("Mass") << i18n("volume") << i18n("moles") ); m_amountSoluteUnit = new Plasma::ComboBox(this); m_amountSoluteUnit->setZValue(6); m_amountSoluteUnit->nativeWidget()->insertItems(0, QStringList() << i18n("grams") << i18n("tons") << i18n("carats") << i18n("pounds") << i18n("ounces") << i18n("troy ounces") ); pGridLayout->addItem(amtSltLabel, 2, 0); pGridLayout->addItem(m_amountSolute, 2, 1); pGridLayout->addItem(m_amountSoluteType, 2, 3); pGridLayout->addItem(m_amountSoluteUnit, 2, 2); // 3 molar mass solute Plasma::Label *molarMassLabel = new Plasma::Label(this); molarMassLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); molarMassLabel->setText(i18n("Molar mass of solute:")); m_molarMass = new Plasma::SpinBox(this); m_molarMass->nativeWidget()->setMaximum(1000000000); //m_MolarMass->setDecimals(4); m_molarMass->setMaximum(1e+09); Plasma::Label *molarMassUnit = new Plasma::Label(this); molarMassUnit->nativeWidget()->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); molarMassUnit->setText(i18n("u (mass)")); pGridLayout->addItem(molarMassLabel, 3, 0); pGridLayout->addItem(m_molarMass, 3, 1); pGridLayout->addItem(molarMassUnit, 3, 2); // 4 equivalent mass solute Plasma::Label *eqtMassLabel = new Plasma::Label(this); eqtMassLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); eqtMassLabel->setText(i18n("Equivalent mass of solute:")); m_eqtMass = new Plasma::SpinBox(this); m_eqtMass->nativeWidget()->setMaximum(1000000000); //m_eqtMass->setDecimals(4); m_eqtMass->setMaximum(1e+09); Plasma::Label *eqtMassUnit = new Plasma::Label(this); eqtMassUnit->nativeWidget()->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); eqtMassUnit->setText(i18n("u (mass)")); pGridLayout->addItem(eqtMassLabel, 4, 0); pGridLayout->addItem(m_eqtMass, 4, 1); pGridLayout->addItem(eqtMassUnit, 4, 2); // 5 density solute Plasma::Label *densitySoluteLabel = new Plasma::Label(this); densitySoluteLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); densitySoluteLabel->setText(i18n("Density of solute:")); m_densitySolute = new Plasma::SpinBox(this); m_densitySolute->nativeWidget()->setMaximum(1000000000); //m_densitySolute->setDecimals(4); m_densitySolute->setMaximum(1e+09); m_densitySoluteUnit = new Plasma::ComboBox(this); m_densitySoluteUnit->setZValue(5); m_densitySoluteUnit->nativeWidget()->insertItems(0, QStringList() << i18n("grams per liter") << i18n("grams per milliliter") << i18n("kilograms per cubic meter") << i18n("kilograms per liter") << i18n("ounces per cubic inch") << i18n("ounces per cubic foot") << i18n("pounds per cubic inch") << i18n("pounds per cubic foot") << i18n("pounds per cubic yard") ); pGridLayout->addItem(densitySoluteLabel, 5, 0); pGridLayout->addItem(m_densitySolute, 5, 1); pGridLayout->addItem(m_densitySoluteUnit, 5, 2); // 6 amount solvent Plasma::Label *amtSlvtLabel = new Plasma::Label(this); amtSlvtLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); amtSlvtLabel->setText(i18n("Amount of solvent:")); m_amountSolvent = new Plasma::SpinBox(this); m_amountSolvent->nativeWidget()->setMaximum(1000000000); //m_amountSolvent->setDecimals(4); m_amountSolvent->setMaximum(1e+09); m_amountSolventType = new Plasma::ComboBox(this); m_amountSolventType->setZValue(2); m_amountSolventType->nativeWidget()->insertItems(0, QStringList() << i18n("volume") << i18n("Mass") << i18n("moles") ); m_amountSolventType->setZValue(3); m_amountSolventUnit = new Plasma::ComboBox(this); m_amountSolventUnit->setZValue(4); m_amountSolventUnit->nativeWidget()->insertItems(0, QStringList() << i18n("liter") << i18n("cubic meters") << i18n("cubic feet") << i18n("cubic inch") << i18n("cubic mile") << i18n("fluid ounce") << i18n("cups") << i18n("gallons") << i18n("pints") ); pGridLayout->addItem(amtSlvtLabel, 6, 0); pGridLayout->addItem(m_amountSolvent, 6, 1); pGridLayout->addItem(m_amountSolventType, 6, 3); pGridLayout->addItem(m_amountSolventUnit, 6, 2); // 7 molar mass solvent Plasma::Label *molarMassSolvtLabel = new Plasma::Label(this); molarMassSolvtLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); molarMassSolvtLabel->setText(i18n("Molar mass of solvent:")); m_molarMassSolvent = new Plasma::SpinBox(this); m_molarMassSolvent->nativeWidget()->setMaximum(1000000000); //m_MolarMassSolvent->setDecimals(4); m_molarMassSolvent->setMaximum(1e+09); Plasma::Label *molarMassSolvtUnit = new Plasma::Label(this); molarMassSolvtUnit->nativeWidget()->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); molarMassSolvtUnit->setText(i18n("u (mass)")); pGridLayout->addItem(molarMassSolvtLabel, 7, 0); pGridLayout->addItem(m_molarMassSolvent, 7, 1); pGridLayout->addItem(molarMassSolvtUnit, 7, 2); // 8 density of solvent Plasma::Label *densitySolventLabel = new Plasma::Label(this); densitySolventLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); densitySolventLabel->setText(i18n("Density of solvent:")); m_densitySolvent = new Plasma::SpinBox(this); m_densitySolvent->nativeWidget()->setMaximum(1000000000); //m_densitySolvent->setDecimals(4); m_densitySolvent->setMaximum(1e+09); m_densitySolventUnit = new Plasma::ComboBox(this); m_densitySolventUnit->setZValue(3); m_densitySolventUnit->nativeWidget()->insertItems(0, QStringList() << i18n("grams per liter") << i18n("grams per milliliter") << i18n("kilograms per cubic meter") << i18n("kilograms per liter") << i18n("ounces per cubic inch") << i18n("ounces per cubic foot") << i18n("pounds per cubic inch") << i18n("pounds per cubic foot") << i18n("pounds per cubic yard") ); pGridLayout->addItem(densitySolventLabel, 8, 0); pGridLayout->addItem(m_densitySolvent, 8, 1); pGridLayout->addItem(m_densitySolventUnit, 8, 2); // 9 Concentration Plasma::Label *concentrationLabel = new Plasma::Label(this); concentrationLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); concentrationLabel->setText(i18n("Concentration:")); m_concentration = new Plasma::SpinBox(this); m_concentration->nativeWidget()->setMaximum(1000000000); //m_concentration->setDecimals(4); m_concentration->setMaximum(1e+09); m_concentrationUnit = new Plasma::ComboBox(this); m_concentrationUnit->setZValue(2); m_concentrationUnit->nativeWidget()->insertItems(0, QStringList() << i18n("molar") << i18n("Normal") << i18n("molal") << i18n("% ( mass )") << i18n("% ( volume )") << i18n("% ( moles )") ); pGridLayout->addItem(concentrationLabel, 9, 0); pGridLayout->addItem(m_concentration, 9, 1); pGridLayout->addItem(m_concentrationUnit, 9, 2); // 11 reset m_reset = new Plasma::PushButton(this); m_reset->setText(i18n("Reset")); pGridLayout->addItem(m_reset, 10, 0); // 10 Results m_error = new Plasma::Label(this); pGridLayout->addItem(m_error, 10, 1, 4, 1); // Done adding elements to the UI, now initialise reset(); // Connect signals with slots (when a change of selection in the UI takes place, // corresponding quantity should be updated in the class.) connect(m_amountSolute, SIGNAL(valueChanged(int)), this, SLOT(amountSoluteChanged())); connect(m_amountSoluteType->nativeWidget(), SIGNAL(activated(int)), this, SLOT(amountSoluteTypeChanged())); connect(m_amountSoluteUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(amountSoluteChanged())); connect(m_molarMass, SIGNAL(valueChanged(int)), this, SLOT(molarMassChanged(int))); connect(m_eqtMass, SIGNAL(valueChanged(int)), this, SLOT(eqtMassChanged(int))); connect(m_densitySolute, SIGNAL(valueChanged(int)), this, SLOT(densitySoluteChanged())); connect(m_densitySoluteUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(densitySoluteChanged())); connect(m_amountSolvent, SIGNAL(valueChanged(int)), this, SLOT(amountSolventChanged())); connect(m_amountSolventType->nativeWidget(), SIGNAL(activated(int)), this, SLOT(amountSolventTypeChanged())); connect(m_amountSolventUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(amountSolventChanged())); connect(m_amountSolventUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(amountSolventChanged())); connect(m_molarMassSolvent, SIGNAL(valueChanged(int)), this, SLOT(molarMassSolventChanged(int))); connect(m_densitySolvent, SIGNAL(valueChanged(int)), this, SLOT(densitySolventChanged())); connect(m_densitySolventUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(densitySolventChanged())); connect(m_concentration, SIGNAL(valueChanged(int)), this, SLOT(concentrationChanged(int))); connect(m_concentrationUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(concentrationChanged(int))); connect(m_calculationMode->nativeWidget(), SIGNAL(activated(int)), this, SLOT(setMode(int))); connect(m_reset, SIGNAL(clicked()), this, SLOT(reset())); /**************************************************************************/ // concentration Calculator setup complete /**************************************************************************/ } return m_widget; } void concentrationCalculator::reset() { /**************************************************************************/ // concentration Calculator set up /**************************************************************************/ error(RESET_CONC_MESG); // initialise the initially selected values m_amountSolute ->setValue(117.0); m_molarMass ->setValue(58.5); m_eqtMass ->setValue(58.5); m_densitySolute ->setValue(2.7); m_amountSolvent ->setValue(1.0); m_molarMassSolvent ->setValue(18.0); m_densitySolvent ->setValue(1000.0); m_concentration ->setValue(2.0); m_mode = 5; // Setup of the UI done // Initialise values m_AmtSolute = Value(117.0, "grams"); m_AmtSolvent = Value(1.0, "liter"); m_MolarMass = 58.5; m_EqtMass = 58.5; m_MolesSolute = 2.0; m_MolesSolvent = 55.5; m_MolarMassSolvent = 18.0; m_DensitySolute = Value(2.7, "grams per milliliter"); m_Concentration = 2.0; m_DensitySolvent = Value(1000.0, "grams per liter"); m_amountSoluteType ->nativeWidget()->setCurrentIndex(0); m_amountSolventType ->nativeWidget()->setCurrentIndex(0); m_amountSoluteUnit ->nativeWidget()->setCurrentIndex(0); m_amountSolventUnit ->nativeWidget()->setCurrentIndex(0); m_densitySolventUnit ->nativeWidget()->setCurrentIndex(0); m_densitySoluteUnit ->nativeWidget()->setCurrentIndex(0); m_concentrationUnit ->nativeWidget()->setCurrentIndex(0); m_calculationMode ->nativeWidget()->setCurrentIndex(5); setMode(5); calculate(); // Initialisation of values done } // Calculates the amount of solute void concentrationCalculator::calculateAmountSolute() { int type1 = m_concentrationUnit->nativeWidget()->currentIndex(); int type2 = m_amountSoluteType->nativeWidget()->currentIndex(); double molesSolute, eqtsSolute, massSolute, volSolute; // variables int mode = 0; /* * mode = 1 (molesSolute) mode = 2 eqtsSolute, mode = 3 mass, 4 volume */ // Calculate the number of moles of the solute switch (type1) { // calculate the number of moles of solute case 0: // molarity specified molesSolute = m_Concentration * volumeSolvent(); mode = 1; break; // Calculate the number of equivalents of solute case 1: // Normality specified eqtsSolute = m_Concentration * volumeSolvent(); mode = 2; break; // Calculate the number of moles of solute case 2: // molality specified molesSolute = m_Concentration * massSolvent() / 1000.0; mode = 1; break; // Calculate the mass of solute case 3: // mass percentage specified if (m_Concentration >= 100.0) { error(PERCENTAGE_ZERO); } massSolute = m_Concentration / (100.0 - m_Concentration) * massSolvent(); mode = 3; break; // Calculate the volume of solute case 4: // volume percentage specified if (m_Concentration >= 100.0) { error(PERCENTAGE_ZERO); } volSolute = m_Concentration / (100.0 - m_Concentration) * volumeSolvent(); mode = 4; break; // Calculate the moles of solute case 5: //mole percentage specified if (m_Concentration >= 100.0) { error(PERCENTAGE_ZERO); } molesSolute = m_Concentration / (100.0 - m_Concentration) * molesSolvent(); mode = 1; break; default: break; } // We have the amount of solvent in some form (moles, equivalents, mass, volume etc) // Now we have to present it in the UI switch (type2) { case 0: // amount should be specified interms of mass switch (mode) { case 1: // we should get mass from moles massSolute = molesSolute * m_MolarMass; break; case 2: // we should obtain mass from number of equivalents massSolute = eqtsSolute * m_EqtMass; break; case 3: // we already know the mass of the solute break; case 4: // we should get the mass from volume massSolute = volSolute * densitySolute(); break; } // update mass of solute m_AmtSolute = Value(massSolute, "grams"); m_AmtSolute = (m_converter->convert(m_AmtSolute, \ m_amountSoluteUnit->nativeWidget()->currentText())); m_amountSolute->setValue(m_AmtSolute.number()); break; case 1: // amount should be specified in terms of volume // validate density if (densitySolute() == 0) { error(DENSITY_ZERO); return; } switch (mode) { case 1: // we should get the volume from moles volSolute = molesSolute * m_MolarMass / densitySolute(); break; case 2: // we should get the volume from equivalents volSolute = eqtsSolute * m_EqtMass / densitySolute(); break; case 3: // we should get the volume from mass volSolute = massSolute / densitySolute(); break; case 4: // we already know the volume break; } // update volume of solute m_AmtSolute = Value(volSolute, "liters"); m_AmtSolute = (m_converter->convert(m_AmtSolute, \ m_amountSoluteUnit->nativeWidget()->currentText())); m_amountSolute->setValue(m_AmtSolute.number()); break; case 2: // amount should be specified in terms of moles switch (mode) { case 1: // we already know the moles of solute break; case 2: // we should obtain moles from equivalents (not possible) molesSolute = 0.0; break; case 3: // we should obtain moles from mass molesSolute = massSolute / m_MolarMass; break; case 4: // we should obtain moles from volume molesSolute = volSolute * densitySolute() / m_MolarMass; break; } // Update the number of moles m_MolesSolute = molesSolute; m_amountSolute->setValue(molesSolute); break; } return; } // Calculates the molar mass void concentrationCalculator::calculateMolarMass() { // molarity / molality / mole fraction required int type = m_concentrationUnit->nativeWidget()->currentIndex(); int type2 = m_amountSolventType->nativeWidget()->currentIndex(); double numMoles; switch (type) { case 0: //molarity specified // number of moles = volume * concentration numMoles = volumeSolvent() * m_Concentration; break; case 1: // cannot be calculated (insufficient data) error(INSUFFICIENT_DATA_MOLE); return; break; case 2: // molality specified numMoles = massSolvent() / 1000.0 * m_Concentration; break; case 3: // cannot be calculated (insufficient data) case 4: error(INSUFFICIENT_DATA_MOLE); return; break; case 5: // mole fraction specified numMoles = m_Concentration / (100.0 - m_Concentration) * molesSolvent(); break; } if (type2 == 2) { // amount of solute is specified in moles, cannot calculate error(INSUFFICIENT_DATA_MOLES); return; } else { if (numMoles == 0.0) { error(MOLES_ZERO); return; } m_MolarMass = massSolute() / numMoles; m_molarMass->setValue(m_MolarMass); } } // Calculates the equivalent mass void concentrationCalculator::calculateEqtMass() { // Normality required int type = m_concentrationUnit->nativeWidget()->currentIndex(); int type2 = m_amountSoluteType->nativeWidget()->currentIndex(); double numEqts; switch (type) { // Normality required case 0: // molarity not sufficient error(INSUFFICIENT_DATA_EQT); return; break; case 1: // normality specified numEqts = volumeSolvent() * m_Concentration; break; case 2: case 3: case 4: case 5: error(INSUFFICIENT_DATA_EQT); return; break; } if (type2 == 2) { // Amount of solute specified in moles, cannot calculate error(INSUFFICIENT_DATA_MOLES); } else { if (numEqts == 0.0) { error(EQTS_ZERO); return; } m_EqtMass = massSolute() / numEqts; m_eqtMass->setValue(m_EqtMass); } return; } // Calculates the calculate molar mass of the solvent void concentrationCalculator::calculateMolarMassSolvent() { // molarity / molality / mole fraction required int type = m_concentrationUnit->nativeWidget()->currentIndex(); int type2 = m_amountSolventType->nativeWidget()->currentIndex(); double numMoles; switch (type) { case 0: // molarity specified case 1: // normality specified case 2: // molality specified case 3: // mass fraction specified case 4: // volume fraction specified error(INSUFFICIENT_DATA_SOLVENT); return; break; // cannot be calculated (insufficient data) case 5: // mole fraction specified numMoles = (100.0 - m_Concentration) / m_Concentration * molesSolute(); break; } if (type2 == 2) { // amount specified in moles error(INSUFFICIENT_DATA_MOLES); } else { m_MolarMassSolvent = massSolvent() / numMoles; m_molarMassSolvent->setValue(m_MolarMassSolvent); } return; } // Calculates the amount of solvent void concentrationCalculator::calculateAmountSolvent() { int type1 = m_concentrationUnit->nativeWidget()->currentIndex(); int type2 = m_amountSolventType->nativeWidget()->currentIndex(); double moleSolvent, massSolvent, volSolvent; int mode = 0; // Indicates the mode in which we have calculated the amount of solvent /* * mode = 1 (molessolvent) mode = 2 eqtssolvent, mode = 3 mass, 4 volume */ // Calculate the number of moles of the solvent if (m_Concentration == 0.0) { error(CONC_ZERO); return; } switch (type1) { // calculate the number of moles of solvent case 0: // molarity specified volSolvent = molesSolute() / m_Concentration; mode = 3; break; // Calculate the number of equivalents of solvent case 1: // Normality specified volSolvent = eqtsSolute() / m_Concentration; mode = 3; break; // Calculate the number of moles of solvent case 2: // molality specified massSolvent = molesSolute() * 1000.0 / m_Concentration; mode = 2; break; // Calculate the mass of solvent case 3: // mass percentage specified massSolvent = (100.0 - m_Concentration) / m_Concentration; massSolvent *= massSolute(); mode = 2; break; // Calculate the volume of solvent case 4: // volume percentage specified volSolvent = (100.0 - m_Concentration) / m_Concentration; volSolvent *= volumeSolute(); mode = 3; break; // Calculate the moles of solvent case 5: //mole percentage specified moleSolvent = (100.0 - m_Concentration) / m_Concentration; moleSolvent *= molesSolute(); mode = 1; break; default: break; } // We have the amount of solvent in some form (moles, equivalents, mass, volume etc) // Now we have to present it in the UI if (densitySolvent() == 0.0) { error(DENSITY_ZERO); return; } if (m_MolarMassSolvent == 0.0) { error(MOLAR_SOLVENT_ZERO); return; } switch (type2) { case 0: // amount should be specified interms of volume switch (mode) { case 1: // obtain volume from moles volSolvent = moleSolvent * m_MolarMassSolvent / densitySolvent(); break; case 2: // obtain volume from mass volSolvent = massSolvent / densitySolvent(); break; case 3: // volume already known break; } m_AmtSolvent = Value(volSolvent, "liters"); m_AmtSolvent = (m_converter->convert(m_AmtSolvent, \ m_amountSolventUnit->nativeWidget()->currentText())); m_amountSolvent->setValue(m_AmtSolvent.number()); break; case 1: // amount should be specified in terms of mass switch (mode) { case 1: // obtain mass from moles massSolvent = moleSolvent / m_MolarMassSolvent; break; case 2: // mass already known break; case 3: // obtain mass from volume massSolvent = volSolvent / densitySolvent(); break; } m_AmtSolvent = Value(massSolvent, "grams"); m_AmtSolvent = (m_converter->convert(m_AmtSolvent, \ m_amountSolventUnit->nativeWidget()->currentText())); m_amountSolvent->setValue(m_AmtSolvent.number()); break; case 2: // amount should be specified in terms of moles switch (mode) { case 1: // moles already known break; case 2: // obtain moles from mass moleSolvent = massSolvent / m_MolarMassSolvent; break; case 3: // obtain moles from volume moleSolvent = volSolvent * densitySolvent() / m_MolarMassSolvent; break; } m_MolesSolvent = moleSolvent; m_amountSolvent->setValue(moleSolvent); break; } return; } // calculates the concentration void concentrationCalculator::calculateConcentration() { int type = m_concentrationUnit->nativeWidget()->currentIndex(); if (volumeSolvent() == 0.0) { error(VOLUME_ZERO); return; } if (massSolvent() == 0.0) { error(MASS_ZERO); return; } if (molesSolvent() == 0.0) { error(MOLES_ZERO); return; } switch (type) { case 0: // molarity m_Concentration = molesSolute() / volumeSolvent(); break; case 1: // normality m_Concentration = eqtsSolute() / volumeSolvent(); break; case 2: // molality m_Concentration = molesSolute() * 1000.0 / massSolvent(); break; case 3: // mass fraction m_Concentration = massSolute() / (massSolute() + massSolvent()) * 100.0; break; case 4: // volume fraction m_Concentration = volumeSolute() / (volumeSolute() + volumeSolvent()) * 100.0; break; case 5: // mole fraction m_Concentration = molesSolute() / (molesSolute() + molesSolvent()) * 100.0; break; default: break; } m_concentration->setValue(m_Concentration); return; } double concentrationCalculator::volumeSolvent() { int type = m_amountSolventType->nativeWidget()->currentIndex(); double volume; switch (type) { case 0: volume = (m_converter->convert(m_AmtSolvent, "liter")).number(); break; case 1: volume = massSolvent() / densitySolvent(); break; case 2: volume = massSolvent() / densitySolvent(); default: break; } return volume; } double concentrationCalculator::molesSolvent() { int type = m_amountSolventType->nativeWidget()->currentIndex(); double moles; switch (type) { case 0: moles = massSolvent() / m_MolarMassSolvent; break; case 1: moles = massSolvent() / m_MolarMassSolvent; break; case 2: moles = m_MolesSolvent; break; default: break; } return moles; } double concentrationCalculator::massSolvent() { int type = m_amountSolventType->nativeWidget()->currentIndex(); double mass; switch (type) { case 0: mass = volumeSolvent() * densitySolvent(); break; case 1: mass = (m_converter->convert(m_AmtSolvent, "gram")) .number(); break; case 2: mass = m_MolesSolvent * m_MolarMassSolvent; break; default: break; } return mass; } double concentrationCalculator::densitySolvent() { return ((m_converter->convert(m_DensitySolvent, "grams per liter")).number()); } double concentrationCalculator::volumeSolute() { int type = m_amountSoluteType->nativeWidget()->currentIndex(); double volume; switch (type) { case 0: volume = massSolute() / densitySolute(); break; case 1: volume = (m_converter->convert(m_AmtSolute, "liter")).number(); break; case 2: volume = massSolute() / densitySolute(); default: break; } return volume; } double concentrationCalculator::molesSolute() { int type = m_amountSoluteType->nativeWidget()->currentIndex(); double moles; if (m_MolarMass == 0.0) { error(MOLAR_MASS_ZERO); return 1.0; } switch (type) { case 0: moles = massSolute() / m_MolarMass; break; case 1: moles = massSolute() / m_MolarMass; break; case 2: moles = m_MolesSolute; break; default: break; } return moles; } double concentrationCalculator::eqtsSolute() { int type = m_amountSoluteType->nativeWidget()->currentIndex(); double eqts; if (m_EqtMass == 0.0) { error(EQT_MASS_ZERO); return 1.0; } switch (type) { case 0: eqts = massSolute() / m_EqtMass; break; case 1: eqts = massSolute() / m_EqtMass; break; case 2: // Cannot be calculated error(INSUFFICIENT_DATA_MOLES); eqts = 1.0; break; default: break; } return eqts; } double concentrationCalculator::massSolute() { int type = m_amountSoluteType->nativeWidget()->currentIndex(); double mass; switch (type) { case 0: mass = (m_converter->convert(m_AmtSolute, "gram")) .number(); break; case 1: mass = volumeSolute() * densitySolute(); break; case 2: mass = m_MolesSolute * m_MolarMass; break; default: break; } return mass; } double concentrationCalculator::densitySolute() { return ((m_converter->convert(m_DensitySolute, "grams per liter")).number()); } // occurs when the amount of solute is changed void concentrationCalculator::amountSoluteChanged() { int type = m_amountSoluteType->nativeWidget()->currentIndex(); switch (type) { case 0: case 1: m_AmtSolute = Value(m_amountSolute->value(), m_amountSoluteUnit->nativeWidget()->currentText()); break; case 2: m_MolesSolute = m_amountSolute->value(); break; } calculate(); } // occurs when the type in which amount of solute is specified is changed void concentrationCalculator::amountSoluteTypeChanged() { int type = m_amountSoluteType->nativeWidget()->currentIndex(); if (type == 0) { // amount of solute specified in terms of mass m_amountSoluteUnit->nativeWidget()->clear(); m_amountSoluteUnit->nativeWidget()->insertItems(0, QStringList() << i18n("grams") << i18n("tons") << i18n("carats") << i18n("pounds") << i18n("ounces") << i18n("troy ounces") ); m_amountSoluteUnit->show(); m_AmtSolute = Value(m_amountSolute->value(), m_amountSoluteUnit->nativeWidget()->currentText()); } else if (type == 1) { // amount of solute is specified in terms of volume m_amountSoluteUnit->nativeWidget()->clear(); m_amountSoluteUnit->nativeWidget()->insertItems(0, QStringList() << i18n("liter") << i18n("cubic meters") << i18n("cubic feet") << i18n("cubic inch") << i18n("cubic mile") << i18n("fluid ounce") << i18n("cups") << i18n("gallons") << i18n("pints") ); m_amountSoluteUnit->show(); m_AmtSolute = Value(m_amountSolute->value(), m_amountSoluteUnit->nativeWidget()->currentText()); } else { // amount of solute is specified in terms of moles m_MolesSolute = m_amountSolute->value(); m_amountSoluteUnit->hide(); } calculate(); } // occurs when the amount of solvent is changed void concentrationCalculator::amountSolventChanged() { int type = m_amountSolventType->nativeWidget()->currentIndex(); switch (type) { // amount of solvent specified in terms of volume case 0: case 1: m_AmtSolvent = Value(m_amountSolvent->value(), m_amountSolventUnit->nativeWidget()->currentText()); break; case 2: m_MolesSolvent = m_amountSolvent->value(); break; } calculate(); } void concentrationCalculator::amountSolventTypeChanged() { int type = m_amountSolventType->nativeWidget()->currentIndex(); if (type == 0) { // amount of solvent specified in terms of volume m_amountSolventUnit->nativeWidget()->clear(); m_amountSolventUnit->nativeWidget()->insertItems(0, QStringList() << i18n("liter") << i18n("cubic meters") << i18n("cubic feet") << i18n("cubic inch") << i18n("cubic mile") << i18n("fluid ounce") << i18n("cups") << i18n("gallons") << i18n("pints") ); m_amountSolventUnit->show(); m_AmtSolvent = Value(m_amountSolvent->value(), m_amountSolventUnit->nativeWidget()->currentText()); } else if (type == 1) { // amount of solvent is specified in terms of mass m_amountSolventUnit->nativeWidget()->clear(); m_amountSolventUnit->nativeWidget()->insertItems(0, QStringList() << i18n("grams") << i18n("tons") << i18n("carats") << i18n("pounds") << i18n("ounces") << i18n("troy ounces") ); m_amountSolventUnit->show(); m_AmtSolvent = Value(m_amountSolvent->value(), m_amountSolventUnit->nativeWidget()->currentText()); } else { // amount is specified in terms of moles m_amountSolventUnit->hide(); m_MolesSolvent = m_amountSolvent->value(); } calculate(); } //FIXME replace 'int value' with 'double value' // occurs when the molar mass of solute is changed void concentrationCalculator::molarMassChanged(int value) { m_MolarMass = value; calculate(); } // occurs when the equivalent mass of solute is changed void concentrationCalculator::eqtMassChanged(int value) { m_EqtMass = value; calculate(); } // occurs when the molar mass of solvent is changed void concentrationCalculator::molarMassSolventChanged(int value) { m_MolarMassSolvent = value; calculate(); } // occurs when the number of moles is changed void concentrationCalculator::densitySoluteChanged() { m_DensitySolute = Value(m_densitySolute->value(), m_densitySoluteUnit->nativeWidget()->currentText()); calculate(); } // occurs when the density of solvent is changed void concentrationCalculator::densitySolventChanged() { m_DensitySolvent = Value(m_densitySolvent->value(), m_densitySolventUnit->nativeWidget()->currentText()); calculate(); } // occurs when the concentration is changed void concentrationCalculator::concentrationChanged(int value) { m_Concentration = value; calculate(); } // This function is called when the mode of calculation is changed void concentrationCalculator::setMode (int mode) { // If there is no change, return. if (m_mode == mode) { return; } // set all to writeable m_amountSolute->nativeWidget()->setReadOnly(false); m_molarMass->nativeWidget()->setReadOnly(false); m_eqtMass->nativeWidget()->setReadOnly(false); m_amountSolvent->nativeWidget()->setReadOnly(false); m_molarMassSolvent->nativeWidget()->setReadOnly(false); m_concentration->nativeWidget()->setReadOnly(false); // set the value that should be calculated to readOnly switch (mode) { case 0: // Calculate the amount of solute m_amountSolute->nativeWidget()->setReadOnly(true); break; case 1: // Calculate the molar mass of solute m_molarMass->nativeWidget()->setReadOnly(true); break; case 2: // Calculate the equivalent mass of solute m_eqtMass->nativeWidget()->setReadOnly(true); break; case 3: // Calculate the amount of solvent m_amountSolvent->nativeWidget()->setReadOnly(true); break; case 4: // Calculate the molar mass of solvent m_molarMassSolvent->nativeWidget()->setReadOnly(true); break; case 5: // Calculate the concentration of the solution m_concentration->nativeWidget()->setReadOnly(true); break; } m_mode = mode; calculate(); } // occurs when any quantity is changed void concentrationCalculator::calculate() { error(RESET_CONC_MESG); switch (m_calculationMode->nativeWidget()->currentIndex()) { case 0: // Calculate the amount of solute if (m_concentrationUnit->nativeWidget()->currentIndex() > 2 && m_concentration->value() > 100) { error(PERCENTAGE_ZERO); return; } calculateAmountSolute(); break; case 1: // Calculate the molar mass of solute calculateMolarMass(); break; case 2: // Calculate the equivalent mass of solute calculateEqtMass(); break; case 3: // Calculate the amount of solvent calculateAmountSolvent(); break; case 4: // Calculate the molar mass of solvent calculateMolarMassSolvent(); break; case 5: // Calculate the concentration of the solution calculateConcentration(); break; } return; } void concentrationCalculator::error(int mode) { switch (mode) { case RESET_CONC_MESG: m_error->setText(""); break; case PERCENTAGE_ZERO: m_error->setText(i18n("Percentage should be less than 100.0, please enter a valid value.")); break; case DENSITY_ZERO: m_error->setText(i18n("Density cannot be zero, please enter a valid value.")); break; case MASS_ZERO: m_error->setText(i18n("Mass cannot be zero, please enter a valid value.")); break; case VOLUME_ZERO: m_error->setText(i18n("Volume cannot be zero, please enter a valid value.")); break; case MOLES_ZERO: m_error->setText(i18n("Number of moles cannot be zero, please enter a valid value.")); break; case MOLAR_SOLVENT_ZERO: m_error->setText(i18n("Molar mass of solvent is zero, please enter a valid value.")); break; case EQTS_ZERO: m_error->setText(i18n("Number of equivalents is zero - cannot calculate equivalent mass.")); break; case CONC_ZERO: m_error->setText(i18n("Concentration is zero, please enter a valid value.")); break; case INSUFFICIENT_DATA_EQT: m_error->setText(i18n("Insufficient data to calculate the required value, please specify normality.")); break; case INSUFFICIENT_DATA_MOLE: m_error->setText(i18n("Insufficient data, please specify molarity / mole fraction / molality to calculate.")); break; case INSUFFICIENT_DATA_MOLES: m_error->setText(i18n("Amount is specified in moles, cannot calculate molar/equivalent masses. Please specify mass/volume.")); break; case INSUFFICIENT_DATA_SOLVENT: m_error->setText(i18n("You can only calculate the molar mass of a solvent if the mole fraction is specified.")); break; case MOLAR_MASS_ZERO: m_error->setText(i18n("Molar mass cannot be zero, please enter a valid value.")); break; case EQT_MASS_ZERO: m_error->setText(i18n("Equivalent mass cannot be zero, please enter a valid value.")); break; default: break; } } void concentrationCalculator::createConfigurationInterface(KConfigDialog *parent) { QWidget *widget = new QWidget(); ui.setupUi(widget); parent->addPage(widget, i18n("General"), icon()); ui.soluteMass->setChecked(m_soluteMass); ui.solventVolume->setChecked(m_solventVolume); - connect(parent, SIGNAL(applyClicked()), this, SLOT(configAccepted())); - connect(parent, SIGNAL(okClicked()), this, SLOT(configAccepted())); + connect(parent->okButton, &QPushButton::clicked, + this, &concentrationCalculator::configAccepted); + connect(parent->buttonBox, &QDialogButtonBox::Apply::clicked, + this, &concentrationCalculator::configAccepted); connect (ui.soluteMass, SIGNAL(toggled(bool)), parent, SLOT(settingsModified())); connect (ui.solventVolume, SIGNAL(toggled(bool)), parent, SLOT(settingsModified())); } void concentrationCalculator::configAccepted() { KConfigGroup cg = config(); QGraphicsItem::update(); m_soluteMass = ui.soluteMass->isChecked(); cg.writeEntry("soluteMass", m_soluteMass); m_solventVolume = ui.solventVolume->isChecked(); cg.writeEntry("solventVolume", m_solventVolume); m_configUpdated = true; updateConstraints(); emit configNeedsSaving(); } #include "concentrationCalculator.moc" diff --git a/plasmoid/applet/gasPlasmoid/gasCalculator.cpp b/plasmoid/applet/gasPlasmoid/gasCalculator.cpp index de780783..9bc43f88 100644 --- a/plasmoid/applet/gasPlasmoid/gasCalculator.cpp +++ b/plasmoid/applet/gasPlasmoid/gasCalculator.cpp @@ -1,678 +1,681 @@ /*************************************************************************** copyright : (C) 2009 by Kashyap R Puranik email : kashthealien@gmail.com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "gasCalculator.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include using namespace KUnitConversion; gasCalculator::gasCalculator(QObject *parent, const QVariantList &args) : Plasma::PopupApplet(parent, args) , m_widget(0) { m_converter = new Converter( this ); setAspectRatioMode(Plasma::IgnoreAspectRatio); setPopupIcon("accessories-calculator"); setHasConfigurationInterface(true); setAssociatedApplication("kalzium"); resize(600, 300); } gasCalculator::~gasCalculator() { if (hasFailedToLaunch()) { // Do some cleanup here } else { // Save settings } } void gasCalculator::init() { configChanged(); } void gasCalculator::configChanged() { KConfigGroup cg = config(); cg.readEntry("ideal",true); } QGraphicsWidget *gasCalculator::graphicsWidget() { //FIXME: // 1.> Currently the spin boxes are integer, please convert them into double // and uncomment certain lines of code which say 'setDecimals(4)' if (!m_widget) { m_widget = new QGraphicsWidget(this); m_widget->setMinimumSize(500, 300); /**************************************************************************/ // Gas Calculator set up /**************************************************************************/ // setup the label Plasma::Frame *pHeader = new Plasma::Frame(this); pHeader->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); pHeader->setText(i18n("Gas Calculator")); //setup the grid layout QGraphicsGridLayout *pGridLayout = new QGraphicsGridLayout(m_widget); pGridLayout->addItem(pHeader, 0, 0, 1, 3); // Set up the user interface // Calculation mode Plasma::Label *calcModeLabel = new Plasma::Label(this); calcModeLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); calcModeLabel->setText(i18n("Calculation Mode:")); m_calculationMode = new Plasma::ComboBox(this); m_calculationMode->setZValue(3); m_calculationMode->nativeWidget()->insertItems(0, QStringList() << i18n("Moles / Mass") << i18n("Pressure") << i18n("Temperature") << i18n("Volume") ); pGridLayout->addItem(calcModeLabel, 1, 0); pGridLayout->addItem(m_calculationMode, 1, 1); // molar mass Plasma::Label *molarMassLabel = new Plasma::Label(this); molarMassLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); molarMassLabel->setText(i18n("Molar Mass of Gas:")); m_molarMass = new Plasma::SpinBox(this); m_molarMass->nativeWidget()->setMinimumWidth(80); m_molarMass->nativeWidget()->setMaximum(1000000000); //m_MolarMass->setDecimals(4); m_molarMass->setMaximum(1e+09); Plasma::Label *molarMassUnitLabel = new Plasma::Label(this); molarMassUnitLabel->nativeWidget()->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); molarMassUnitLabel->setText(i18n("u (mass)")); pGridLayout->addItem(molarMassLabel, 2, 0); pGridLayout->addItem(m_molarMass, 2, 1); pGridLayout->addItem(molarMassUnitLabel, 2, 2); // moles Plasma::Label *molesLabel = new Plasma::Label(this); molesLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); molesLabel->setText(i18n("Number of moles:")); m_moles = new Plasma::SpinBox(this); m_moles->nativeWidget()->setMinimumWidth(80); m_moles->nativeWidget()->setMaximum(1000000000); //m_Moles->setDecimals(4); m_moles->setMaximum(1e+09); pGridLayout->addItem(molesLabel, 3, 0); pGridLayout->addItem(m_moles, 3, 1); // mass Plasma::Label *massLabel = new Plasma::Label(this); massLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); massLabel->setText(i18n("Mass of the gas:")); m_mass = new Plasma::SpinBox(this); m_mass->nativeWidget()->setMinimumWidth(80); m_mass->nativeWidget()->setMaximum(1000000000); //m_Mass->setDecimals(4); m_mass->setMaximum(1e+09); m_massUnit = new Plasma::ComboBox(this); m_massUnit->setZValue(2); m_massUnit->nativeWidget()->insertItems(0, QStringList() << i18n("grams") << i18n("tons") << i18n("carats") << i18n("pounds") << i18n("ounces") << i18n("troy ounces") ); m_massUnit->setZValue(6); pGridLayout->addItem(massLabel, 4, 0); pGridLayout->addItem(m_mass, 4, 1); pGridLayout->addItem(m_massUnit, 4, 2); // pressure Plasma::Label *pressureLabel = new Plasma::Label(this); pressureLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); pressureLabel->setText(i18n("Pressure of the Gas:")); m_pressure = new Plasma::SpinBox(this); m_pressure->nativeWidget()->setMinimumWidth(80); m_pressure->nativeWidget()->setMaximum(1000000000); //m_Pressure->setDecimals(4); m_pressure->setMaximum(1e+09); m_pressureUnit = new Plasma::ComboBox(this); m_pressureUnit->setZValue(2); m_pressureUnit->nativeWidget()->insertItems(0, QStringList() << i18n("atmospheres") << i18n("pascal") << i18n("bars") << i18n("millibars") << i18n("decibars") << i18n("torrs") << i18n("inches of mercury") ); m_pressureUnit->setZValue(5); pGridLayout->addItem(pressureLabel, 5, 0); pGridLayout->addItem(m_pressure, 5, 1); pGridLayout->addItem(m_pressureUnit, 5, 2); // temperature Plasma::Label *temperatureLabel = new Plasma::Label(this); temperatureLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); temperatureLabel->setText(i18n("Temperature:")); m_temperature = new Plasma::SpinBox(this); m_temperature->nativeWidget()->setMinimumWidth(80); m_temperature->nativeWidget()->setMaximum(1000000000); //m_Temp->setDecimals(4); m_temperature->setMaximum(1e+09); m_temperatureUnit = new Plasma::ComboBox(this); m_temperatureUnit->setZValue(2); m_temperatureUnit->nativeWidget()->insertItems(0, QStringList() << i18n("kelvins") << i18n("celsius") << i18n("fahrenheit") << i18n("delisles") << i18n("r\303\251aumurs") ); m_temperatureUnit->setZValue(4); pGridLayout->addItem(temperatureLabel, 6, 0); pGridLayout->addItem(m_temperature, 6, 1); pGridLayout->addItem(m_temperatureUnit, 6, 2); // volume Plasma::Label *volumeLabel = new Plasma::Label(this); volumeLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); volumeLabel->setText(i18n("Volume of the gas:")); m_volume = new Plasma::SpinBox(this); m_volume->nativeWidget()->setMinimumWidth(80); m_volume->nativeWidget()->setMaximum(1000000000); //m_volume->setDecimals(4); m_volume->setMaximum(1e+09); m_volumeUnit = new Plasma::ComboBox(this); m_volumeUnit->setZValue(2); m_volumeUnit->nativeWidget()->insertItems(0, QStringList() << i18n("liter") << i18n("cubic feet") << i18n("cubic inch") << i18n("fluid ounce") << i18n("cups") << i18n("gallons") << i18n("pints") ); m_volumeUnit->setZValue(3); pGridLayout->addItem(volumeLabel, 7, 0); pGridLayout->addItem(m_volume, 7, 1); pGridLayout->addItem(m_volumeUnit, 7, 2); // van der waals constant a Plasma::Label *vand_aLabel = new Plasma::Label(this); vand_aLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); vand_aLabel->setText(i18n("Van der Waals constant 'a':")); m_Vand_a = new Plasma::SpinBox(this); m_Vand_a->nativeWidget()->setMinimumWidth(80); m_Vand_a->nativeWidget()->setMaximum(1000000000); //m_Vand_A->setDecimals(4); m_Vand_a->setMaximum(1e+09); m_aUnit = new Plasma::ComboBox(this); m_aUnit->setZValue(2); m_aUnit->nativeWidget()->insertItems(0, QStringList() << i18n("liter^2 atmosphere/mol^2") ); m_aUnit->setZValue(2); pGridLayout->addItem(vand_aLabel, 8, 0); pGridLayout->addItem(m_Vand_a, 8, 1); pGridLayout->addItem(m_aUnit, 8, 2); // van der Waals constant b Plasma::Label *vand_bLabel = new Plasma::Label(this); vand_bLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); vand_bLabel->setText(i18n("Van der Waals constant 'b':")); m_Vand_b = new Plasma::SpinBox(this); m_Vand_b->nativeWidget()->setMinimumWidth(80); m_Vand_b->nativeWidget()->setMaximum(1000000000); //m_Vand_B->setDecimals(4); m_Vand_b->setMaximum(1e+09); m_bUnit = new Plasma::ComboBox(this); m_bUnit->setZValue(2); m_bUnit->nativeWidget()->insertItems(0, QStringList() << i18n("liters") << i18n("cubic meters") << i18n("cubic feet") << i18n("cubic inches") << i18n("gallons") << i18n("cups") ); m_bUnit->setZValue(1); pGridLayout->addItem(vand_bLabel, 9, 0); pGridLayout->addItem(m_Vand_b, 9, 1); pGridLayout->addItem(m_bUnit, 9, 2); // Results m_error = new Plasma::Label(this); pGridLayout->addItem(m_error, 10, 1, 4, 1); // Reset m_reset = new Plasma::PushButton(this); m_reset->setText(i18n("Reset")); pGridLayout->addItem(m_reset, 10, 0); // Adding objects to the UI done, now initialise reset(); // Connect signals with slots //FIXME replace all int with double after using the doubleSpinBox connect(m_temperature, SIGNAL(valueChanged(int)), this, SLOT(tempChanged())); connect(m_temperatureUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(tempChanged())); connect(m_volume, SIGNAL(valueChanged(int)), this, SLOT(volChanged())); connect(m_volumeUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(volChanged())); connect(m_pressure, SIGNAL(valueChanged(int)), this, SLOT(pressureChanged())); connect(m_pressureUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(pressureChanged())); connect(m_mass, SIGNAL(valueChanged(int)), this, SLOT(massChanged())); connect(m_massUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(massChanged())); connect(m_moles, SIGNAL(valueChanged(int)), this, SLOT(molesChanged(int))); connect(m_molarMass, SIGNAL(valueChanged(int)), this, SLOT(molarMassChanged(int))); connect(m_Vand_a, SIGNAL(valueChanged(int)), this, SLOT(Vand_aChanged())); connect(m_aUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(Vand_aChanged())); connect(m_Vand_b, SIGNAL(valueChanged(int)), this, SLOT(Vand_bChanged())); connect(m_bUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(Vand_bChanged())); connect(m_calculationMode->nativeWidget(), SIGNAL(activated(int)), this, SLOT(setMode(int))); connect(m_reset, SIGNAL(clicked()), this, SLOT(reset())); /**************************************************************************/ // gas Calculator setup complete /**************************************************************************/ } return m_widget; } void gasCalculator::reset() { error(RESET_GAS_MESG); m_molarMass ->setValue(2.008); m_temperature ->setValue(273.0); m_volume ->setValue(22.4024); m_pressure ->setValue(1.0); m_Vand_a ->setValue(0.0); m_Vand_b ->setValue(0.0); m_mass ->setValue(2.016); m_moles ->setValue(1.0); // Setup of the UI done m_massUnit ->nativeWidget()->setCurrentIndex(0); m_pressureUnit ->nativeWidget()->setCurrentIndex(0); m_temperatureUnit ->nativeWidget()->setCurrentIndex(0); m_volumeUnit ->nativeWidget()->setCurrentIndex(0); m_bUnit ->nativeWidget()->setCurrentIndex(0); m_aUnit ->nativeWidget()->setCurrentIndex(0); m_calculationMode ->nativeWidget()->setCurrentIndex(3); // Initialise values m_Temp = Value(273.0, "kelvins"); m_MolarMass = 2.016; m_Moles = 1.0; m_Mass = Value( m_MolarMass * m_Moles, "grams"); m_Pressure = Value(1.0, "atmosphere"); m_Vand_A = 0.0; m_Vand_B = Value(0.0, "liters"); m_Vol = Value(22.4024, "liters"); // Initialisation of values done setMode(3); molarMassChanged(2); } /* Note:- Van der Val's gas equation ( P + n^2 a / V^2) ( V - nb ) = nRT where P - pressure V - Volume n - number of moles R - Universal gas constant T - temperature a,b - Van der Val's constants */ // Calculates the Pressure void gasCalculator::calculatePressure() { double pressure; double volume = (m_converter->convert(m_Vol, "liters")).number(); double temp = (m_converter->convert(m_Temp, "kelvins")).number(); double b = (m_converter->convert(m_Vand_B, "liters")).number(); pressure = m_Moles * R * temp / (volume - m_Moles * b) - m_Moles * m_Moles * m_Vand_A / volume / volume; m_Pressure = Value(pressure, "atmospheres"); m_Pressure = m_converter->convert(m_Pressure, m_pressureUnit->nativeWidget()->currentText()); m_pressure->setValue(m_Pressure.number()); //pressure = } // Calculates the molar mass of the gas void gasCalculator::calculateMolarMass() { double mass = ((m_converter->convert(m_Mass, "grams")).number()); double volume = ((m_converter->convert(m_Vol, "liters")).number()); double pressure = ((m_converter->convert(m_Pressure, "atmospheres")).number()); double temp = ((m_converter->convert(m_Temp, "kelvins")).number()); double b = ((m_converter->convert(m_Vand_B, "liters")).number()); m_MolarMass = mass * R * temp / (pressure + m_Moles * m_Moles * m_Vand_A / volume / volume)\ / (volume - m_Moles * b); m_molarMass->setValue(m_MolarMass); } // Calculates the Volume void gasCalculator::calculateVol() { double volume; double pressure = ((m_converter->convert(m_Pressure, "atmospheres")).number()); double temp = ((m_converter->convert(m_Temp, "kelvins")).number()); double b = ((m_converter->convert(m_Vand_B, "liters")).number()); volume = m_Moles * R * temp / pressure + (m_Moles * b); m_Vol = Value(volume, "liters"); m_Vol = (m_converter->convert(m_Vol, m_volumeUnit->nativeWidget()->currentText())); m_volume->setValue(m_Vol.number()); } // Calculates the Temperature void gasCalculator::calculateTemp() { double temp; double volume = ((m_converter->convert(m_Vol, "liters")).number()); double pressure = ((m_converter->convert(m_Pressure, "atmospheres")).number()); double b = ((m_converter->convert(m_Vand_B, "liters")).number()); temp = (pressure + (m_Moles * m_Moles * m_Vand_A / volume / volume))\ * (volume - m_Moles * b) / m_Moles / R; m_Temp = Value(temp, "kelvins"); m_Temp = (m_converter->convert(m_Temp, m_temperatureUnit->nativeWidget()->currentText())); m_temperature->setValue(m_Temp.number()); } // Calculates the number of moles void gasCalculator::calculateMoles() { double volume = ((m_converter->convert(m_Vol, "liters")).number()); double pressure = ((m_converter->convert(m_Pressure, "atmospheres")).number()); double temp = ((m_converter->convert(m_Temp, "kelvins")).number()); double b = ((m_converter->convert(m_Vand_B, "liters")).number()); m_Moles = (pressure + m_Moles * m_Moles * m_Vand_A / volume / volume)\ * (volume - m_Moles * b) / R / temp; m_moles->setValue(m_Moles); } // Calculates the mass of substance void gasCalculator::calculateMass() { double mass; double volume = ((m_converter->convert(m_Vol, "liters")).number()); double pressure = ((m_converter->convert(m_Pressure, "atmospheres")).number()); double temp = ((m_converter->convert(m_Temp, "kelvins")).number()); double b = ((m_converter->convert(m_Vand_B, "liters")).number()); mass = (pressure + m_Moles * m_Moles * m_Vand_A / volume / volume)\ * (volume - m_Moles * b) * m_MolarMass / R / temp; m_Mass = Value(mass, "grams"); m_Mass = (m_converter->convert(m_Mass, m_massUnit->nativeWidget()->currentText())); m_mass->setValue(m_Mass.number()); } // Functions ( slots ) that occur on changing a value // occurs when the volume is changed void gasCalculator::volChanged() { m_Vol = Value(m_volume->value(), m_volumeUnit->nativeWidget()->currentText()); calculate(); } // occurs when the temperature is changed void gasCalculator::tempChanged() { m_Temp = Value(m_temperature->value(), m_temperatureUnit->nativeWidget()->currentText()); calculate(); } // occurs when the pressure is changed void gasCalculator::pressureChanged() { m_Pressure = Value(m_pressure->value(), m_pressureUnit->nativeWidget()->currentText()); calculate(); } // occurs when the mass is changed void gasCalculator::massChanged() { m_Mass = Value(m_mass->value(), m_massUnit->nativeWidget()->currentText()); m_Moles = ((m_converter->convert(m_Mass, "grams")).number()) / m_MolarMass; m_moles->setValue(m_Moles); calculate(); } //FIXME: change int value to double value in the next two functions after using the doubleSpinBox // occurs when the number of moles is changed void gasCalculator::molesChanged(int value) { m_Moles = value; m_Mass = Value((m_Moles * m_MolarMass), "grams"); m_Mass = (m_converter->convert(m_Mass, m_massUnit->nativeWidget()->currentText())); m_mass->setValue(m_Mass.number()); QString temp; temp.setNum(value); calculate(); } // occurs when the molar mass is changed void gasCalculator::molarMassChanged(int value) { if ( value == 0.0 ) { error(MOLAR_MASS_ZERO_); return; } m_MolarMass = value; m_Mass = Value(m_MolarMass * m_Moles, "grams"); m_Mass = (m_converter->convert(m_Mass, m_massUnit->nativeWidget()->currentText())); m_mass->setValue(m_Mass.number()); calculate(); } // occurs when the number of moles is changed void gasCalculator::Vand_aChanged() { m_Vand_A = m_Vand_a->value(); calculate(); } // occurs when the number of moles is changed void gasCalculator::Vand_bChanged() { m_Vand_B = Value(m_Vand_b->value(), m_bUnit->nativeWidget()->currentText()); calculate(); } void gasCalculator::setMode(int mode) { m_mode = mode; m_moles->nativeWidget()->setReadOnly(false); m_mass->nativeWidget()->setReadOnly(false); m_pressure->nativeWidget()->setReadOnly(false); m_temperature->nativeWidget()->setReadOnly(false); m_volume->nativeWidget()->setReadOnly(false); // set the quantity that should be calculated to readOnly switch (mode) { case 0: m_moles->nativeWidget()->setReadOnly(true); m_mass->nativeWidget()->setReadOnly(true); break; case 1: m_pressure->nativeWidget()->setReadOnly(true); break; case 2: m_temperature->nativeWidget()->setReadOnly(true); break; case 3: m_volume->nativeWidget()->setReadOnly(true); break; } calculate(); } // occurs when any quantity is changed void gasCalculator::calculate() { error(RESET_GAS_MESG); switch(m_mode) { case 0: calculateMoles(); break; case 1: calculatePressure(); break; case 2: calculateTemp(); break; case 3: calculateVol(); break; } } void gasCalculator::error(int mode) { switch (mode) { case RESET_GAS_MESG: m_error->setText(""); break; case VOL_ZERO : m_error->setText(i18n("Volume cannot be zero, please enter a valid value.")); break; case MOLAR_MASS_ZERO_: m_error->setText(i18n("The molar mass cannot be zero, please enter a non-zero value.")); default: break; } } void gasCalculator::createConfigurationInterface(KConfigDialog *parent) { QWidget *widget = new QWidget(); ui.setupUi(widget); parent->addPage(widget, i18n("General"), icon()); ui.ideal->setChecked(m_ideal); - connect(parent, SIGNAL(applyClicked()), this, SLOT(gasConfigAccepted())); - connect(parent, SIGNAL(okClicked()), this, SLOT(gasConfigAccepted())); + connect(parent->okButton, &QPushButton::clicked, + this, &gasCalculator::gasConfigAccepted); + connect(parent->buttonBox, &QDialogButtonBox::Apply::clicked, + this, &gasCalculator::gasConfigAccepted); connect (ui.ideal, SIGNAL(toggled(bool)), parent, SLOT(settingsModified())); } void gasCalculator::gasConfigAccepted() { KConfigGroup cg = config(); QGraphicsItem::update(); m_ideal = ui.ideal->isChecked(); cg.writeEntry("ideal", m_ideal); m_configUpdated = true; updateConstraints(); emit configNeedsSaving(); } #include "gasCalculator.moc" diff --git a/plasmoid/applet/nuclearPlasmoid/kalziumdataobject.cpp b/plasmoid/applet/nuclearPlasmoid/kalziumdataobject.cpp index f4c8cf6d..30249a76 100644 --- a/plasmoid/applet/nuclearPlasmoid/kalziumdataobject.cpp +++ b/plasmoid/applet/nuclearPlasmoid/kalziumdataobject.cpp @@ -1,193 +1,193 @@ /*************************************************************************** * Copyright (C) 2005, 2006, 2007 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "kalziumdataobject.h" #include #include #include #include #include #include #include #include -#include +#include #include #include #include #include KalziumDataObject* KalziumDataObject::instance() { static KalziumDataObject kdo; return &kdo; } KalziumDataObject::KalziumDataObject() : m_search(0) { // reading elements ElementSaxParser * parser = new ElementSaxParser(); QFile xmlFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "libkdeedu/data/elements.xml")); QXmlInputSource source(&xmlFile); QXmlSimpleReader reader; reader.setContentHandler(parser); reader.parse(source); ElementList = parser->getElements(); //we don't need parser anymore, let's free its memory delete parser; //read the spectra SpectrumParser * spectrumparser = new SpectrumParser(); QFile xmlSpFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "libkdeedu/data/spectra.xml")); QXmlInputSource spsource(&xmlSpFile); QXmlSimpleReader sp_reader; sp_reader.setContentHandler(spectrumparser); sp_reader.parse(spsource); m_spectra = spectrumparser->getSpectrums(); //we don't need spectrumparser anymore, let's free its memory delete spectrumparser; // reading isotopes IsotopeParser * isoparser = new IsotopeParser(); QFile xmlIsoFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "libkdeedu/data/isotopes.xml")); QXmlInputSource isosource(&xmlIsoFile); QXmlSimpleReader isoreader; isoreader.setContentHandler(isoparser); isoreader.parse(isosource); QList isotopes = isoparser->getIsotopes(); //we don't need isoparser anymore, let's free its memory delete isoparser; foreach (Isotope *iso, isotopes) { int num = iso->parentElementNumber(); if (m_isotopes.contains(num)) { m_isotopes[num].append(iso); } else { QList newlist; newlist.append(iso); m_isotopes.insert(num, newlist); } } // cache it m_numOfElements = ElementList.count(); KPixmapCache cache("kalzium"); for (int i = 0; i < m_numOfElements; ++i) { //FIXME in case we ever get more than one theme we need //a settings-dialog where we can select the different iconsets... QString setname = "school"; QString pathname = QStandardPaths::locate(QStandardPaths::DataLocation, "data/iconsets/", QStandardPaths::LocateDirectory); QString filename = pathname + setname + '/' + QString::number(i + 1) + ".svg"; QPixmap pix = cache.loadFromSvg(filename, QSize(40, 40)); if (pix.isNull()) { pix = QPixmap(40, 40); pix.fill(Qt::transparent); QPainter p(&pix); Element *e = ElementList.at(i); QString esymbol = e->dataAsString(ChemicalDataObject::symbol); p.drawText(0, 0, 40, 40, Qt::AlignCenter | Qt::TextWordWrap, esymbol); p.end(); } PixmapList << pix; } } KalziumDataObject::~KalziumDataObject() { //Delete all elements qDeleteAll(ElementList); //Delete all isotopes QHashIterator > i(m_isotopes); while (i.hasNext()) { i.next(); qDeleteAll(i.value()); } } Element* KalziumDataObject::element(int number) { // checking that we are requesting a valid element if ((number <= 0) || (number > m_numOfElements)) { return 0; } return ElementList[ number-1 ]; } QPixmap KalziumDataObject::pixmap(int number) { // checking that we are requesting a valid element if ((number <= 0) || (number > m_numOfElements)) { return 0; } return PixmapList[number - 1]; } QList KalziumDataObject::isotopes(Element *element) { return isotopes(element->dataAsVariant(ChemicalDataObject::atomicNumber).toInt()); } QList KalziumDataObject::isotopes(int number) { return m_isotopes.contains(number) ? m_isotopes.value(number) : QList(); } Spectrum * KalziumDataObject::spectrum(int number) { foreach (Spectrum *s, m_spectra) { if (s->parentElementNumber() == number) { return s; } } return 0; } void KalziumDataObject::setSearch(Search *srch) { m_search = srch; } Search* KalziumDataObject::search() const { return m_search; } diff --git a/plasmoid/applet/nuclearPlasmoid/nuclearCalculator.cpp b/plasmoid/applet/nuclearPlasmoid/nuclearCalculator.cpp index d8a6b4a2..7a92bd0a 100644 --- a/plasmoid/applet/nuclearPlasmoid/nuclearCalculator.cpp +++ b/plasmoid/applet/nuclearPlasmoid/nuclearCalculator.cpp @@ -1,667 +1,670 @@ /*************************************************************************** copyright : (C) 2009 by Kashyap R Puranik email : kashthealien@gmail.com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "nuclearCalculator.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include using namespace KUnitConversion; nuclearCalculator::nuclearCalculator(QObject *parent, const QVariantList &args) : Plasma::PopupApplet(parent, args) , m_widget(0) { m_converter = new Converter(this); setAspectRatioMode(Plasma::IgnoreAspectRatio); setPopupIcon("accessories-calculator"); setHasConfigurationInterface(true); setAssociatedApplication("kalzium"); resize(600, 450); } nuclearCalculator::~nuclearCalculator() { if (hasFailedToLaunch()) { // Do some cleanup here } else { // Save settings } } void nuclearCalculator::init() { configChanged(); } void nuclearCalculator::configChanged() { KConfigGroup cg = config(); m_massOnly = cg.readEntry("massOnly",true); } void nuclearCalculator::reset() { const int ISOTOPE_NUM = 22; error(RESET_NUKE_MESG); // Add all isotope names of Uranium (by default) to the isotope comboBox QList list = KalziumDataObject::instance()->isotopes(92); QString iso; m_isotope->clear(); foreach (Isotope *i, list) { iso.setNum(i->mass()); m_isotope->addItem(iso); } // initialize the data, initially selected values (Uranium, 92, 238) m_element->nativeWidget()->setCurrentIndex(91); m_isotope->nativeWidget()->setCurrentIndex(ISOTOPE_NUM); m_halfLife->setValue(list.at(ISOTOPE_NUM)->halflife()); m_initAmt->setValue(6.0); m_finalAmt->setValue(3.0); m_time->setValue(list.at(ISOTOPE_NUM)->halflife()); m_halfLifeUnit->nativeWidget()->setCurrentIndex(0); m_initType->nativeWidget()->setCurrentIndex(0); m_finalType->nativeWidget()->setCurrentIndex(0); m_initUnit->nativeWidget()->setCurrentIndex(0); m_finalUnit->nativeWidget()->setCurrentIndex(0); m_timeUnit->nativeWidget()->setCurrentIndex(0); m_calculationMode ->nativeWidget()->setCurrentIndex(2); // Setup of the UI done // Initialize values m_InitAmount = Value(6.0, "g") ; m_FinalAmount = Value(3.0, "g"); m_Mass = list.at(ISOTOPE_NUM)->mass(); m_Time = Value((list.at(ISOTOPE_NUM)->halflife()), "y"); m_HalfLife = Value(list.at(ISOTOPE_NUM)->halflife(), "y"); m_Element = * KalziumDataObject::instance()->element(92); m_Isotope = * list.at(ISOTOPE_NUM); setMode(2); // Initialization of values done } QGraphicsWidget *nuclearCalculator::graphicsWidget() { //FIXME: // Currently the spin boxes are integer, please convert them into double after // doubleSpinBoxes are available if (!m_widget) { // Position all UI elements m_widget = new QGraphicsWidget(this); m_widget->setMinimumSize(550, 400); Plasma::Frame *pHeader = new Plasma::Frame(this); pHeader->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); pHeader->setText(i18n("Nuclear Calculator")); Plasma::GroupBox *pGroupBox1 = new Plasma::GroupBox(this); Plasma::GroupBox *pGroupBox2 = new Plasma::GroupBox(this); QGraphicsGridLayout *pGridLayout = new QGraphicsGridLayout(pGroupBox1); QGraphicsGridLayout *pGridLayout2 = new QGraphicsGridLayout(pGroupBox2); QGraphicsLinearLayout *pVLayout = new QGraphicsLinearLayout(Qt::Vertical, m_widget); pVLayout->addItem(pGroupBox1); pVLayout->addItem(pGroupBox2); // pVLayout->addItem(new Plasma::) // here comes the element - isotope and halfLife info part Plasma::Label *eleLabel = new Plasma::Label(this); eleLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); eleLabel->setText(i18n("Element name:")); Plasma::Label *isoLabel = new Plasma::Label(this); isoLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); isoLabel->setText(i18n("Isotope mass:")); Plasma::Label *hLifeLabel = new Plasma::Label(this); hLifeLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); hLifeLabel->setText(i18n("Half-Life:")); m_element = new Plasma::ComboBox(this); m_element->setZValue(2); m_isotope = new Plasma::ComboBox(this); m_isotope->setZValue(1); m_halfLife = new Plasma::SpinBox(this); m_halfLife->nativeWidget()->setMinimumWidth(100); m_halfLife->nativeWidget()->setMaximum(1000000000); //m_halfLife->setDecimals(4); m_halfLife->setMaximum(1e+09); m_halfLifeUnit = new Plasma::ComboBox(this); m_halfLifeUnit->nativeWidget()->insertItems(0, QStringList() << i18n("year") << i18n("seconds") << i18n("minutes") << i18n("hours") << i18n("days") << i18n("weeks")); m_halfLifeUnit->setZValue(6); pGridLayout->addItem(pHeader, 0, 0, 1, 4); pGridLayout->addItem(eleLabel, 1, 0); pGridLayout->addItem(m_element, 1, 1); pGridLayout->addItem(isoLabel, 2, 0); pGridLayout->addItem(m_isotope, 2, 1); pGridLayout->addItem(hLifeLabel, 3, 0); pGridLayout->addItem(m_halfLifeUnit, 3, 2); pGridLayout->addItem(m_halfLife, 3, 1); // Here comes the amount and time part // Calculation mode Plasma::Label *calcModeLabel = new Plasma::Label(this); calcModeLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); calcModeLabel->setText(i18n("Calculation Mode:")); m_calculationMode = new Plasma::ComboBox(this); m_calculationMode->setZValue(3); m_calculationMode->nativeWidget()->insertItems(0, QStringList() << i18n("Initial amount") << i18n("Final amount") << i18n("Time") ); Plasma::Label *initLabel = new Plasma::Label(this); initLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); initLabel->setText(i18n("Initial amount:")); Plasma::Label *finalLabel = new Plasma::Label(this); finalLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); finalLabel->setText(i18n("Final amount:")); Plasma::Label *timeLabel = new Plasma::Label(this); timeLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); timeLabel->setText(i18n("Time:")); /*x Plasma::Label *m_sliderLabel = new Plasma::Label(this); m_sliderLabel->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_sliderLabel->setText(i18n("Time in Half-Lives"));*/ m_numHalfLives = new Plasma::Label(this); m_numHalfLives->nativeWidget()->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_numHalfLives->setText(i18n("0 seconds")); m_initAmt = new Plasma::SpinBox(this); m_initAmt->nativeWidget()->setMinimumWidth(200); m_initAmt->nativeWidget()->setMaximum(1000000000); //m_initAmt->setDecimals(4); m_initAmt->setMaximum(1e+09); m_finalAmt = new Plasma::SpinBox(this); m_finalAmt->nativeWidget()->setMinimumWidth(200); m_finalAmt->nativeWidget()->setMaximum(1000000000); //m_finalAmt->setDecimals(4); m_finalAmt->setMaximum(1e+09); m_time = new Plasma::SpinBox(this); m_time->nativeWidget()->setMinimumWidth(200); m_time->nativeWidget()->setMaximum(1000000000); //m_time->setDecimals(4); m_time->setMaximum(1e+09); m_initUnit = new Plasma::ComboBox(this); m_initUnit->setZValue(2); m_initUnit->nativeWidget()->insertItems(0, QStringList() << i18n("grams") << i18n("tons") << i18n("carats") << i18n("pounds") << i18n("ounces") << i18n("troy ounces")); m_initUnit->setZValue(3); m_finalUnit = new Plasma::ComboBox(this); m_finalUnit->setZValue(2); m_finalUnit->nativeWidget()->insertItems(0, QStringList() << i18n("grams") << i18n("tons") << i18n("carats") << i18n("pounds") << i18n("ounces") << i18n("troy ounces")); m_finalUnit->setZValue(2); m_timeUnit = new Plasma::ComboBox(this); m_timeUnit->setZValue(2); m_timeUnit->nativeWidget()->insertItems(0, QStringList() << i18n("year") << i18n("seconds") << i18n("minutes") << i18n("hours") << i18n("days") << i18n("weeks")); m_timeUnit->setZValue(1); m_initType = new Plasma::ComboBox(this); m_initType->setZValue(2); m_initType->nativeWidget()->insertItems(0, QStringList() << i18n("Mass") << i18n("moles")); m_initType->setZValue(2); m_finalType = new Plasma::ComboBox(this); m_finalType->setZValue(2); m_finalType->nativeWidget()->insertItems(0, QStringList() << i18n("Mass") << i18n("moles")); m_finalType->setZValue(1); /*m_slider = new Plasma::Slider(this); m_slider->setRange(0, 100); m_slider->setOrientation(Qt::Horizontal); m_slider->setMaximum(100); */ m_error = new Plasma::Label(this); m_reset = new Plasma::PushButton(this); m_reset->setText(i18n("Reset")); pGridLayout2->addItem(calcModeLabel, 5, 0); pGridLayout2->addItem(initLabel, 6, 0); pGridLayout2->addItem(finalLabel, 7, 0); pGridLayout2->addItem(timeLabel, 8, 0); // pGridLayout2->addItem(m_sliderLabel, 9, 0); pGridLayout2->addItem(m_error, 10, 1, 1, 3); pGridLayout2->addItem(m_reset, 10, 0); pGridLayout2->addItem(m_calculationMode, 5, 1); pGridLayout2->addItem(m_initAmt, 6, 1); pGridLayout2->addItem(m_finalAmt, 7, 1); pGridLayout2->addItem(m_time, 8, 1); // pGridLayout2->addItem(m_slider, 9, 1); pGridLayout2->addItem(m_initType, 6, 3); pGridLayout2->addItem(m_finalType, 7, 3); pGridLayout2->addItem(m_numHalfLives, 9, 2); pGridLayout2->addItem(m_initUnit, 6, 2); pGridLayout2->addItem(m_finalUnit, 7, 2); pGridLayout2->addItem(m_timeUnit, 8, 2); // Positioning of UI elements done // Now add required properties to the UI widgets /**************************************************************************/ // Nuclear Calculator set up // /**************************************************************************/ KalziumDataObject *kdo = KalziumDataObject::instance(); // add all element names to the comboBox in the user interface foreach (Element *e, kdo->ElementList) { m_element->nativeWidget()->addItem(e->dataAsString(ChemicalDataObject::name)); } ///FIXME /* The last three elements will be removed because information is not available and causes the program to crash when selected. */ int count = m_element->nativeWidget()->count(); m_element->nativeWidget()->removeItem(count - 1); m_element->nativeWidget()->removeItem(count - 2); m_element->nativeWidget()->removeItem(count - 3); // Add all isotope names of Uranium (by default) to the isotope comboBox reset(); // Connect signals with slots connect(m_element->nativeWidget(), SIGNAL(activated(int)), this, SLOT(elementChanged(int))); connect(m_isotope->nativeWidget(), SIGNAL(activated(int)), this, SLOT(isotopeChanged(int))); //FIXME change int to double in the following signals after finding doubleSpinBox connect(m_halfLife, SIGNAL(valueChanged(int)), this, SLOT(halfLifeChanged())); connect(m_halfLifeUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(halfLifeChanged())); connect(m_initAmt, SIGNAL(valueChanged(int)), this, SLOT(initAmtChanged())); connect(m_initUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(initAmtChanged())); connect(m_initType->nativeWidget(), SIGNAL(activated(int)), this, SLOT(initAmtChanged())); connect(m_finalAmt, SIGNAL(valueChanged(int)), this, SLOT(finalAmtChanged())); connect(m_finalUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(finalAmtChanged())); connect(m_finalType->nativeWidget(), SIGNAL(activated(int)), this, SLOT(finalAmtChanged())); connect(m_time, SIGNAL(valueChanged(int)), this, SLOT(timeChanged())); connect(m_timeUnit->nativeWidget(), SIGNAL(activated(int)), this, SLOT(timeChanged())); /* connect(m_slider, SIGNAL(valueChanged(int)), this, SLOT(sliderMoved(int)));*/ connect(m_calculationMode->nativeWidget(), SIGNAL(activated(int)), this, SLOT(setMode(int))); connect(m_reset, SIGNAL(clicked()), this, SLOT(reset())); /**************************************************************************/ // Nuclear Calculator setup complete /**************************************************************************/ } return m_widget; } void nuclearCalculator::elementChanged (int index) { // set the newly chosen element m_Element = * KalziumDataObject::instance()->element(index + 1); // Add all isotope names of Uranium (by default) to the isotope comboBox QList list = KalziumDataObject::instance()->isotopes(index + 1); QString isotope; // A temporary string m_isotope->clear(); // Clear the contents of the combo box // update the combobox with isotopes of the new element foreach (Isotope *i, list) { isotope.setNum(i->mass()); m_isotope->addItem(isotope); } // Set the halfLife to that of the first isotope of the element. m_halfLife->setValue(list. at(0)->halflife()); // Recalculate and update calculate(); } void nuclearCalculator::isotopeChanged(int index) { // update the nuclear Calculator int elementNumber = m_element->nativeWidget()->currentIndex() + 1; QList list = KalziumDataObject::instance()->isotopes(elementNumber); m_Isotope = * list.at(index); // get the halfLife of the new isotope double halfLife = list.at(index)->halflife(); m_Mass = list.at(index)->mass(); // A string used for searching the right Unit QString halfLifeUnit = list . at(index)->halflifeUnit(); halfLifeUnit = (halfLifeUnit == "y") ? "year" : "seconds"; // Update the UI with the halfLife value m_halfLife->setValue(halfLife); int x = m_halfLifeUnit->nativeWidget()->findText(halfLifeUnit); if (x >= 0) { m_halfLifeUnit->nativeWidget()->setCurrentIndex(x); } m_HalfLife = Value(halfLife, halfLifeUnit); // Recalculate and update calculate(); } void nuclearCalculator::halfLifeChanged() { // update the halfLife value m_HalfLife = Value(m_halfLife->value(), m_halfLifeUnit->nativeWidget()->currentText()); // recalculate the required calculate(); } void nuclearCalculator::initAmtChanged() { // If quantity is specified in terms of mass, quantity <- (mass , Unit) if (m_initType->nativeWidget()->currentIndex() == 0) { m_InitAmount = Value(m_initAmt->value(), m_initUnit->nativeWidget()->currentText()); } else { // If quantity is specified in terms of moles quantity <- (moles * atomicMass, Unit) m_InitAmount = Value(((m_initAmt->value()) * m_Mass), \ m_initUnit->nativeWidget()->currentText()); } calculate(); } void nuclearCalculator::finalAmtChanged() { // If quantity is specified in terms of mass, quantity <- (mass , Unit) if (m_finalType->nativeWidget()->currentIndex() == 0) { m_FinalAmount = Value(m_finalAmt->value(), \ m_finalUnit->nativeWidget()->currentText()); // If quantity is specified in terms of moles quantity <- (moles * atomicMass, Unit) } else { m_FinalAmount = Value(((m_finalAmt->value()) * m_Mass), \ m_finalUnit->nativeWidget()->currentText()); } calculate(); } void nuclearCalculator::timeChanged() { m_Time = Value(m_time->value(), m_timeUnit->nativeWidget()->currentText()); calculate(); } /*void nuclearCalculator::sliderMoved(int numHlives) { double num = numHlives / 10.0; m_Time = Value(num * m_HalfLife. number() , m_HalfLife. unit()); m_time->setValue(m_Time. number()); m_timeUnit->nativeWidget()->setCurrentIndex(m_halfLifeUnit->nativeWidget()->currentIndex()); m_numHalfLives->setText(m_Time.toString()); }*/ void nuclearCalculator::calculate() { error(RESET_NUKE_MESG); // Validate the values involved in calculation if (m_HalfLife. number() == 0.0) { error(HALFLIFE_ZERO); return; } switch (m_mode) { case 0: // Calculate initial amount if (m_FinalAmount.number() == 0.0) { error(FINAL_AMT_ZERO); return; } calculateInitAmount(); break; case 1: // Calulate final Amount after time if (m_InitAmount.number() == 0.0) { error(INIT_AMT_ZERO); return; } calculateFinalAmount(); break; case 2: // Calculate Time // If final amount greater than initial, error if (m_FinalAmount.number() > (m_converter->convert(m_InitAmount, m_FinalAmount.unit()->symbol())).number()) { error(FINAL_AMT_GREATER); return; } else if (m_finalAmt->value() == 0.0) { // final amount is 0.0 error(FINAL_AMT_ZERO); return; } calculateTime(); break; } } void nuclearCalculator::setMode(int mode) { m_mode = mode; m_initAmt->nativeWidget()->setReadOnly(false); m_finalAmt->nativeWidget()->setReadOnly(false); m_time->nativeWidget()->setReadOnly(false); // set the quantity that should be calculated to readOnly switch (mode) { case 0: m_initAmt->nativeWidget()->setReadOnly(true); // showSlider(true); break; case 1: m_finalAmt->nativeWidget()->setReadOnly(true); // showSlider(true); break; case 2: m_time->nativeWidget()->setReadOnly(true); // showSlider(false); break; } calculate(); } void nuclearCalculator::showSlider(bool /*show*/) { // TODO /* if (show) { m_sliderLabel->hide(); m_slider->hide(); m_numHalfLives->hide(); } else { m_sliderLabel->show(); m_slider->show(); m_numHalfLives->show(); } */ } void nuclearCalculator::calculateInitAmount() { // If no time has elapsed, initial and final amounts are the same m_InitAmount = m_FinalAmount; if (m_Time. number() == 0.0) { m_initAmt->setValue(m_InitAmount . number()); return; } // Calculate the number of halfLives that have elapsed double ratio = (m_converter->convert(m_Time, m_HalfLife. unit() \ ->symbol()). number()) /m_HalfLife. number(); // find out the initial amount m_InitAmount = Value(m_InitAmount. number() * pow(2.0 , ratio), m_InitAmount. unit()); // Convert into the required units m_InitAmount = m_converter->convert(m_InitAmount, m_InitAmount. unit()->symbol()); m_initAmt->setValue(m_InitAmount . number()); } void nuclearCalculator::calculateFinalAmount() { // If no time has elapsed, initial and final amounts are the same m_FinalAmount = m_InitAmount; if (m_Time. number() == 0.0) { m_finalAmt->setValue(m_FinalAmount.number()); return; } // Calculate the number of halfLives that have elapsed double ratio = (m_converter->convert(m_Time , m_HalfLife. unit() \ ->symbol()). number()) / m_HalfLife. number(); // Calculate the final amount m_FinalAmount = Value(m_FinalAmount . number() / pow(2.0, ratio), m_InitAmount. unit()); // Convert into the required units m_FinalAmount = m_converter->convert(m_FinalAmount, m_FinalAmount. unit()->symbol()); m_finalAmt->setValue(m_FinalAmount. number()); } void nuclearCalculator::calculateTime() { // If initial and final masses are the same (both units and value) // the time is also 0 if (m_InitAmount.number() == m_FinalAmount.number() && \ m_InitAmount. unit() == m_FinalAmount . unit()) { m_Time = Value(0.0, m_Time. unit()); m_time->setValue(m_Time. number()); return; } // calculate the ratio of final to initial masses double ratio = (m_converter->convert(m_InitAmount , m_FinalAmount.unit()\ ->symbol())).number() / m_FinalAmount.number(); // The number of halfLives (log 2 (x) = log x / log 2) double numHalfLives = log(ratio) / log(2.0); double time_value = numHalfLives * m_HalfLife . number(); // Calculate the total time taken Value temp = Value(time_value, m_HalfLife. unit()); m_Time = m_converter->convert(temp , m_Time.unit()->symbol()); m_time->setValue(m_Time. number()); } void nuclearCalculator::error(int mode) { switch (mode) { // Depending on the mode, set the error messages. case RESET_NUKE_MESG: m_error->setText(""); break; case INIT_AMT_ZERO: m_error->setText(i18n("Initial amount cannot be zero.")); break; case FINAL_AMT_ZERO: m_error->setText(i18n("Final amount cannot be zero.")); break; case HALFLIFE_ZERO: m_error->setText(i18n("Time is zero, please enter a valid value.")); break; case FINAL_AMT_GREATER: m_error->setText(i18n("Final amount cannot be greater than initial amount.")); break; } } void nuclearCalculator::createConfigurationInterface(KConfigDialog *parent) { QWidget *widget = new QWidget(); ui.setupUi(widget); parent->addPage(widget, i18n("General"), icon()); ui.massOnly->setChecked(m_massOnly); - connect(parent, SIGNAL(applyClicked()), this, SLOT(configAccepted())); - connect(parent, SIGNAL(okClicked()), this, SLOT(configAccepted())); + connect(parent->okButton, &QPushButton::clicked, + this, &nuclearCalculator::configAccepted); + connect(parent->buttonBox, &QDialogButtonBox::Apply::clicked, + this, &nuclearCalculator::configAccepted); connect(ui.massOnly, SIGNAL(toggled(bool)), parent, SLOT(settingsModified())); } void nuclearCalculator::configAccepted() { KConfigGroup cg = config(); QGraphicsItem::update(); m_massOnly = ui.massOnly->isChecked(); cg.writeEntry("massOnly", m_massOnly); m_configUpdated = true; updateConstraints(); emit configNeedsSaving(); } #include "nuclearCalculator.moc" diff --git a/plasmoid/applet/psePlasmoid/Molmasscalculator.cpp b/plasmoid/applet/psePlasmoid/Molmasscalculator.cpp index 555bd7dd..67d9dd6b 100644 --- a/plasmoid/applet/psePlasmoid/Molmasscalculator.cpp +++ b/plasmoid/applet/psePlasmoid/Molmasscalculator.cpp @@ -1,276 +1,292 @@ /*********************************************************************************** * Mass calculator: Plasmoid to calculate mass of a Molecule. * Copyright (C) 2009, 2010 Etienne Rebetez, etienne.rebetez@oberwallis.ch * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***********************************************************************************/ // own #include "Molmasscalculator.h" // Qt #include #include #include // KDE #include #include #include // Plasma #include +#include +#include +#include +#include // local Molmasscalculator::Molmasscalculator(QObject *parent, const QVariantList &args) : Plasma::PopupApplet(parent, args), m_widget(0), m_PeriodWidget(0), m_lineedit(0), m_MassLabel(0), m_switchButton(0) { // Some Applet settings setAspectRatioMode(Plasma::IgnoreAspectRatio); setHasConfigurationInterface(true); setAcceptDrops(false); setAssociatedApplication("kalzium"); m_triggerTimer = new QTimer(); m_triggerTimer->setSingleShot(true); m_triggerTimer->setInterval(700); - connect(m_triggerTimer, SIGNAL(timeout()), this, SLOT(ParseMolecule())); + connect(m_triggerTimer, &QTimer::timeout, this, &Molmasscalculator::ParseMolecule); // Needed for the Popupapplet setPopupIcon("kalzium"); } Molmasscalculator::~Molmasscalculator() { if (!hasFailedToLaunch()) { saveConfig(); } delete m_switchButton; delete m_MassLabel; delete m_lineedit; delete m_PeriodWidget; delete m_widget; delete m_triggerTimer; } void Molmasscalculator::init() { // checking if the Dataengine is availiable if (!dataEngine("kalzium")->isValid()) { setFailedToLaunch(true, i18n("Dataengine \"kalzium\" not found")); } // loads the configuration configChanged(); // Create the Periodic Table m_PeriodWidget = new PeriodicGrid(config().readEntry("tableType", 0), this); graphicsWidget(); // Calculate the demo molecule. ParseMolecule(); //set sizes managePeriodSystem(); } void Molmasscalculator::appendElement(QString elementSymbol) { QString molecule; molecule = m_lineedit->text(); molecule.append(elementSymbol); ParseMolecule(molecule); } void Molmasscalculator::ParseMolecule(QString strInput) { if (!strInput.isEmpty()) { m_molecule = dataEngine("kalzium")->query(QString("Molecule:Parser:") + strInput); newCalculatedMass(); } } void Molmasscalculator::ParseMolecule() { ParseMolecule(m_lineedit->text()); } void Molmasscalculator::newCalculatedMass() { if (m_molecule["molMass"].toString().isEmpty()) { m_MassLabel->setText(i18n("Invalid Molecule")); return; } //Set new MassLabel Text m_MassLabel->setText(QString::number(m_molecule["molMass"].toDouble(), 'g', 6) + " u"); //Sets the niceMolecule string in the Lineedit //Configuration Option? m_lineedit->setText(m_molecule["niceMolecule"].toString()); //Copy new Mass to Clipboard if (m_copyToClipboard) { QApplication::clipboard()->setText(m_molecule["molMass"].toString()); } } QGraphicsWidget *Molmasscalculator::graphicsWidget() { if (m_widget) { return m_widget; } m_widget = new QGraphicsWidget(this); QGraphicsLinearLayout *MainLayout = new QGraphicsLinearLayout(Qt::Vertical , m_widget); QGraphicsLinearLayout *TopLayout = new QGraphicsLinearLayout(Qt::Horizontal, MainLayout); Plasma::Label *MoleculeLabel = new Plasma::Label; MoleculeLabel->setText(i18n("Molecule:")); m_MassLabel = new Plasma::Label; m_MassLabel->setAlignment(Qt::AlignCenter); QString css("font-size:18px; color:" + this->palette().text().color().name() + ';'); m_MassLabel->setStyleSheet(css); m_lineedit = new Plasma::LineEdit(); m_lineedit->setClearButtonEnabled(true); m_lineedit->setMinimumWidth(100); m_lineedit->setText(i18n("C2H5OH")); - connect(m_lineedit, SIGNAL(textEdited(QString)), m_triggerTimer, SLOT(start())); + connect(m_lineedit, &Plasma::LineEdit::textEdited, m_triggerTimer, &QTimer::start); m_switchButton = new Plasma::IconWidget(); - connect(m_switchButton, SIGNAL(clicked()), this, SLOT(toggleTable())); + connect(m_switchButton, &Plasma::IconWidget::clicked, this, &graphicsWidget::toggleTable); TopLayout->addItem(MoleculeLabel); TopLayout->addItem(m_lineedit); TopLayout->addItem(m_switchButton); TopLayout->setSpacing(0); TopLayout->setContentsMargins(0,0,0,0); MainLayout->addItem(TopLayout); MainLayout->addItem(m_MassLabel); MainLayout->addItem(m_PeriodWidget); MainLayout->setSpacing(2); return m_widget; } void Molmasscalculator::toggleTable() { if (m_showPeriodicTable) { m_showPeriodicTable = false; } else { m_showPeriodicTable = true; } managePeriodSystem(); } void Molmasscalculator::managePeriodSystem() { QString iconName; KIconLoader iconLoader; int x, y; if (m_showPeriodicTable) { iconName = "arrow-down"; m_PeriodWidget->show(); x = pseTables::instance()->getTabletype(m_PeriodWidget->getCurrentPseTyp())->tableSize().x() * 33; y = pseTables::instance()->getTabletype(m_PeriodWidget->getCurrentPseTyp())->tableSize().y() * 34; } else { iconName = "arrow-right"; m_PeriodWidget->hide(); x = 300; y = 60; } m_switchButton->setIcon(iconLoader.loadIcon(iconName, KIconLoader::Small)); m_widget->setMinimumSize(x, y); m_widget->setPreferredSize(x, y); m_widget->resize(x, y); resize(x, y); } void Molmasscalculator::createConfigurationInterface(KConfigDialog* parent) { - parent->setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Apply); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Apply); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + parent->setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + parent->connect(buttonBox, &QDialogButtonBox::accepted, this, &createConfigurationInterface::accept); + parent->connect(buttonBox, &QDialogButtonBox::rejected, this, &createConfigurationInterface::reject); + mainLayout->addWidget(buttonBox); QWidget *widget = new QWidget(parent); m_ui.setupUi(widget); parent->addPage(widget, i18n("General"), "kalzium"); m_ui.showPeriodic->setChecked(m_showPeriodicTable); m_ui.copyToCliboard->setChecked(m_copyToClipboard); foreach (const QString &thisTable, pseTables::instance()->tables()) { m_ui.tabletyp->addItem(thisTable); } m_ui.tabletyp->setCurrentIndex(m_PeriodWidget->getCurrentPseTyp()); - connect(parent, SIGNAL(applyClicked()), this, SLOT(configAccepted())); - connect(parent, SIGNAL(okClicked()), this, SLOT(configAccepted())); + connect(parent->okButton, &QPushButton::clicked, + this, &Molmasscalculator::configAccepted); + connect(parent->buttonBox, &QDialogButtonBox::Apply::clicked, + this, &Molmasscalculator::configAccepted); connect(m_ui.showPeriodic, SIGNAL(toggled(bool)), parent, SLOT(settingsModified())); connect(m_ui.copyToCliboard, SIGNAL(toggled(bool)), parent, SLOT(settingsModified())); connect(m_ui.tabletyp, SIGNAL(currentIndexChanged(QString)), parent, SLOT(settingsModified())); } void Molmasscalculator::configAccepted() { if (m_ui.showPeriodic->isChecked() != m_showPeriodicTable) { m_showPeriodicTable = m_ui.showPeriodic->isChecked(); managePeriodSystem(); } if (m_ui.copyToCliboard->checkState() != m_copyToClipboard) { m_copyToClipboard = m_ui.copyToCliboard->checkState(); } if (m_ui.tabletyp->currentIndex() != m_PeriodWidget->getCurrentPseTyp()) { m_PeriodWidget->setCurrentPseTyp(m_ui.tabletyp->currentIndex()); managePeriodSystem(); } saveConfig(); } void Molmasscalculator::saveConfig() { config().writeEntry("showPeriodicTable",m_showPeriodicTable); config().writeEntry("copyToClipboard",m_copyToClipboard); config().writeEntry("tableType",m_PeriodWidget->getCurrentPseTyp()); } void Molmasscalculator::configChanged() { m_showPeriodicTable = config().readEntry("showPeriodicTable", true); m_copyToClipboard = config().readEntry("copyToClipboard", false); } #include "Molmasscalculator.moc" diff --git a/src/calculator/calculator.cpp b/src/calculator/calculator.cpp index 383cd6a4..574cc53b 100644 --- a/src/calculator/calculator.cpp +++ b/src/calculator/calculator.cpp @@ -1,128 +1,142 @@ /*************************************************************************** * Copyright (C) 2009 by Kashyap R Puranik, kashthealien@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "calculator.h" #include -#include -#include -#include #include +#include #include +#include +#include + +#include +#include +#include #include -calculator::calculator(QWidget *parent) : KDialog(parent) +#include +#include + +calculator::calculator(QWidget *parent) : QDialog(parent) { setWindowTitle(i18n("Chemical Calculator")); - setButtons(Help | Close); - setDefaultButton(Close); - - ui.setupUi(mainWidget()); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Close); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + connect(buttonBox, &QDialogButtonBox::accepted, this, &calculator::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &calculator::reject); + mainLayout->addWidget(buttonBox); + buttonBox->button(QDialogButtonBox::Close)->setDefault(true); + + ui.setupUi(mainWidget); int maxTextWidth = 0; QStyleOptionViewItem option; option.initFrom(ui.tree); for (int i = 0; i < ui.tree->topLevelItemCount(); ++i) { maxTextWidth = qMax(maxTextWidth, ui.tree->itemDelegate()->sizeHint(option, ui.tree->model()->index(i, 0)).width()); } // 20 because we want some margins, not a too tight text ui.tree->setMaximumWidth(qMax(ui.tree->maximumWidth(), maxTextWidth + 20)); // Add the nuclear calculator to the user interface m_nuclearCalculator = new nuclearCalculator(this); ui.stack->addWidget(m_nuclearCalculator); // Add the gas calculator to the user interface m_gasCalculator = new gasCalculator(this); ui.stack->addWidget(m_gasCalculator); // Add the concentration calculator to the user interface m_concCalculator = new concCalculator(this); ui.stack->addWidget(m_concCalculator); // Add the molecular mass Calculator widget to the user interface m_moleCalculator = new MolcalcWidget(this); ui.stack->addWidget(m_moleCalculator); // Add the molecular mass Calculator widget to the user interface m_titraCalculator = new titrationCalculator(this); ui.stack->addWidget(m_titraCalculator); #ifdef HAVE_FACILE // Add the equation balancer widget to the user interface QTreeWidgetItem *treeItem = new QTreeWidgetItem(ui.tree); treeItem->setText(0, i18n("Equation Balancer")); m_equationBalancer = new EQChemDialog(this); ui.stack->addWidget(m_equationBalancer); #endif // Add an image to the file ui.pic->setPixmap((QIcon::fromTheme("calculate")).pixmap(128,128)); // Connect the tree item selection signal to the corresponding slot connect(ui.tree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(slotItemSelection(QTreeWidgetItem*))); ui.tree->setCurrentItem(ui.tree->topLevelItem(0), 0, QItemSelectionModel::ToggleCurrent); // help clicked - connect(this, SIGNAL(helpClicked()), this, SLOT(slotHelp())); + connect(buttonBox->button(QDialogButtonBox::Help), &QPushButton::clicked, this, &calculator::slotHelp); } calculator :: ~calculator() { } void calculator::slotItemSelection(QTreeWidgetItem *item) { if (item == 0L) { return; } //DEBUG qDebug() << "Item clicked: " << item->text(0); QString s = item->text(0); if (!(s.compare(i18n("Introduction")))) { ui.stack->setCurrentWidget(ui.intro); } else if (!(s.compare(i18n("Nuclear Calculator")))) { // if nuclear calculator is selected, show the widget in the user interface ui.stack->setCurrentWidget(m_nuclearCalculator); } else if (!(s.compare(i18n("Gas Calculator")))) { // if gas calculator is selected, show the widget in the user interface ui.stack->setCurrentWidget(m_gasCalculator); } else if (!(s.compare(i18n("Concentration Calculator")))) { // if the concentration calculator is selected, show the widget in the UI ui.stack->setCurrentWidget(m_concCalculator); // The equation balancer needs FACILE library, if it's present HAVE_FACILE = 1 #ifdef HAVE_FACILE } else if (!(s.compare(i18n("Equation Balancer")))) { // If the equation balancer was selected, open it in the UI. ui.stack->setCurrentWidget(m_equationBalancer); #endif } else if (!(s.compare(i18n("Molecular mass Calculator")))) { ui.stack->setCurrentWidget(m_moleCalculator); } else if (!(s.compare(i18n("Titration Calculator")))) { ui.stack->setCurrentWidget(m_titraCalculator); } } void calculator::slotHelp() { - // KToolInvocation::invokeHelp("calculator", "kalzium",""); + KHelpClient::invokeHelp("calculator", "kalzium"); } diff --git a/src/calculator/calculator.h b/src/calculator/calculator.h index e2cdf538..3f5a1bdc 100644 --- a/src/calculator/calculator.h +++ b/src/calculator/calculator.h @@ -1,80 +1,80 @@ /*************************************************************************** * Copyright (C) 2009 by Kashyap R Puranik, kashthealien@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef CALCULATOR_H #define CALCULATOR_H -#include +#include #include "ui_calculator.h" #include "nuclearCalculator.h" #include "gasCalculator.h" #include "concCalculator.h" #include "titrationCalculator.h" #include "molcalcwidget.h" #include #include #ifdef HAVE_FACILE #include #endif /** * This widget implements the body of the calculator widget, * various calculators like the nuclear Calculator will be added to this. * * @author Kashyap R Puranik */ -class calculator : public KDialog +class calculator : public QDialog { Q_OBJECT public: /* * The clas constructor and destructor, takes in a Widget as parent */ calculator(QWidget *parent = nullptr); // constructor ~ calculator(); // destructor private: Ui::calculator ui; // The user interface KActionCollection * m_actionCollection; // These are the various calculator widgets that will be added to this calculator nuclearCalculator * m_nuclearCalculator; // The nuclear calculator gasCalculator * m_gasCalculator; // The gas calculator concCalculator * m_concCalculator; // The concentration calculator titrationCalculator * m_titraCalculator; // The concentration calculator MolcalcWidget * m_moleCalculator; // The molecular mass calculator #ifdef HAVE_FACILE EQChemDialog * m_equationBalancer; // The equation balancer #endif protected slots: /** * invoke the help of the correct chapter */ virtual void slotHelp(); private slots: // occurs when an tree item is selected, opens the corresponding calculator void slotItemSelection(QTreeWidgetItem *item); public slots: }; #endif // CALCULATOR_H diff --git a/src/detailinfodlg.cpp b/src/detailinfodlg.cpp index 094d1ae3..1c2a482e 100644 --- a/src/detailinfodlg.cpp +++ b/src/detailinfodlg.cpp @@ -1,637 +1,637 @@ /*************************************************************************** begin : Tue Apr 8 2003 copyright : (C) 2003, 2004, 2005, 2006 by Carsten Niehaus email : cniehaus@kde.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "detailinfodlg.h" #include "isotope.h" #include "kalziumdataobject.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "psetables.h" #include #include #include #include #include #include #include #include "element.h" #include "orbitswidget.h" #include "detailedgraphicaloverview.h" #include "spectrumviewimpl.h" #include "kalziumutils.h" #include "prefs.h" DetailedInfoDlg::DetailedInfoDlg(int el, QWidget *parent) : KPageDialog(parent), m_tableTyp(0) { setFaceType(List); buttonBox()->clear(); buttonBox()->addButton(QDialogButtonBox::Close); buttonBox()->addButton(QDialogButtonBox::Help); const QString nextButtonIconSource = (layoutDirection() == Qt::LeftToRight) ? "arrow-right" : "arrow-left"; QPushButton *nextButton = new QPushButton(QIcon::fromTheme(nextButtonIconSource), i18nc("Next element", "Next"), this); nextButton->setToolTip(i18n("Goes to the next element")); const QString prevButtonIconSource = (layoutDirection() == Qt::LeftToRight) ? "arrow-left" : "arrow-right"; QPushButton *prevButton = new QPushButton(QIcon::fromTheme(prevButtonIconSource), i18nc("Previous element", "Previous"), this); prevButton->setToolTip(i18n("Goes to the previous element")); buttonBox()->addButton(prevButton, QDialogButtonBox::ActionRole); buttonBox()->addButton(nextButton, QDialogButtonBox::ActionRole); resize(820, 580); m_baseHtml = QStandardPaths::locate(QStandardPaths::DataLocation, "data/htmlview/", QStandardPaths::LocateDirectory); m_baseHtml2 = QStandardPaths::locate(QStandardPaths::DataLocation, "data/hazardsymbols/", QStandardPaths::LocateDirectory); //X m_picsdir = QStandardPaths::locate(QStandardPaths::DataLocation, "elempics/") + "elempics/"; //X m_picsdir = QFileInfo(m_picsdir).absolutePath(); // creating the tabs but not the contents, as that will be done when setting the element createContent(); m_actionCollection = new KActionCollection(this); KStandardAction::quit(this, SLOT(close()), m_actionCollection); connect(prevButton, &QPushButton::clicked, this, &DetailedInfoDlg::showPreviousElement); connect(nextButton, &QPushButton::clicked, this, &DetailedInfoDlg::showNextElement); connect(buttonBox(), &QDialogButtonBox::helpRequested, this, &DetailedInfoDlg::slotHelp); // setting the element and updating the whole dialog setElement(el); } DetailedInfoDlg::~DetailedInfoDlg() { qDeleteAll(m_htmlpages); } void DetailedInfoDlg::setElement(int el) { Element *element = KalziumDataObject::instance()->element(el); if (!element) { return; } m_element = element; m_elementNumber = el; emit elementChanged(m_elementNumber); reloadContent(); /* enableButton(User1, true); - enableButton(User2, true); + user2Button->setEnabled(true); if (m_elementNumber == 1) { - enableButton(User2, false); + user2Button->setEnabled(false); } else if (m_elementNumber == KalziumDataObject::instance()->numberOfElements()) { - enableButton(User1, false); + user1Button->setEnabled(false); }*/ } // void DetailedInfoDlg::setOverviewBackgroundColor(const QColor &bgColor) // { // // dTab->setBackgroundColor(bgColor); // } void DetailedInfoDlg::setTableType(int tableTyp) { m_tableTyp = tableTyp; } KHTMLPart* DetailedInfoDlg::addHTMLTab(const QString& title, const QString& icontext, const QString& iconname) { QWidget* frame = new QWidget(this); KPageWidgetItem *item = addPage(frame, title); item->setHeader(icontext); item->setIcon(QIcon::fromTheme(iconname)); QVBoxLayout *layout = new QVBoxLayout(frame); layout->setMargin(0); KHTMLPart *w = new KHTMLPart(frame, frame); w->setJScriptEnabled(false); w->setJavaEnabled(false); w->setMetaRefreshEnabled(false); w->setPluginsEnabled(false); connect(w->browserExtension(), SIGNAL(openUrlRequest(QUrl)), this, SLOT(slotLinkClicked(QUrl))); layout->addWidget(w->view()); return w; } void DetailedInfoDlg::fillHTMLTab(KHTMLPart* htmlpart, const QString& htmlcode) { if (!htmlpart) { return; } htmlpart->begin(); htmlpart->write(htmlcode); // set the background color of the document to match that of the dialog DOM::HTMLElement element = htmlpart->htmlDocument().body(); if (element.tagName() == "body") { const QColor backgroundColor = palette().background().color(); ((DOM::HTMLBodyElement)element).setBgColor(backgroundColor.name()); } htmlpart->end(); } QString DetailedInfoDlg::getHtml(DATATYPE type) { QString html = "" "Chemical data" "" "" "
" "
" + m_element->dataAsString(ChemicalDataObject::symbol) + "" + createWikiLink(m_element->dataAsString(ChemicalDataObject::name)) + "" + i18n("Block: %1", m_element->dataAsString(ChemicalDataObject::periodTableBlock)) + "
" ""; switch (type) { case MISC: { // discovery date and discoverers html.append(""); // origin of the name QString nameorigin = m_element->dataAsString(ChemicalDataObject::nameOrigin); if (!nameorigin.isEmpty()) { html.append(""); } //X if (m_element->artificial() || m_element->radioactive()) { //X html.append(""); //X } break; } case ISOTOPES: { html.append(""); break; } case DATA: { // melting point html.append(""); // boiling point html.append(""); // electro affinity html.append(""); //Electronic configuration html.append(""); // covalent radius html.append(""); // van der Waals radius html.append(""); // mass html.append(""); // 1st ionization energy html.append(""); // electro negativity html.append(""); // Oxidation numbers html.append(""); break; } case EXTRA: { //Wikipedia.org // html.append (""); //http://education.jlab.org/itselemental/ele001.html html.append (""); // FIXME only works with english locals html.append (""); //chemipedia.org //html.append(""); //physics.nist.gov //html.append(""); } } html += "
\"icon\"/"); html += KalziumUtils::prettyUnit(m_element, ChemicalDataObject::date); QString discoverers = m_element->dataAsString(ChemicalDataObject::discoverers); if (!discoverers.isEmpty()) { discoverers = discoverers.replace(';', ", "); html += "
" + i18n("It was discovered by %1.", discoverers); } html.append("
\"icon\"/"); html.append(i18n("Origin of the name:
%1", nameorigin)); html.append("
\"icon\"/"); //X if (!m_element->radioactive()) { //X html.append(i18n("This element is artificial")); //X } else if (!m_element->artificial()) { //X html.append(i18n("This element is radioactive")); //X } else { //X html.append(i18n("This element is radioactive and artificial")); //X } //X html.append("
"); html.append(isotopeTable()); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Melting Point"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::meltingpoint)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Boiling Point"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::boilingpoint)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Electron Affinity"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::electronAffinity)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Electronic configuration"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::electronicConfiguration)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Covalent Radius"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::radiusCovalent)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("van der Waals Radius"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::radiusVDW)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Atomic mass"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::mass)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Ionization energy"), i18n("First Ionization energy"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::ionization)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Electronegativity"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::electronegativityPauling)); html.append("
\"icon\"/"); html.append(createWikiLink(i18n("Oxidation states"))); html.append(""); html.append(KalziumUtils::prettyUnit(m_element, ChemicalDataObject::oxidation)); html.append("
\"icon\"/"); html.append ("
"); html.append (createWikiLink(m_element->dataAsString(ChemicalDataObject::name), i18nc("Link to element's Wikipedia page, %1 is localized language name", "Wikipedia (%1)", QLocale().nativeLanguageName()))); html.append ("
"); html.append ("dataAsString(ChemicalDataObject::atomicNumber), 3, '0')); html.append (".html"); html.append ("\" target=\"_blank\" > "); html.append ("Jefferson Lab"); html.append (""); html.append ("
"); html.append ("dataAsString(ChemicalDataObject::name).toLower()); // hydrogen } html.append ("\" target=\"_blank\" >"); html.append ("Webelements"); html.append ("
\"icon\"/"); //html.append("
\"icon\"/"); //html.append("
"; return html; } QString DetailedInfoDlg::isotopeTable() const { QList list = KalziumDataObject::instance()->isotopes(m_elementNumber); QString html; html = ""; foreach (Isotope *isotope, list) { html.append(""); } html += "
"; html += i18n("Isotope-Table"); html += "
"; html += i18n("Mass"); html += ""; html += i18n("Neutrons"); html += ""; html += i18n("Percentage"); html += ""; html += i18n("Half-life period"); html += ""; html += i18n("Energy and Mode of Decay"); html += ""; html += i18n("Spin and Parity"); html += ""; html += i18n("Magnetic Moment"); html += "
"); if (isotope->mass() > 0.0) { html.append(i18n("%1 u", isotope->mass())); } html.append(""); html.append(QString::number(((isotope)->nucleons() - (isotope)->parentElementNumber()))); html.append(""); if (!(isotope)->abundance().isEmpty()) { html.append(i18nc("this can for example be '24%'", "%1%", (isotope)->abundance())); } html.append(""); if ((isotope)->halflife() > 0.0) { html.append(i18nc("The first argument is the value, the second is the unit. For example '17 s' for '17 seconds',.", "%1 %2", (isotope)->halflife(), (isotope)->halflifeUnit())); } html.append(""); if ((isotope)->alphalikeliness() > 0.0) { if ((isotope)->alphadecay() > 0.0) { html.append(i18n("%1 MeV", (isotope)->alphadecay())); } html.append(i18n(" %1", QChar(945))); if ((isotope)->alphalikeliness() < 100.0) { html.append(i18n("(%1%)", (isotope)->alphalikeliness())); } if ((isotope)->betaminuslikeliness() > 0.0 || (isotope)->betapluslikeliness() > 0.0 || (isotope)->eclikeliness() > 0.0) { html.append(i18n(", ")); } } if ((isotope)->betaminuslikeliness() > 0.0) { if ((isotope)->betaminusdecay() > 0.0) { html.append(i18n("%1 MeV", (isotope)->betaminusdecay())); } html.append(i18n(" %1-", QChar(946))); if ((isotope)->betaminuslikeliness() < 100.0) { html.append(i18n("(%1%)", (isotope)->betaminuslikeliness())); } if ((isotope)->betapluslikeliness() > 0.0 || (isotope)->eclikeliness() > 0.0) { html.append(i18n(", ")); } } if ((isotope)->betapluslikeliness() > 0.0) { if ((isotope)->betaplusdecay() > 0.0) { html.append(i18n("%1 MeV", (isotope)->betaplusdecay())); } html.append(i18n(" %1+", QChar(946))); if ((isotope)->betapluslikeliness() == (isotope)->eclikeliness()) { if ((isotope)->ecdecay() > 0.0) { html.append(i18n("%1 MeV", (isotope)->ecdecay())); } html.append(i18nc("Acronym of Electron Capture"," EC")); } if ((isotope)->betapluslikeliness() < 100.0) { html.append(i18n("(%1%)", (isotope)->betapluslikeliness())); } html += ' '; } if ((isotope)->eclikeliness() > 0.0) { if ((isotope)->ecdecay() > 0.0) { html.append(i18n("%1 MeV", (isotope)->ecdecay())); } html.append(i18nc("Acronym of Electron Capture"," EC")); if ((isotope)->eclikeliness() < 100.0) { html.append(i18n("(%1%)", (isotope)->eclikeliness())); } } html.append(""); html.append((isotope)->spin()); html.append(""); if (!(isotope)->magmoment().isEmpty()) { html.append(i18n("%1 %2n", (isotope)->magmoment(), QChar(956))); } html.append("
"; return html; } void DetailedInfoDlg::createContent() { KPageWidgetItem *item = nullptr; // Removed the overview Tab, because its an Dockwidget and dosn't show much information. // overview tab // QWidget *m_pOverviewTab = new QWidget(); // item = addPage(m_pOverviewTab, i18n("Overview")); // item->setHeader(i18n("Overview")); // item->setIcon(QIcon("overview")); // QVBoxLayout *overviewLayout = new QVBoxLayout(m_pOverviewTab); // overviewLayout->setMargin(0); // dTab = new DetailedGraphicalOverview(m_pOverviewTab); // dTab->setObjectName("DetailedGraphicalOverview"); // overviewLayout->addWidget(dTab); //X // picture tab //X QWidget *m_pPictureTab = new QWidget(); //X item = addPage(m_pPictureTab, i18n("Picture")); //X item->setHeader(i18n("What does this element look like?")); //X item->setIcon(QIcon("elempic")); //X QVBoxLayout *mainLayout = new QVBoxLayout(m_pPictureTab); //X mainLayout->setMargin(0); //X piclabel = new QLabel(m_pPictureTab); //X piclabel->setMinimumSize(400, 350); //X mainLayout->addWidget(piclabel); // html tab m_htmlpages["new"] = addHTMLTab(i18n("Data Overview"), i18n("Data Overview"), "applications-science"); // atomic model tab QWidget *m_pModelTab = new QWidget(this); item = addPage(m_pModelTab, i18n("Atom Model")); item->setHeader(i18n("Atom Model")); item->setIcon(QIcon::fromTheme("orbits")); QVBoxLayout *modelLayout = new QVBoxLayout(m_pModelTab); modelLayout->setMargin(0); wOrbits = new OrbitsWidget(m_pModelTab); modelLayout->addWidget(wOrbits); // html tabs m_htmlpages["isotopes"] = addHTMLTab(i18n("Isotopes"), i18n("Isotopes"), "isotopemap"); m_htmlpages["misc"] = addHTMLTab(i18n("Miscellaneous"), i18n("Miscellaneous"), "misc"); // spectrum widget tab QWidget *m_pSpectrumTab = new QWidget(this); item = addPage(m_pSpectrumTab, i18n("Spectrum")); item->setHeader(i18n("Spectrum")); item->setIcon(QIcon::fromTheme("spectrum")); QVBoxLayout *spectrumLayout = new QVBoxLayout(m_pSpectrumTab); spectrumLayout->setMargin(0); m_spectrumStack = new QStackedWidget(m_pSpectrumTab); spectrumLayout->addWidget(m_spectrumStack); m_spectrumview = new SpectrumViewImpl(m_spectrumStack); m_spectrumview->setObjectName("spectrumwidget"); m_spectrumStack->addWidget(m_spectrumview); m_spectrumLabel = new QLabel(m_spectrumStack); m_spectrumStack->addWidget(m_spectrumLabel); // html extra tab m_htmlpages["extra"] = addHTMLTab(i18n("Extra information"), i18n("Extra Information"), "applications-internet"); } void DetailedInfoDlg::reloadContent() { // reading the most common data const QString element_name = m_element->dataAsString(ChemicalDataObject::name); // const QString element_symbol = m_element->dataAsString(ChemicalDataObject::symbol); // updating caption setWindowTitle(i18nc("For example Carbon (6)", "%1 (%2)", element_name, m_elementNumber)); // updating overview tab // dTab->setElement(m_elementNumber); //X // updating picture tab //X QString picpath = m_picsdir + element_symbol + ".jpg"; //X if (QFile::exists(picpath)) { //X QImage img(picpath, "JPEG"); //X img = img.scaled(400, 400, Qt::KeepAspectRatio); //X piclabel->setPixmap(QPixmap::fromImage(img)); //X } else { //X piclabel->setText(i18n("No picture of %1 found.", element_name)); //X } // updating atomic model tab wOrbits->setElementNumber(m_elementNumber); /* wOrbits->setWhatsThis( i18n("Here you can see the atomic hull of %1. %2 has the configuration %3.") .arg(m_element->dataAsString(ChemicalDataObject::name)) .arg(m_element->dataAsString(ChemicalDataObject::name)) .arg(""));//m_element->parsedOrbits())); */ // updating html tabs fillHTMLTab(m_htmlpages["new"], getHtml(DATA)); fillHTMLTab(m_htmlpages["misc"], getHtml(MISC)); fillHTMLTab(m_htmlpages["isotopes"], getHtml(ISOTOPES)); fillHTMLTab(m_htmlpages["extra"], getHtml(EXTRA)); Spectrum * spec = KalziumDataObject::instance()->spectrum(m_elementNumber); // updating spectrum widget if (spec) { m_spectrumview->setSpectrum(spec); m_spectrumStack->setCurrentWidget(m_spectrumview); } else { m_spectrumLabel->setText(i18n("No spectrum of %1 found.", element_name)); m_spectrumStack->setCurrentWidget(m_spectrumLabel); } } QString DetailedInfoDlg::createWikiLink(QString link) { return createWikiLink(link, link); } QString DetailedInfoDlg::createWikiLink(QString link, QString displayString) { QString html; QString language(QLocale().uiLanguages().first()); //Wikipedia.org html.append (" "); html.append (displayString); html.append (""); // Example from the comment "http://en.wikipedia.org/wiki/hydrogen" return html; } void DetailedInfoDlg::slotLinkClicked(const QUrl &url) { if (url.isEmpty() || !url.isValid()) { return; } - KRun::runUrl(url, QStringLiteral("text/html"), nullptr); + KRun::runUrl(url, QStringLiteral("text/html"), this, KRun::RunFlags(), QString(), QByteArray()); } void DetailedInfoDlg::slotHelp() { //TODO fix this stuff... #if 0 QString chapter = "infodialog_overview"; switch (activePageIndex()) { case 0: chapter = "infodialog_overview"; break; case 1: chapter = "infodialog_orbits"; break; case 2: chapter = "infodialog_chemical"; break; case 3: chapter = "infodialog_energies"; break; case 4: chapter = "infodialog_misc"; break; case 5: chapter = "infodialog_spectrum"; break; case 6: chapter = "infodialog_warnings"; break; } #endif KHelpClient::invokeHelp("infodialog_spectrum", QLatin1String("kalzium")); } void DetailedInfoDlg::showNextElement() { setElement(pseTables::instance()->getTabletype(m_tableTyp)->nextOf(m_elementNumber)); } void DetailedInfoDlg::showPreviousElement() { setElement(pseTables::instance()->getTabletype(m_tableTyp)->previousOf(m_elementNumber)); } diff --git a/src/detailinfodlg.h b/src/detailinfodlg.h index 63fe6ad5..d72be45b 100644 --- a/src/detailinfodlg.h +++ b/src/detailinfodlg.h @@ -1,142 +1,141 @@ /*************************************************************************** begin : Tue Apr 2 20:43:44 2002 UTC copyright : (C) 2003, 2004, 2005, 2006 by Carsten Niehaus email : cniehaus@kde.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef DETAILINFODLG_H #define DETAILINFODLG_H #include #include -#include #include class DetailedGraphicalOverview; class Element; class KalziumTableType; class OrbitsWidget; class SpectrumViewImpl; class QLabel; class QStackedWidget; class KActionCollection; class KHTMLPart; /** * @brief The dialog which shows all available information of an element * @author Carsten Niehaus */ class DetailedInfoDlg : public KPageDialog { Q_OBJECT public: explicit DetailedInfoDlg(int el, QWidget *parent = nullptr); ~DetailedInfoDlg(); void setElement(int el); // void setOverviewBackgroundColor(const QColor &bgColor); void setTableType(int ktt); /** * add to the numbers @return the beatified string */ QString beautifyOrbitalString(const QString& orbits); private: enum DATATYPE { MISC = 0, ISOTOPES, DATA, /** m_htmlpages; int m_tableTyp; /** * Create the initial set of tabs. Used it *ONLY* once in the * constructor. */ void createContent(); void reloadContent(); QString getHtml(DATATYPE); QString m_baseHtml; QString m_baseHtml2; //X QString m_picsdir; /** * Add a new HTML page to the dialog. * * @param title The title of the tab, appears above the htmlview * @param icontext The name of the tab, appears belov or instead * of the icon * @param iconname The name of the icon * @returns the pointer to the resulting KHTMLPart, needed for * writing HTML code on it */ KHTMLPart* addHTMLTab(const QString& title, const QString& icontext, const QString& iconname); /** * Change the HTML code in an HTML page. * * @param htmlpart the KHTMLPart to edit * @param htmlcode the HTML code to display */ void fillHTMLTab(KHTMLPart* htmlpart, const QString& htmlcode); /** * Creates a localized link to Wikipedia. * http://en.wikipedia.org/wiki/link" * @param link the link inside wikipedia * @param displayString the displayed string to click on. */ QString createWikiLink(QString link, QString displayString); /// overloaded function to add link as the displayed String QString createWikiLink(QString link); private slots: void slotLinkClicked(const QUrl &url); void showNextElement(); void showPreviousElement(); /** * invoke the help of the correct chapter */ virtual void slotHelp(); signals: void elementChanged(int); }; #endif // DETAILINFODLG_H diff --git a/src/elementdataviewer.cpp b/src/elementdataviewer.cpp index bf54ad6b..37a24bf7 100644 --- a/src/elementdataviewer.cpp +++ b/src/elementdataviewer.cpp @@ -1,534 +1,544 @@ /*************************************************************************** copyright : (C) 2004, 2005, 2006 by Carsten Niehaus email : cniehaus@kde.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "elementdataviewer.h" #include #include #include -#include -#include -#include -#include -#include #include "prefs.h" +#include #include -#include +#include +#include +#include +#include +#include //QT-Includes +#include +#include #include #include +#include #include -#include +#include AxisData::AxisData(AXISTYPE type) : currentDataType(-1) { m_type = type; } double AxisData::value(int element) const { if ((element < 1) || (element > dataList.count())) { return 0.0; } return dataList[element - 1]; } ElementDataViewer::ElementDataViewer(QWidget *parent) - : KDialog(parent), + : QDialog(parent), m_yData(new AxisData(AxisData::Y)), m_xData(new AxisData(AxisData::X)) { - setCaption(i18n("Plot Data")); - setButtons(Help | Close); - setDefaultButton(Close); + setWindowTitle(i18n("Plot Data")); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Close); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + connect(buttonBox, &QDialogButtonBox::accepted, this, &ElementDataViewer::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &ElementDataViewer::reject); + mainLayout->addWidget(buttonBox); + buttonBox->button(QDialogButtonBox::Close)->setDefault(true); KalziumDataObject *kdo = KalziumDataObject::instance(); - ui.setupUi(mainWidget()); + ui.setupUi(mainWidget); m_timer = new QTimer(this); m_timer->setSingleShot(true); // setup the list of names foreach (Element *e, kdo->ElementList) { names << e->dataAsString(ChemicalDataObject::name); symbols << e->dataAsString(ChemicalDataObject::symbol); elecConfig<< e->dataAsString(ChemicalDataObject::electronicConfiguration); block << e->dataAsString(ChemicalDataObject::periodTableBlock); } m_actionCollection = new KActionCollection (this); KStandardAction::quit(this, SLOT(close()), m_actionCollection); - connect(m_timer, SIGNAL(timeout()), - this, SLOT(drawPlot())); - connect(ui.KCB_y, SIGNAL(activated(int)), - this, SLOT(rangeChanged())); - connect(ui.KCB_x, SIGNAL(activated(int)), - this, SLOT(rangeChanged())); - connect(ui.comboElementLabels, SIGNAL(activated(int)), - this, SLOT(rangeChanged())); - connect(ui.comboElementType,SIGNAL(activated(int)), - this, SLOT(rangeChanged())); - connect(ui.from, SIGNAL(valueChanged(int)), - this, SLOT(rangeChanged())); - connect(ui.to, SIGNAL(valueChanged(int)), - this, SLOT(rangeChanged())); - connect(this, SIGNAL(helpClicked()), - this, SLOT(slotHelp())); - connect(ui.full, SIGNAL(clicked()), - this, SLOT(fullRange())); + connect(m_timer, &QTimer::timeout, + this, &ElementDataViewer::drawPlot); + connect(ui.KCB_y, QOverload::of(&KComboBox::activated), + this, &ElementDataViewer::rangeChanged); + connect(ui.KCB_x, QOverload::of(&KComboBox::activated), + this, &ElementDataViewer::rangeChanged); + connect(ui.comboElementLabels, QOverload::of(&KComboBox::activated), + this, &ElementDataViewer::rangeChanged); + connect(ui.comboElementType, QOverload::of(&KComboBox::activated), + this, &ElementDataViewer::rangeChanged); + connect(ui.from, QOverload::of(&QSpinBox::valueChanged), + this, &ElementDataViewer::rangeChanged); + connect(ui.to, QOverload::of(&QSpinBox::valueChanged), + this, &ElementDataViewer::rangeChanged); + connect(buttonBox->button(QDialogButtonBox::Help), &QPushButton::clicked, + this, &ElementDataViewer::slotHelp); + connect(ui.full, &QPushButton::clicked, + this, &ElementDataViewer::fullRange); drawPlot(); resize(650, 500); } ElementDataViewer::~ElementDataViewer() { delete m_yData; delete m_xData; } void ElementDataViewer::slotHelp() { KHelpClient::invokeHelp("plot_data", "kalzium"); } void ElementDataViewer::rangeChanged() { if (ui.from->value() > ui.to->value()) { ui.to->setValue(ui.from->value()); } m_timer->stop(); m_timer->start(500); } void ElementDataViewer::fullRange() { ui.from ->setValue(1); ui.to ->setValue(116); } void ElementDataViewer::setLimits() { qDebug() << "ElementDataViewer::setLimits()"; double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0; getMinMax(x1, x2, m_xData); getMinMax(y1, y2, m_yData); qDebug() << x1 << " :: " << x2 << " ----- " << y1 << " :: " << y2; //JH: add some padding to show all points double dx = 0.05*(x2-x1); double dy = 0.05*(y2-y1); x1 -= dx; x2 += dx; y1 -= dy; y2 += dy; //X // try to put a small padding to make the points on the axis visible //X double dx = (to - from + 1) / 25 + 1.0; //X double dy = (maxY - minY) / 10.0; //X // in case that dy is quite small (for example, when plotting a single //X // point) //X if (dy < 1e-7) //X dy = maxY / 10.0; //X ui.plotwidget->setLimits(from - dx, to + dx, minY - dy, maxY + dy); ui.plotwidget->setLimits(x1, x2, y1, y2); } void ElementDataViewer::getMinMax(double& min, double& max, AxisData * data) { int firstElement = ui.from->value(); int lastElement = ui.to->value(); double minValue = data->value(firstElement); double maxValue = data->value(firstElement); qDebug() << "Taking elements from " << firstElement << " to " << lastElement; for (int _currentVal = firstElement; _currentVal <= lastElement; ++_currentVal) { //go over all selected elements double v = data->value(_currentVal); if (minValue > v) { minValue = v; } if (maxValue < v) { maxValue = v; } } qDebug() << "The value are ]"<< minValue << " , " << maxValue << "[."; min = minValue; max = maxValue; } void ElementDataViewer::keyPressEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_Plus: case Qt::Key_Equal: slotZoomIn(); break; case Qt::Key_Minus: case Qt::Key_Underscore: slotZoomOut(); break; case Qt::Key_Escape: close(); break; } } void ElementDataViewer::slotZoomIn() {} void ElementDataViewer::slotZoomOut() {} void ElementDataViewer::setupAxisData(AxisData *data) { int selectedData = 0; if (data->type() == AxisData::X) { selectedData = ui.KCB_x->currentIndex(); } else { selectedData = ui.KCB_y->currentIndex(); } data->currentDataType = selectedData; // init to _something_ ChemicalDataObject::BlueObelisk kind = ChemicalDataObject::mass; QString caption; int unit = KUnitConversion::NoUnit; switch (selectedData) { case AxisData::NUMBER: { kind = ChemicalDataObject::atomicNumber; caption = i18n("Atomic Number"); break; } case AxisData::MASS: { kind = ChemicalDataObject::mass; caption = i18n("Atomic Mass"); break; } case AxisData::EN: { kind = ChemicalDataObject::electronegativityPauling; caption = i18n("Electronegativity"); break; } case AxisData::MELTINGPOINT: { kind = ChemicalDataObject::meltingpoint; caption = i18n("Melting Point"); unit = Prefs::temperatureUnit(); break; } case AxisData::BOILINGPOINT: { kind = ChemicalDataObject::boilingpoint; caption = i18n("Boiling Point"); unit = Prefs::temperatureUnit(); break; } case AxisData::ATOMICRADIUS: { kind = ChemicalDataObject::radiusVDW; caption = i18n("Atomic Radius"); unit = Prefs::lengthUnit(); break; } case AxisData::COVALENTRADIUS: { kind = ChemicalDataObject::radiusCovalent; caption = i18n("Covalent Radius"); unit = Prefs::lengthUnit(); break; } } KalziumDataObject *kdo = KalziumDataObject::instance(); DoubleList dblDataList; foreach (Element * element, kdo->ElementList) { dblDataList << element->dataAsVariant(kind, unit).toDouble(); } data->dataList.clear(); data->dataList << dblDataList; data->kind = kind; if (unit != KUnitConversion::NoUnit) { QString stringUnit = KalziumDataObject::instance()->unitAsString(unit); data->unit = QString(' ' + stringUnit); caption.append(" ["); caption.append(stringUnit); caption.append(']'); } if (data->type() == AxisData::X) { ui.plotwidget->axis(KPlotWidget::BottomAxis)->setLabel(caption); } else { ui.plotwidget->axis(KPlotWidget::LeftAxis)->setLabel(caption); ui.plotwidget->axis(KPlotWidget::RightAxis)->setLabel(caption); } } void ElementDataViewer::drawPlot() { /* * to be 100% safe delete the old list */ ui.plotwidget->removeAllPlotObjects(); /* * spare the next step in case everything is already set and done */ if (m_yData->currentDataType != ui.KCB_y->currentIndex()) { initData(); } if (m_xData->currentDataType != ui.KCB_x->currentIndex()) { initData(); } /* * if the user selected the elements 20 to 30 the list-values are 19 to 29!!! */ const int tmpfrom = ui.from->value(); const int tmpto = ui.to->value(); const int from = qMin(tmpfrom, tmpto); const int to = qMax(tmpfrom, tmpto); /* * The number of elements. #20 to 30 are 30-20+1=11 Elements */ int num = to - from + 1; setLimits(); QSet metals, metalloids, nonMetals; metals << 3 << 4 << 11 << 12 << 13; for (int i = 19; i <= 31; ++i) { metals << i; } for (int i = 37; i <= 50; ++i) { metals << i; } for (int i = 55; i <= 83; ++i) { metals << i; } for (int i = 87; i <= 116; ++i) { metals << i; } metalloids << 5 << 14 << 32 << 33 << 51 << 52 << 84 << 85; nonMetals << 1 << 2 << 6 << 7 << 8 << 9 << 10 << 15 << 16; nonMetals << 17 << 18 << 34 << 35 << 36 << 53 << 54 << 86; /* * check if the users wants to see the elementnames or not */ int whatShow = ui.comboElementLabels->currentIndex(); /* * Checks what type of element, the user wants to plot. * example, metal, non-metal. */ int whichType = ui.comboElementType->currentIndex(); KPlotObject* dataPointGreen = nullptr; KPlotObject* dataPointRed = nullptr; double av_x = 0.0; double max_x = m_xData->value(from); double min_x = m_xData->value(from); double av_y = 0.0; double max_y = m_yData->value(from); double min_y = m_yData->value(from); /* * iterate for example from element 20 to 30 and contruct * the KPlotObjects */ dataPointGreen = new KPlotObject( Qt::green, KPlotObject::Points, 4, KPlotObject::Star); dataPointGreen->setLabelPen(QPen(Qt::blue)); dataPointRed = new KPlotObject( Qt::red, KPlotObject::Points, 4, KPlotObject::Star); //Star can be replaced with a cross dataPointRed->setLabelPen(QPen(Qt::blue)); for (int i = from; i < to + 1; ++i) { double value_y = m_yData->value(i); double value_x = m_xData->value(i); bool known = ((value_y) > 0.0) ? 1 : 0; //The element is know if its value is not zero bool belongs = 1; //The value of belongs is one if it belongs to the particular group //See if the particular element belongs to the selected set or not. //If a particular group of elements is selected, if (whichType > 0) { belongs = 0; switch (whichType) { case 1: //Plot only metals belongs = metals . contains(i); break; case 2: //plot only nonmetals and metalloids belongs = (nonMetals.contains(i) || metalloids.contains(i)); break; case 3: //Plot s block elements belongs = (block[i - 1]== "s"); break; case 4: //Plot p block elements belongs = (block[i - 1]== "p"); break; case 5: //Plot d block elements belongs = (block[i - 1]== "d"); break; case 6: //plot f block elements belongs = (block[i - 1]== "f"); break; case 7: // Noble gases belongs = ((elecConfig[i - 1]) . endsWith(QLatin1String("p6"))); belongs |= (i == 2); //Include Helium break; case 8: // Alkalie metals belongs = ((elecConfig[i - 1]) . endsWith(QLatin1String("s1"))); belongs &= (block[i - 1]== "s"); //exclude chromium belongs &= (i != 1); //exclude Hydrogen break; case 9: // Alkaline earth metals belongs = ((elecConfig[i - 1]) . endsWith(QLatin1String("s2"))); belongs &= (block[i - 1]== "s"); //exclude chromium belongs &= (i != 2); //exclude Helium break; case 10: // Lanthanides // If element i is an f block element, with // electronic configuration containing "f4" in it // or the element is Lanthanum belongs = ((block[i - 1]== "f") && \ ((elecConfig[i - 1]) . contains ("4f"))) || \ (i == 57); //Lanthanum 57 break; case 11: //Actinides //If element i is an f block element, with // electronic configuration containing "f5" in it // or the element is Actinium belongs = (((block[i - 1]== "f")) && \ ((elecConfig[i - 1]) . contains ("5f"))) || \ (i == 89); //Actinium 89 break; case 12: //Radio active belongs = ((i == 43) || (i == 61) || (i > 84)); // Technitium prothomium and then polonium onwards. break; default: whichType = 0; belongs = 1; } } if (belongs) { if (known) { av_x += value_x; av_y += value_y; if (value_x > max_x) { max_x = value_x; } if (value_y > max_y) { max_y = value_y; } if (value_x < min_x) { min_x = value_x; } if (value_y < min_y) { min_y = value_y; } QString lbl; if (whatShow > 0) { //The users wants to see the labels lbl = whatShow == 1 ? names[i-1] : symbols[i-1]; } dataPointGreen->addPoint(value_x, value_y, lbl); } else { //unknown value //num is required while finding the average, if an element is not //known it should not contribute to the average. --num; QString lbl; if (whatShow > 0) { //The user wants to see the labels lbl = whatShow == 1 ? names[i - 1] : symbols[i - 1]; } dataPointRed->addPoint(value_x, value_y, lbl); //For an Unknown value, use a red point to mark the data-point. } } else { //The element does not belong to the set //num is required while finding average, if an element is //not in the selected set, it should not contribute to the avg. --num; } } ui.plotwidget->addPlotObject(dataPointGreen); ui.plotwidget->addPlotObject(dataPointRed); if (num > 0) { //now set the values for the min, max and avarage value ui.av_x->setText(QString::number(av_x / num).append(m_xData->unit)); ui.minimum_x->setText(QString::number(min_x).append(m_xData->unit)); ui.maximum_x->setText(QString::number(max_x).append(m_xData->unit)); ui.av_y->setText(QString::number(av_y / num).append(m_yData->unit)); ui.minimum_y->setText(QString::number(min_y).append(m_yData->unit)); ui.maximum_y->setText(QString::number(max_y).append(m_yData->unit)); } else { ui.av_x->setText(QString::number(0.0)); ui.minimum_x->setText(QString::number(0.0)); ui.maximum_x->setText(QString::number(0.0)); ui.av_y->setText(QString::number(0.0)); ui.minimum_y->setText(QString::number(0.0)); ui.maximum_y->setText(QString::number(0.0)); } } void ElementDataViewer::initData() { setupAxisData(m_xData); setupAxisData(m_yData); } diff --git a/src/elementdataviewer.h b/src/elementdataviewer.h index 0888e49a..8c4124bc 100644 --- a/src/elementdataviewer.h +++ b/src/elementdataviewer.h @@ -1,148 +1,148 @@ /*************************************************************************** copyright : (C) 2004, 2005, 2006 by Carsten Niehaus email : cniehaus@kde.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef ELEMENTDATAVIEWER_H #define ELEMENTDATAVIEWER_H -#include +#include #include "ui_plotsetupwidget.h" #include "kalziumdataobject.h" #include "kalziumutils.h" class QTimer; class KActionCollection; typedef QList DoubleList; /** * @short the values of an axis * @author Carsten Niehaus */ class AxisData { public: /** * This represents the possible datasets. */ enum PAXISDATA { NUMBER = 0, MASS, EN, MELTINGPOINT, BOILINGPOINT, ATOMICRADIUS, COVALENTRADIUS }; enum AXISTYPE { X = 0, Y }; AxisData(AxisData::AXISTYPE); /** * @return the value of the selected dataset of element @p element */ double value(int element) const; /** * the dataList contains the values off all elements * but only of the currently selected data type. This * means that it eg contains all boiling points */ DoubleList dataList; QString unit; int currentDataType; ChemicalDataObject::BlueObelisk kind; AXISTYPE type() const { return m_type; } private: AXISTYPE m_type; }; /** * @short This widget shows the plot and the widget * where you can setup the plot * @author Carsten Niehaus */ -class ElementDataViewer : public KDialog +class ElementDataViewer : public QDialog { Q_OBJECT public: ElementDataViewer(QWidget *parent = nullptr); ~ElementDataViewer(); /** * the AxixData for the y-Axis */ AxisData *m_yData; /** * the AxixData for the x-Axis */ AxisData *m_xData; protected: void keyPressEvent(QKeyEvent *e) override; private: Ui::PlotSetupWidget ui; void getMinMax(double& min, double& max, AxisData * data); QStringList names; QStringList symbols; QStringList elecConfig; //Electronic configuration of elements QStringList block; //Indicates the periodic table block s,p,d,f... QTimer *m_timer; KActionCollection* m_actionCollection; void initData(); void setupAxisData(AxisData * data); void setLimits(); protected slots: /** * invoke the help of the correct chapter */ virtual void slotHelp(); private slots: void rangeChanged(); void fullRange(); public slots: void slotZoomIn(); void slotZoomOut(); /** * draws the plot */ void drawPlot(); }; #endif // ELEMENTDATAVIEWER_H diff --git a/src/eqchemview.cpp b/src/eqchemview.cpp index ec485878..6df66e0a 100644 --- a/src/eqchemview.cpp +++ b/src/eqchemview.cpp @@ -1,112 +1,110 @@ /*************************************************************************** * Copyright (C) 2004, 2005, 2006 by Thomas Nagy * * Copyright (C) 2006 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "eqchemview.h" #include #include -#include - #include #include "ui_equationview.h" #include #include #ifdef HAVE_FACILE extern "C" { char* solve_equation(const char *); } #else char* solve_equation(const char *) { return NULL; } #endif void EQChemDialog::compute() { QString equation(ui.lineEdit->text()); equation.replace("->", " -> "); equation.append(' '); equation.prepend(' '); char * result = solve_equation(equation.toLatin1().constData()); QString answer = QString(result); qDebug() << "Answer: " << answer; ui.answer_label->setText(answer); // mem leak ? free(result); } EQChemDialog::EQChemDialog(QWidget *parent) : QWidget(parent) { ui.setupUi(this); LineEditUrlDropEventFilter *dropUrlEventFilter = new LineEditUrlDropEventFilter(parent); dropUrlEventFilter->installEventFilter(ui.lineEdit); ui.lblHelp->setText(getHelpText()); connect(ui.calculateButton, SIGNAL(clicked()), this, SLOT(compute())); connect(ui.btnCopy, SIGNAL(clicked()), this, SLOT(copyAnswer())); } void EQChemDialog::copyAnswer() { qDebug() << "EQChemDialog::copyAnswer()"; QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(ui.answer_label->text(), QClipboard::Clipboard); } const QString EQChemDialog::getHelpText() { return i18nc( "Help text for the chemical equation solver", "The equation solver allows you to balance a chemical equation.
" "
" "Using Variables
" "To express variable quantities of an element, put a single character in front " "of the element's symbol, as shown in this example:
" "aH + bO -> 5H2O (Result: 10 H + 5 O -> 5 H2O)
" "Solving this expression will give you the needed amount of Hydrogen and Oxygen.
" "
" "Defining electric charges
" "Use box brackets to specify the electric charge of an element, as shown in this example:
" "4H[+] + 2O -> cH2O[2+] (Result: 4 H+ + 2 O -> 2 H2O2+)" ); } QSize EQChemDialog::sizeHint() const { QSize size; size.setWidth(200); return size; } #include "eqchemview.moc" diff --git a/src/exportdialog.cpp b/src/exportdialog.cpp index 960c030b..6ac29d24 100644 --- a/src/exportdialog.cpp +++ b/src/exportdialog.cpp @@ -1,241 +1,263 @@ /*************************************************************************** copyright : (C) 2007 by Johannes Simon email : johannes.simon@gmail.com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "exportdialog.h" #include "kalziumutils.h" -#include -#include -#include #include +#include +#include +#include +#include +#include + +#include +#include +#include #include +#include + static const char HTML_HEADER[] = "" "\n" "\n" "\n" "\n" "\n"; static const char HTML_FOOTER[] = "\n" "\n"; static const char XML_HEADER[] = "\n"; ElementListEntry::ElementListEntry(Element * element) : QListWidgetItem() { m_atomicNum = element->dataAsVariant(ChemicalDataObject::atomicNumber).toInt(); m_name = element->dataAsString(ChemicalDataObject::name); m_element = element; setText(m_name); } ElementListEntry::~ElementListEntry() { } PropertyListEntry::PropertyListEntry(const QString & name, ChemicalDataObject::BlueObelisk type) : QListWidgetItem() { setText(name); m_type = type; } PropertyListEntry::~PropertyListEntry() { } ExportDialog::ExportDialog(QWidget * parent) - : KDialog(parent),m_outputStream(nullptr) + : QDialog(parent),m_outputStream(nullptr) { qDebug() << "ExportDialog::ExportDialog"; - setButtons(Help | User1 | Cancel); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel|QDialogButtonBox::Help); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + QPushButton *user1Button = new QPushButton; + buttonBox->addButton(user1Button, QDialogButtonBox::ActionRole); + connect(buttonBox, &QDialogButtonBox::accepted, this, &ExportDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &ExportDialog::reject); + mainLayout->addWidget(buttonBox); qDebug() << "ExportDialog: setButtons"; - ui.setupUi(mainWidget()); - qDebug() << "ExportDialog: ui.setupUi(mainWidget());"; - setButtonGuiItem(User1, KGuiItem(i18n("OK"))); + ui.setupUi(mainWidget); + qDebug() << "ExportDialog: ui.setupUi(mainWidget)"; + KGuiItem::assign(user1Button, KGuiItem(i18n("OK"))); qDebug() << "ExportDialog: setButtonGuiItem(User1, KGuiItem(i18n(\"OK\")));"; ui.targetFile->setMode(KFile::File | KFile::Directory | KFile::LocalOnly); qDebug() << "ui.targetFile->setMode(KFile::File | KFile::Directory | KFile::LocalOnly);"; - setCaption(i18n("Export Chemical Data")); + setWindowTitle(i18n("Export Chemical Data")); qDebug() << "ui.targetFile->setMode(KFile::File | KFile::Directory | KFile::LocalOnly);"; populateElementList(); qDebug() << "ui.targetFile->setMode(KFile::File | KFile::Directory | KFile::LocalOnly);"; ui.formatList->addItem(".html (formatted html document)", "html"); ui.formatList->addItem(".xml (raw element data)", "xml"); ui.formatList->addItem(".csv (comma-separated data)", "csv"); qDebug() << "ui.formatList->addItem(...);"; - connect(this, SIGNAL(user1Clicked()), this, SLOT(slotOkClicked())); - qDebug() << "connect(this, SIGNAL(user1Clicked()), this, SLOT(slotOkClicked()));"; - setHelp(QString(),"kalzium"); - qDebug() << "setHelp(QString(),\"kalzium\");"; + connect(user1Button, &QPushButton::clicked, this, &ExportDialog::slotOkClicked); + qDebug() << "connect(user1Button, SIGNAL(clicked()), this, SLOT(slotOkClicked()));"; + connect(buttonBox, &QDialogButtonBox::helpRequested, this, &ExportDialog::slotHelpRequested); + qDebug() << "KHelpClient::invokeHelp(QString(), \"kalzium\");"; } ExportDialog::~ExportDialog() { delete m_outputStream; } void ExportDialog::populateElementList() { // Add descriptive headers QListWidgetItem *header1 = new QListWidgetItem(i18n("Elements")); QListWidgetItem *header2 = new QListWidgetItem(i18n("Properties")); header1->setFlags(Qt::ItemIsEnabled); header2->setFlags(Qt::ItemIsEnabled); QFont font; font.setBold(true); header1->setFont(font); header2->setFont(font); ui.elementListWidget->addItem(header1); ui.propertyListWidget->addItem(header2); // Add elements foreach (Element *element, KalziumDataObject::instance()->ElementList) { ElementListEntry *entry = new ElementListEntry(element); ui.elementListWidget->addItem(entry); } ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Atomic Number"), ChemicalDataObject::atomicNumber)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Symbol"), ChemicalDataObject::symbol)); //ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Name"), ChemicalDataObject::name)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Mass"), ChemicalDataObject::mass)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Exact Mass"), ChemicalDataObject::exactMass)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Ionization"), ChemicalDataObject::ionization)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Electron Affinity"), ChemicalDataObject::electronAffinity)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Electronegativity"), ChemicalDataObject::electronegativityPauling)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Covalent Radius"), ChemicalDataObject::radiusCovalent)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Van der Waals Radius"), ChemicalDataObject::radiusVDW)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Melting Point"), ChemicalDataObject::meltingpoint)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Boiling Point"), ChemicalDataObject::boilingpoint)); ui.propertyListWidget->addItem(new PropertyListEntry(i18n("Family"), ChemicalDataObject::family)); } void ExportDialog::slotOkClicked() { QString format = ui.formatList->itemData(ui.formatList->currentIndex(), Qt::UserRole).toString(); QString filename = ui.targetFile->url().toLocalFile(); if (!filename.endsWith(format)) { filename += '.' + format; } QFile outputFile(filename); if (outputFile.exists()) { if (KMessageBox::questionYesNo(this, i18n("File already exists. Do you want to overwrite it?")) == KMessageBox::No) { return; } } if (!outputFile.open(QIODevice::WriteOnly)) { KMessageBox::error(this, i18n("Could not open file for writing.")); return; } delete m_outputStream; m_outputStream = new QTextStream(&outputFile); if (format == "html") { exportToHtml(); } else if (format == "xml") { exportToXml(); } else { exportToCsv(); } // close the dialog done(0); } +void ExportDialog::slotHelpRequested() +{ + KHelpClient::invokeHelp(QString(), "kalzium"); +} + void ExportDialog::exportToHtml() { *m_outputStream << HTML_HEADER << "\n"; foreach (QListWidgetItem *element, ui.elementListWidget->selectedItems()) { *m_outputStream << "\n\n\n"; foreach (QListWidgetItem *property, ui.propertyListWidget->selectedItems()) { *m_outputStream << "\n\n\n\n"; } } *m_outputStream << "
" << ((ElementListEntry*)element)->m_element->dataAsString(ChemicalDataObject::name) << "
" << ((PropertyListEntry*) property)->text() << "" << KalziumUtils::prettyUnit( ((ElementListEntry*) element)->m_element, ((PropertyListEntry*) property)->m_type) << "
\n" << HTML_FOOTER; } void ExportDialog::exportToXml() { *m_outputStream << XML_HEADER << "\n"; foreach (QListWidgetItem *element, ui.elementListWidget->selectedItems()) { *m_outputStream << " m_element->dataAsString(ChemicalDataObject::name) << "\">\n"; foreach (QListWidgetItem *property, ui.propertyListWidget->selectedItems()) { *m_outputStream << " text() << "\">" << KalziumUtils::prettyUnit( ((ElementListEntry*) element)->m_element, ((PropertyListEntry*) property)->m_type) << "\n"; } *m_outputStream << " \n"; } *m_outputStream << "\n"; } void ExportDialog::exportToCsv() { *m_outputStream << "Name"; foreach (QListWidgetItem *property, ui.propertyListWidget->selectedItems()) { *m_outputStream << ", \"" << ((PropertyListEntry*) property)->text() << "\""; } *m_outputStream << "\n"; foreach (QListWidgetItem *element, ui.elementListWidget->selectedItems()) { *m_outputStream << "\"" << ((ElementListEntry*) element)->m_element->dataAsString(ChemicalDataObject::name) << "\""; foreach (QListWidgetItem *property, ui.propertyListWidget->selectedItems()) { *m_outputStream << ", \"" << KalziumUtils::prettyUnit( ((ElementListEntry*) element)->m_element, ((PropertyListEntry*) property)->m_type) << "\""; } *m_outputStream << "\n"; } } diff --git a/src/exportdialog.h b/src/exportdialog.h index c9500092..547f3f8b 100644 --- a/src/exportdialog.h +++ b/src/exportdialog.h @@ -1,69 +1,74 @@ /*************************************************************************** copyright : (C) 2007 by Johannes Simon email : johannes.simon@gmail.com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef EXPORTDIALOG_H #define EXPORTDIALOG_H #include #include -#include +#include #include "kalziumdataobject.h" #include "ui_exportdialog.h" class KDialog; class ElementListEntry : public QListWidgetItem { public: ElementListEntry(Element *element); ~ElementListEntry(); int m_atomicNum; QString m_name; Element *m_element; }; class PropertyListEntry : public QListWidgetItem { public: PropertyListEntry(const QString & name, ChemicalDataObject::BlueObelisk type); ~PropertyListEntry(); ChemicalDataObject::BlueObelisk m_type; }; /** * @author: Johannes Simon */ -class ExportDialog : public KDialog +class ExportDialog : public QDialog { Q_OBJECT public: ExportDialog(QWidget *parent); ~ExportDialog(); void populateElementList(); void exportToHtml(); void exportToXml(); void exportToCsv(); private: Ui::exportDialogForm ui; QTextStream *m_outputStream; public slots: void slotOkClicked(); + /** + * Open help page + */ + void slotHelpRequested(); + }; #endif // EXPORTDIALOG_H diff --git a/src/isotopetable/isotopeitem.cpp b/src/isotopetable/isotopeitem.cpp index b98155d2..ad68b8f4 100644 --- a/src/isotopetable/isotopeitem.cpp +++ b/src/isotopetable/isotopeitem.cpp @@ -1,143 +1,143 @@ /*************************************************************************** * Copyright (C) 2005-2008 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "isotopeitem.h" #include "isotopescene.h" #include #include #include #include #include -#include +#include IsotopeItem::IsotopeItem(Isotope *i, qreal x, qreal y, qreal width, qreal height, QGraphicsItem *parent) : QAbstractGraphicsShapeItem(parent) { m_rect = QRectF(0, 0, width, height); setPos(x, y); m_isotope = i; m_type = getType(m_isotope); QBrush b; switch (m_type) { case alpha: b = QBrush(Qt::red); break; case ec: b = QBrush(Qt::blue); break; case multiple: b = QBrush(Qt::green); break; case bplus: b = QBrush(Qt::yellow); break; case bminus: b = QBrush(Qt::white); break; case stable: b = QBrush(Qt::lightGray); break; default: b = QBrush(Qt::darkGray); break; } setBrush(b); m_symbolFont = QFont("Arial", 3 ,QFont::Bold); m_otherFont = QFont("Arial", 1 ,QFont::Bold); setFlag(QGraphicsItem::ItemIsMovable, false); setFlag(QGraphicsItem::ItemIsSelectable, false); setCacheMode(QGraphicsItem::DeviceCoordinateCache); setToolTip(i18n("Isotope of Element %1 (%2)", m_isotope->parentElementNumber(), m_isotope->parentElementSymbol())); } void IsotopeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget) const qreal lod = option->levelOfDetailFromTransform(painter->worldTransform()); if (lod > 0.3) { painter->setPen(pen()); } else { painter->setPen(Qt::NoPen); } painter->setBrush(brush()); painter->drawRect(m_rect); if (lod >= 1.0) { // FIXME: Get rid of magic numbers and rather dynamically calculate them QRectF r1(m_rect.translated(0.0, 2.5)); painter->setFont(m_symbolFont); painter->drawText(r1, Qt::AlignHCenter | Qt::TextDontClip, m_isotope->parentElementSymbol());//, s->parentElementNumber() if (lod >= 4.0) { QRectF r2(m_rect.topLeft() + QPointF(1.0, 0.5), m_rect.size() / 2.0); QRectF r3(m_rect.topLeft() + QPointF(6.0, 0.5) , m_rect.size() / 2.0); painter->setFont(m_otherFont); painter->drawText(r2, Qt::AlignHCenter | Qt::TextDontClip, QString::number(m_isotope->parentElementNumber())); painter->drawText(r3, Qt::AlignHCenter | Qt::TextDontClip, QString::number(m_isotope->nucleons())); } } } IsotopeItem::IsotopeType IsotopeItem::getType(Isotope * isotope) { //TODO Here I need a clever way to find out *what* to return. if (isotope->alphalikeliness() > 60.0) { return IsotopeItem::alpha; } if (isotope->betaminuslikeliness() > 60.0) { return IsotopeItem::bminus; } if (isotope->betapluslikeliness() > 60.0) { return IsotopeItem::bminus; } if (isotope->eclikeliness() > 60.0) { return IsotopeItem::ec; } else { return IsotopeItem::stable; } } void IsotopeItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->button() != Qt::RightButton) { event->ignore(); return; } IsotopeScene *scene2 = static_cast(scene()); scene2->updateContextHelp(this); } diff --git a/src/isotopetable/isotopetabledialog.cpp b/src/isotopetable/isotopetabledialog.cpp index 4023ba50..056b3b30 100644 --- a/src/isotopetable/isotopetabledialog.cpp +++ b/src/isotopetable/isotopetabledialog.cpp @@ -1,107 +1,115 @@ /*************************************************************************** * Copyright (C) 2005-2008 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "isotopetabledialog.h" #include "isotopeitem.h" #include "isotopescene.h" #include "legendwidget.h" #include "kalziumschemetype.h" #include -#include - +#include #include -#include +#include +#include +#include +#include -IsotopeTableDialog::IsotopeTableDialog(QWidget* parent) : KDialog(parent) +IsotopeTableDialog::IsotopeTableDialog(QWidget* parent) : QDialog(parent) { - setCaption(i18n("Isotope Table")); - setButtons(Close); - setDefaultButton(Close); - ui.setupUi(mainWidget()); + setWindowTitle(i18n("Isotope Table")); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + connect(buttonBox, &QDialogButtonBox::rejected, this, &IsotopeTableDialog::reject); + mainLayout->addWidget(buttonBox); + buttonBox->button(QDialogButtonBox::Close)->setDefault(true); + ui.setupUi(mainWidget); ui.guide->setGuidedView(ui.gv); connect(ui.gv->scene(), SIGNAL(itemSelected(IsotopeItem*)), this, SLOT(updateDockWidget(IsotopeItem*))); connect(ui.gv, SIGNAL(zoomLevelChanged(double)), this, SLOT(slotZoomLevelChanged(double))); connect(ui.Slider, SIGNAL(valueChanged(int)), this, SLOT(zoom(int))); //Here comes the legend part QList< QPair > items; items << qMakePair(i18nc("alpha ray emission", "alpha"), QColor(Qt::red)); items << qMakePair(i18nc("Electron capture method", "EC"), QColor(Qt::blue)); items << qMakePair(i18nc("Many ways", "Multiple"), QColor(Qt::green)); items << qMakePair(i18nc("Beta plus ray emission", "Beta +"), QColor(Qt::yellow)); items << qMakePair(i18nc("Beta minus ray emission", "Beta -"), QColor(Qt::white)); items << qMakePair(i18nc("Stable isotope", "Stable"), QColor(Qt::lightGray)); items << qMakePair(i18nc("Default colour", "default"), QColor(Qt::darkGray)); foreach (const legendPair &pair, items) { LegendItem *item = new LegendItem(pair); ui.infoWidget->layout()->addWidget(item); } ui.infoWidget->setMinimumWidth(150); } void IsotopeTableDialog::zoom (int level) { double zoom = level / 2.0; (ui.gv)->setZoom(zoom); } void IsotopeTableDialog::updateDockWidget(IsotopeItem * item) { Isotope *s = item->isotope(); QString header = i18n("

%1 (%2)

", s->parentElementSymbol(), s->parentElementNumber()); QString mag = i18n("Magnetic moment: %1", s->magmoment().isEmpty()? i18nc("Unknown magnetic moment", "Unknown"):s->magmoment()); QString halflife; if (s -> halflife() > 0.0) { halflife = i18n ("Halflife: %1 %2", s->halflife(), s->halflifeUnit()); } else { halflife = i18n ("Halflife: Unknown"); } QString abundance = i18n("Abundance: %1 %", !s->abundance().isEmpty() ? s->abundance() : "0"); QString nucleons = i18n("Number of nucleons: %1", s->nucleons()); QString spin = i18n("Spin: %1", s->spin().isEmpty()? i18nc("Unknown spin", "Unknown"): s->spin()); QString exactMass = i18n("Exact mass: %1 u", s->mass()); QString html = header + "
" + nucleons + "
" + mag + "
" + exactMass + "
" + spin +"
" + abundance + "
" + halflife; ui.label->setText(html); } void IsotopeTableDialog::slotZoomLevelChanged(double value) { const bool b = ui.Slider->blockSignals(true); ui.Slider->setValue(qreal(value * 2)); ui.Slider->blockSignals(b); } diff --git a/src/isotopetable/isotopetabledialog.h b/src/isotopetable/isotopetabledialog.h index 4db0ab5b..76a78471 100644 --- a/src/isotopetable/isotopetabledialog.h +++ b/src/isotopetable/isotopetabledialog.h @@ -1,52 +1,52 @@ /*************************************************************************** * Copyright (C) 2007, 2008 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef ISOTOPETABLEDIALOG_H #define ISOTOPETABLEDIALOG_H #include "ui_isotopedialog.h" -#include +#include class IsotopeItem; /** * This class is the drawing widget for the whole table * * @author Pino Toscano * @author Carsten Niehaus */ -class IsotopeTableDialog : public KDialog +class IsotopeTableDialog : public QDialog { Q_OBJECT public: explicit IsotopeTableDialog(QWidget* parent = nullptr); private: Ui::isotopeWidget ui; private slots: void updateDockWidget(IsotopeItem *); void zoom(int); void slotZoomLevelChanged(double); }; #endif // ISOTOPETABLEDIALOG_H diff --git a/src/kalzium.cpp b/src/kalzium.cpp index 41b73514..450faf12 100644 --- a/src/kalzium.cpp +++ b/src/kalzium.cpp @@ -1,654 +1,653 @@ /*************************************************************************** copyright : (C) 2003-2007 by Carsten Niehaus email : cniehaus@kde.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "kalzium.h" #include #include #include #include #include "prefs.h" #include "ui_settings_colors.h" #include "ui_settings_gradients.h" #include "ui_settings_calc.h" #include "detailinfodlg.h" #include "detailedgraphicaloverview.h" #include "gradientwidget_impl.h" #include "kalziumdataobject.h" #include "kalziumnumerationtype.h" #include "kalziumschemetype.h" #include "kalziumgradienttype.h" #include "legendwidget.h" #include "exportdialog.h" #include "search.h" #include "searchwidget.h" #include "tableinfowidget.h" #include "psetables.h" #include #ifdef HAVE_FACILE #include "eqchemview.h" #endif #ifdef HAVE_OPENBABEL2 #if defined(HAVE_EIGEN) && defined(HAVE_AVOGADRO) #include "tools/moleculeview.h" #include #endif #include "tools/obconverter.h" #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include #define IDS_ELEMENTINFO 7 Kalzium::Kalzium() : KXmlGuiWindow(nullptr) { setObjectName("KalziumMainWindow"); // Init pointers with null m_infoDialog = nullptr; m_isotopeDialog = nullptr; m_elementDataPlotter = nullptr; m_tablesDialog = nullptr; m_rsDialog = nullptr; m_calculator = nullptr; m_exportDialog = nullptr; m_glossarydlg = nullptr; m_elementInfo = nullptr; // reading the elements from file KalziumDataObject::instance(); Search *newsearch = new Search(); KalziumDataObject::instance()->setSearch(newsearch); // Main pse-Table Tablewidget QWidget *pseTempWidget = new QWidget(this); QVBoxLayout *layout = new QVBoxLayout(pseTempWidget); layout->setMargin(0); layout->setSpacing(2); SearchWidget *searchWidget = new SearchWidget(pseTempWidget); searchWidget->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum)); // Creating the periodic table m_periodicTable = new PeriodicTableView(pseTempWidget); // Connecting the search to the periodic table connect(newsearch, SIGNAL(searchChanged()), KalziumElementProperty::instance(), SIGNAL(propertyChanged())); connect(newsearch, SIGNAL(searchReset()), KalziumElementProperty::instance(), SIGNAL(propertyChanged())); layout->addWidget(searchWidget); layout->addWidget(m_periodicTable); setCentralWidget(pseTempWidget); connect(m_periodicTable->pseScene(), SIGNAL(elementChanged(int)), this, SLOT(openInformationDialog(int))); connect(m_periodicTable->pseScene(), SIGNAL(elementHovered(int)), this, SLOT(elementHover(int))); connect(this, SIGNAL(numerationChanged(int)), m_periodicTable, SIGNAL(numerationChange(int))); // layouting setupSidebars(); setupActions(); setupStatusBar(); } void Kalzium::setupActions() { export_action = actionCollection()->add("file_exporter"); export_action->setText(i18n("&Export Data...")); connect(export_action, SIGNAL(triggered(bool)), this, SLOT(slotShowExportDialog())); // the action for swiching look: color schemes and gradients QStringList schemes = KalziumElementProperty::instance()->schemeList(); /*KalziumSchemeTypeFactory::instance()->schemes();*/ QStringList gradients = KalziumElementProperty::instance()->gradientList(); // the action for swiching look: schemes look_action_schemes = actionCollection()->add("view_look_onlyschemes"); look_action_schemes->setText(i18n("&Scheme")); look_action_schemes->setItems(schemes); look_action_schemes->setToolBarMode(KSelectAction::MenuMode); look_action_schemes->setToolButtonPopupMode(QToolButton::InstantPopup); connect(look_action_schemes, SIGNAL(triggered(int)), this, SLOT(slotSwitchtoLookScheme(int))); // the action for swiching look: gradients look_action_gradients = actionCollection()->add("view_look_onlygradients"); look_action_gradients->setText(i18n("&Gradients")); look_action_gradients->setItems(gradients); look_action_gradients->setToolBarMode(KSelectAction::MenuMode); look_action_gradients->setToolButtonPopupMode(QToolButton::InstantPopup); connect(look_action_gradients, SIGNAL(triggered(int)), this, SLOT(slotSwitchtoLookGradient(int))); // the action for swiching tables QStringList table_schemes = pseTables::instance()->tables(); table_action = actionCollection()->add("view_table"); table_action->setText(i18n("&Tables")); table_action->setItems(table_schemes); table_action->setCurrentItem(Prefs::table()); connect(table_action, SIGNAL(triggered(int)), this, SLOT(slotSwitchtoTable(int))); // the actions for switching numeration numeration_action = actionCollection()->add("view_numerationtype"); numeration_action->setText(i18n("&Numeration")); numeration_action->setItems(KalziumNumerationTypeFactory::instance()->numerations()); numeration_action->setCurrentItem(Prefs::numeration()); connect(numeration_action, SIGNAL(triggered(int)), this, SLOT(slotSwitchtoNumeration(int))); // tools actions m_pPlotAction = actionCollection()->addAction("tools_plotdata"); m_pPlotAction->setText(i18n("&Plot Data...")); m_pPlotAction->setIcon(QIcon::fromTheme("plot")); connect(m_pPlotAction, SIGNAL(triggered()), this, SLOT(slotPlotData())); // calculator actions m_pcalculator = actionCollection()->addAction("tools_calculate"); m_pcalculator->setText(i18n("Perform &Calculations...")); m_pcalculator->setIcon(QIcon::fromTheme("calculate")); m_pcalculator->setWhatsThis(i18nc("WhatsThis Help", "This is the calculator, it performs basic chemical calculations.")); connect(m_pcalculator, SIGNAL(triggered()), this, SLOT(showCalculator())); m_pIsotopeTableAction= actionCollection()->addAction("tools_isotopetable"); m_pIsotopeTableAction->setText(i18n("&Isotope Table...")); m_pIsotopeTableAction->setIcon(QIcon::fromTheme("isotopemap")); m_pIsotopeTableAction->setWhatsThis(i18nc("WhatsThis Help", "This table shows all of the known isotopes of the chemical elements.")); connect(m_pIsotopeTableAction, SIGNAL(triggered()), this, SLOT(slotIsotopeTable())); m_pGlossaryAction = actionCollection()->addAction("tools_glossary"); m_pGlossaryAction->setText(i18n("&Glossary...")); m_pGlossaryAction->setIcon(QIcon::fromTheme("glossary")); connect(m_pGlossaryAction, SIGNAL(triggered()), this, SLOT(slotGlossary())); m_pRSAction = actionCollection()->addAction("tools_rs"); m_pRSAction->setText(i18n("&R/S Phrases...")); m_pRSAction->setIcon(QIcon::fromTheme("kalzium_rs")); connect(m_pRSAction, SIGNAL(triggered()), this, SLOT(slotRS())); m_pOBConverterAction = actionCollection()->addAction("tools_obconverter"); m_pOBConverterAction->setText(i18n("Convert chemical files...")); m_pOBConverterAction->setIcon(QIcon::fromTheme("edit-copy")); m_pOBConverterAction->setWhatsThis(i18nc("WhatsThis Help", "With this tool, you can convert files containing chemical data between various file formats.")); connect(m_pOBConverterAction, SIGNAL(triggered()), this, SLOT(slotOBConverter())); #ifndef HAVE_OPENBABEL2 m_pOBConverterAction->setEnabled(false); #endif m_pMoleculesviewer = actionCollection()->addAction("tools_moleculeviewer"); m_pMoleculesviewer->setText(i18n("Molecular Editor...")); m_pMoleculesviewer->setIcon(QIcon::fromTheme("kalzium_molviewer")); m_pMoleculesviewer->setWhatsThis(i18nc("WhatsThis Help", "This tool allows you to view and edit 3D molecular structures.")); connect(m_pMoleculesviewer, SIGNAL(triggered()), this, SLOT(slotMoleculeviewer())); #if !defined(HAVE_OPENBABEL2) || !defined(HAVE_EIGEN) || !defined(HAVE_AVOGADRO) m_pMoleculesviewer->setEnabled(false); #endif m_pTables = actionCollection()->addAction("tools_tables"); m_pTables->setText(i18n("&Tables...")); m_pTables->setIcon(QIcon::fromTheme("kalzium_tables")); m_pTables->setWhatsThis(i18nc("WhatsThis Help", "This will open a dialog with listings of symbols and numbers related to chemistry.")); connect(m_pTables, SIGNAL(triggered()), this, SLOT(slotTables())); // other period view options m_pLegendAction = m_legendDock->toggleViewAction(); actionCollection()->addAction("view_legend", m_pLegendAction); m_pLegendAction->setIcon(QIcon::fromTheme("legend")); m_pLegendAction->setWhatsThis(i18nc("WhatsThis Help", "This will show or hide the legend for the periodic table.")); m_SidebarAction = m_dockWin->toggleViewAction(); actionCollection()->addAction("view_sidebar", m_SidebarAction); m_SidebarAction->setIcon(QIcon::fromTheme("sidebar")); m_SidebarAction->setWhatsThis(i18nc("WhatsThis Help", "This will show or hide a sidebar with additional information and a set of tools.")); m_SidebarAction = m_tableDock->toggleViewAction(); actionCollection()->addAction("view_tablebar", m_SidebarAction); m_SidebarAction->setIcon(QIcon::fromTheme("kalzium_tables")); m_SidebarAction->setWhatsThis(i18nc("WhatsThis Help", "This will show or hide a sidebar with additional information about the table.")); // the standard actions actionCollection()->addAction("saveAs", KStandardAction::saveAs(this, SLOT(slotExportTable()), actionCollection())); KStandardAction::preferences(this, SLOT(showSettingsDialog()), actionCollection()); actionCollection()->addAction("quit", KStandardAction::quit(qApp, SLOT(quit()), actionCollection())); m_legendWidget->LockWidget(); slotSwitchtoLookGradient(KalziumElementProperty::instance()->gradientId()); slotSwitchtoLookScheme(KalziumElementProperty::instance()->schemeId()); slotSwitchtoNumeration(Prefs::numeration()); slotSwitchtoTable(Prefs::table()); m_legendWidget->UnLockWidget(); m_legendWidget->updateContent(); // set the shell's ui resource file setXMLFile("kalziumui.rc"); setupGUI(); } void Kalzium::setupSidebars() { setDockNestingEnabled(true); m_legendWidget = new LegendWidget(this); m_legendDock = new QDockWidget(i18n("Legend"), this); m_legendDock->setObjectName(QLatin1String("kalzium-legend")); m_legendDock->setFeatures(QDockWidget::AllDockWidgetFeatures); m_legendDock->setWidget(m_legendWidget); connect(m_legendDock, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)), m_legendWidget, SLOT(setDockArea(Qt::DockWidgetArea))); connect(m_legendWidget, SIGNAL(elementMatched(int)), m_periodicTable, SLOT(slotSelectAdditionalElement(int))); connect(m_legendWidget, SIGNAL(resetElementMatch()), m_periodicTable, SLOT(slotUnSelectElements())); m_TableInfoWidget = new TableInfoWidget(this); m_tableDock = new QDockWidget(i18n("Table Information"), this); m_tableDock->setWidget(m_TableInfoWidget); m_tableDock->setObjectName(QLatin1String("kalzium-tableinfo")); m_tableDock->setFeatures(QDockWidget::AllDockWidgetFeatures); m_dockWin = new QDockWidget(i18n("Information"), this); m_dockWin->setObjectName(QLatin1String("kalzium-sidebar")); m_dockWin->setFeatures(QDockWidget::AllDockWidgetFeatures); m_dockWin->setMinimumWidth(250); m_toolbox = new QToolBox(m_dockWin); m_dockWin->setWidget(m_toolbox); m_detailWidget = new DetailedGraphicalOverview(m_toolbox); m_detailWidget->setObjectName("DetailedGraphicalOverview"); m_detailWidget->setMinimumSize(200, m_detailWidget->minimumSize().height()); m_toolbox->addItem(m_detailWidget, QIcon::fromTheme("overview"), i18n("Overview")); m_gradientWidget = new GradientWidgetImpl(m_toolbox); m_gradientWidget->setObjectName("viewtWidget"); connect(m_gradientWidget, SIGNAL(gradientValueChanged(double)), KalziumElementProperty::instance(), SLOT(setSliderValue(double))); connect(m_gradientWidget->scheme_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotSwitchtoLookScheme(int))); connect(m_gradientWidget->gradient_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotSwitchtoLookGradient(int))); m_toolbox->addItem(m_gradientWidget, QIcon::fromTheme("statematter"), i18n("View")); addDockWidget(Qt::LeftDockWidgetArea, m_dockWin); addDockWidget(Qt::BottomDockWidgetArea, m_tableDock, Qt::Horizontal); addDockWidget(Qt::BottomDockWidgetArea, m_legendDock, Qt::Horizontal); m_tableDock->setVisible(false); } void Kalzium::slotExportTable() { - QString fileName = KFileDialog::getSaveFileName(QUrl(), i18n("*.png *.xpm *.jpg *.svg"), // - this, - i18n("Save Kalzium's Table In")); + QString fileName = QFileDialog::getSaveFileName(this, i18n("Save Kalzium's Table In"), QString(), i18n("Image files (*.png *.xpm *.jpg *.svg)")); if (fileName.endsWith(QLatin1String(".svg"))) { m_periodicTable->generateSvg(fileName); } else { QPixmap pix = QPixmap::grabWidget(m_periodicTable); pix.save(fileName); } } void Kalzium::slotGlossary() { if (!m_glossarydlg) { // creating the glossary dialog and loading the glossaries we have m_glossarydlg = new GlossaryDialog(this); m_glossarydlg->setObjectName(QLatin1String("glossary")); QString dir = QStandardPaths::locate(QStandardPaths::DataLocation, "data/", QStandardPaths::LocateDirectory); dir = QFileInfo(dir).absolutePath(); QString picturepath = dir + "/bg.jpg"; QUrl u = QUrl::fromLocalFile(dir + "/knowledge.xml"); Glossary *g = new Glossary(u); g->setName(i18n("Knowledge")); g->setBackgroundPicture(picturepath); m_glossarydlg->addGlossary(g, true); u = QUrl::fromLocalFile(dir + "/tools.xml"); g = new Glossary(u, dir + "/toolpics/"); g->setName(i18n("Tools")); g->setBackgroundPicture(picturepath); m_glossarydlg->addGlossary(g, true); } m_glossarydlg->show(); } void Kalzium::slotRS() { if (!m_rsDialog) { m_rsDialog = new RSDialog(this); } m_rsDialog->show(); } void Kalzium::slotOBConverter() { #ifdef HAVE_OPENBABEL2 KOpenBabel * d = new KOpenBabel(this); d->setAttribute(Qt::WA_DeleteOnClose); d->show(); #endif } MoleculeDialog *Kalzium::slotMoleculeviewer() { #if defined(HAVE_OPENBABEL2) && defined(HAVE_EIGEN) && defined(HAVE_AVOGADRO) if (!QGLFormat::hasOpenGL()) { QMessageBox::critical(Q_NULLPTR, i18n("Kalzium Error"), i18n("This system does not support OpenGL.")); return nullptr; } MoleculeDialog * d = new MoleculeDialog(this); d->show(); return d; #if 0 KPluginLoader loader("libkalziumglpart"); KPluginFactory* factory = loader.factory(); if (factory) { KParts::ReadOnlyPart *part = 0; part = static_cast(factory->create(this, "KalziumGLPart")); part->widget()->show(); } #endif #endif return nullptr; } void Kalzium::slotTables() { if (!m_tablesDialog) { m_tablesDialog = new TablesDialog(this); } m_tablesDialog->show(); } void Kalzium::slotIsotopeTable() { if (!m_isotopeDialog) { m_isotopeDialog = new IsotopeTableDialog(this); } m_isotopeDialog->show(); } void Kalzium::slotPlotData() { if (!m_elementDataPlotter) { m_elementDataPlotter = new ElementDataViewer(this); } m_elementDataPlotter->show(); } void Kalzium::showCalculator() { if (!m_calculator) { m_calculator = new calculator(this); } m_calculator -> show(); } void Kalzium::slotSwitchtoTable(int index) { m_periodicTable->slotChangeTable(index); m_TableInfoWidget->setTableType(index); if (m_infoDialog) { m_infoDialog->setTableType(m_periodicTable->table()); } Prefs::setTable(index); Prefs::self()->save(); } void Kalzium::slotSwitchtoNumeration(int index) { emit numerationChanged(index); Prefs::setNumeration(index); Prefs::self()->save(); } void Kalzium::slotSwitchtoLookGradient(int which) { qDebug() << "slotSwitchtoLookGradient Kalzium"; KalziumElementProperty::instance()->setGradient(which); look_action_gradients->blockSignals(true); m_gradientWidget->gradient_combo->blockSignals(true); look_action_gradients->setCurrentItem(which); m_gradientWidget->gradient_combo->setCurrentIndex(which); look_action_gradients->blockSignals(false); m_gradientWidget->gradient_combo->blockSignals(false); m_gradientWidget->slotGradientChanged(); m_legendWidget->updateContent(); } void Kalzium::slotSwitchtoLookScheme(int which) { qDebug() << "slotSwitchtoLookScheme Kalzium"; KalziumElementProperty::instance()->setScheme(which); m_gradientWidget->scheme_combo->blockSignals(true); look_action_schemes->blockSignals(true); look_action_schemes->setCurrentItem(which); m_gradientWidget->scheme_combo->setCurrentIndex(which); look_action_schemes->blockSignals(false); m_gradientWidget->scheme_combo->blockSignals(false); m_legendWidget->updateContent(); } void Kalzium::showSettingsDialog() { if (KConfigDialog::showDialog("settings")) { return; } //KConfigDialog didn't find an instance of this dialog, so lets create it : KConfigDialog *dialog = new KConfigDialog(this,"settings", Prefs::self()); // colors page Ui_setupColors ui_colors; QWidget *w_colors = new QWidget(this); w_colors->setObjectName("colors_page"); ui_colors.setupUi(w_colors); dialog->addPage(w_colors, i18n("Schemes"), "preferences-desktop-color"); // gradients page Ui_setupGradients ui_gradients; QWidget *w_gradients = new QWidget(this); w_gradients->setObjectName("gradients_page"); ui_gradients.setupUi(w_gradients); dialog->addPage(w_gradients, i18n("Gradients"), "preferences-desktop-color"); // units page m_unitsDialog = new UnitSettingsDialog(this); m_unitsDialog->setObjectName("units_page"); dialog->addPage(m_unitsDialog, i18n("Units"), "system-run"); Ui_setupCalc ui_calc; QWidget *w_calc = new QWidget(this); ui_calc.setupUi(w_calc); dialog->addPage(w_calc, i18n("Calculator"), "accessories-calculator"); connect(dialog, SIGNAL(settingsChanged(QString)), this, SLOT(slotUpdateSettings())); connect(dialog, SIGNAL(settingsChanged(QString)), m_gradientWidget, SLOT(slotGradientChanged())); dialog->show(); } void Kalzium::slotUpdateSettings() { Prefs::setLengthUnit(m_unitsDialog->getLenghtUnitId()); Prefs::setEnergiesUnit(m_unitsDialog->getEnergyUnitId()); Prefs::setTemperatureUnit(m_unitsDialog->getTemperatureUnitId()); Prefs::self()->save(); /*This slot function calls change the color of pse elements immideately after prefs change*/ slotSwitchtoLookGradient(Prefs::colorgradientbox()); slotSwitchtoLookScheme(Prefs::colorschemebox()); } void Kalzium::slotShowExportDialog() { if (!m_exportDialog) { m_exportDialog = new ExportDialog(this); } m_exportDialog->show(); } void Kalzium::setupStatusBar() { QStatusBar *statusBar = new QStatusBar(this); setStatusBar(statusBar); m_elementInfo = new QLabel(""); m_elementInfo->setAlignment(Qt::AlignRight); statusBar->addWidget(m_elementInfo, 1); statusBar->show(); } void Kalzium::elementHover(int num) { // extractIconicInformationAboutElement(num); Element *e = KalziumDataObject::instance()->element(num); m_elementInfo->setText(i18nc("For example: \"Carbon (6), Mass: 12.0107 u\"", "%1 (%2), Mass: %3 u", e->dataAsString(ChemicalDataObject::name), e->dataAsString(ChemicalDataObject::atomicNumber), e->dataAsString(ChemicalDataObject::mass))); qDebug() << "change item in status bar"; m_detailWidget->setElement(num); } // FIXME What is that function for? Does not seem to do anything useful... yet? void Kalzium::extractIconicInformationAboutElement(int elementNumber) { QString setname = "school"; QString pathname = QStandardPaths::locate(QStandardPaths::DataLocation, "data/iconsets/", QStandardPaths::LocateDirectory); pathname = QFileInfo(pathname).absolutePath(); QString filename = pathname + setname + '/' + "iconinformation.txt"; QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } QString infoline; QTextStream in(&file); while (!in.atEnd()) { QString tmp = in.readLine(); if (tmp.startsWith(QString::number(elementNumber))) { infoline = tmp; } } QString realText = "Moin dies ist ein test!"; //X QString realText = infoline.remove(QRegExp("\\d+ ")); } void Kalzium::openInformationDialog(int number) { if (m_infoDialog) { m_infoDialog->setElement(number); } else { m_infoDialog = new DetailedInfoDlg(number, this); // Remove the selection when this dialog finishes or hides. connect(m_infoDialog, SIGNAL(elementChanged(int)), m_periodicTable, SLOT(slotSelectOneElement(int))); connect(m_infoDialog, SIGNAL(elementChanged(int)), this, SLOT(elementHover(int))); } m_infoDialog->setTableType(m_periodicTable->table()); m_infoDialog->show(); } Kalzium::~Kalzium() { delete m_periodicTable; delete m_infoDialog; delete m_TableInfoWidget; delete m_legendWidget; delete m_gradientWidget; delete m_dockWin; delete m_legendDock; delete m_tableDock; } void Kalzium::loadMolecule(const QString &moleculeFile) { #if defined(HAVE_OPENBABEL2) && defined(HAVE_EIGEN) && defined(HAVE_AVOGADRO) MoleculeDialog *d = slotMoleculeviewer(); if (d) { d->loadMolecule(moleculeFile); } #endif } QSize Kalzium::sizeHint() const { return QSize(700, 500); } diff --git a/src/kalziumelementproperty.cpp b/src/kalziumelementproperty.cpp index cceee383..ea163aa8 100644 --- a/src/kalziumelementproperty.cpp +++ b/src/kalziumelementproperty.cpp @@ -1,241 +1,241 @@ /*************************************************************************** * Copyright (C) 2010 by Etienne Rebetez etienne.rebetez@oberwallis.ch * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "kalziumelementproperty.h" #include "kalziumdataobject.h" #include "search.h" -#include "klocale.h" +#include #include KalziumElementProperty* KalziumElementProperty::instance() { static KalziumElementProperty elementProperty; return &elementProperty; } KalziumElementProperty::KalziumElementProperty() : m_mode(0) { m_currentScheme = Prefs::colorschemebox(); if (schemeList().count() <= m_currentScheme) m_currentScheme = 0; m_currentGradient = Prefs::colorgradientbox(); if (isGradient()) m_mode = GRADIENTVALUE; } KalziumElementProperty::~KalziumElementProperty() { } bool KalziumElementProperty::isGradient() { return m_currentGradient > 1; } void KalziumElementProperty::setScheme(int newScheme) { m_currentScheme = newScheme; Prefs::setColorschemebox(newScheme); Prefs::self()->save(); propertyChanged(); } void KalziumElementProperty::setGradient(int newGradient) { m_currentGradient = newGradient; Prefs::setColorgradientbox(newGradient); Prefs::self()->save(); if (isGradient()) { m_mode = GRADIENTVALUE; } else { m_mode = NORMAL; } propertyChanged(); } QStringList KalziumElementProperty::schemeList() const { return KalziumSchemeTypeFactory::instance()->schemes(); } QStringList KalziumElementProperty::gradientList() const { QStringList customList; customList << i18nc("No Gradient", "None"); customList << KalziumGradientTypeFactory::instance()->gradients(); return customList; } KalziumSchemeType* KalziumElementProperty::scheme() const { return KalziumSchemeTypeFactory::instance()->build(m_currentScheme); } KalziumGradientType* KalziumElementProperty::gradient() const { if (m_currentGradient == NOGRADIENT) { return KalziumGradientTypeFactory::instance()->build(NOGRADIENT); } return KalziumGradientTypeFactory::instance()->build(m_currentGradient - 1); } int KalziumElementProperty::gradientId() const { return m_currentGradient; } int KalziumElementProperty::schemeId() const { return m_currentScheme; } void KalziumElementProperty::setSliderValue(double slide) { m_slider = slide; propertyChanged(); } double KalziumElementProperty::getValue(int el) const { if (m_currentGradient != NOGRADIENT) return gradient()->value(el); return 0; } QColor KalziumElementProperty::getElementColor(int el) { if (m_currentGradient == NOGRADIENT) return scheme()->elementBrush(el).color(); return gradientBrushLogic(el); } QBrush KalziumElementProperty::getElementBrush(int el) { QBrush elementBrush; elementBrush.setStyle(Qt::SolidPattern); elementBrush.setColor(Qt::transparent); // Hide filtered elements from search if (!KalziumDataObject::instance()->search()->matches(el) && KalziumDataObject::instance()->search()->isActive()) { return QBrush(Qt::darkGray, Qt::Dense7Pattern); } //The iconic view is the 3rd view (0,1,2,...). Pixmaps don't make nice gradients. if (m_currentScheme == 2) { elementBrush = scheme()->elementBrush(el); } else { // add a nice gradient QColor color = getElementColor(el); QLinearGradient grad(QPointF(0, 0), QPointF(0, 40)); grad.setColorAt(0,color); qreal h, s, v, a; color.getHsvF(&h, &s, &v, &a); color.setHsvF(h, s, v*0.7, a); grad.setColorAt(1,color); elementBrush = QBrush(grad); } return elementBrush; } QColor KalziumElementProperty::getTextColor(int el) const { return scheme()->textColor(el); } QColor KalziumElementProperty::getBorderColor(int el) const { // Show scheme color as border when gradients are selected. if (m_currentGradient != NOGRADIENT) { return scheme()->elementBrush(el).color(); } // Transparent Borders don't make sens. if (getTextColor(el) == QColor(Qt::transparent)) { return QColor(Qt::black); } return getTextColor(el); } int KalziumElementProperty::getMode() const { return m_mode; } QColor KalziumElementProperty::gradientBrushLogic(int el) const { QColor gradientColor; bool isActiv = true; const double gradientValue = gradient()->value(el); const double melting = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::meltingpoint).toDouble(); const double boiling = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::boilingpoint).toDouble(); switch (m_currentGradient) { case SOMGradientType: if (m_slider < melting) { //the element is solid gradientColor = Prefs::color_solid(); } else if ((m_slider > melting) && (m_slider < boiling)) { //the element is liquid gradientColor = Prefs::color_liquid(); } else if ((m_slider >= boiling) && (boiling > 0.0)) { //the element is vaporous gradientColor = Prefs::color_vapor(); } else { gradientColor = Qt::lightGray; } return gradientColor; case DISCOVERYDATE: if (gradientValue > m_slider) { isActiv = false; } break; default: // All other gradients if (gradientValue < m_slider) { isActiv = false; } break; } if (!isActiv && gradientValue != -1) { //FIXME No magic number... Defined in KalziumGradientFactory gradientColor = Qt::transparent; } else { const double coeff = gradient()->elementCoeff(el); gradientColor = gradient()->calculateColor(coeff); } return gradientColor; } diff --git a/src/kalziumgradienttype.cpp b/src/kalziumgradienttype.cpp index ea0219ae..e30906de 100644 --- a/src/kalziumgradienttype.cpp +++ b/src/kalziumgradienttype.cpp @@ -1,712 +1,712 @@ /*************************************************************************** * Copyright (C) 2005, 2006 by Pino Toscano, toscano.pino@tiscali.it * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "kalziumgradienttype.h" #include "element.h" #include "prefs.h" #include "kalziumdataobject.h" #include #include #include -#include +#include #include KalziumGradientTypeFactory::KalziumGradientTypeFactory() { m_gradients << KalziumSOMGradientType::instance(); m_gradients << KalziumCovalentRadiusGradientType::instance(); m_gradients << KalziumVanDerWaalsRadiusGradientType::instance(); m_gradients << KalziumMassGradientType::instance(); m_gradients << KalziumBoilingPointGradientType::instance(); m_gradients << KalziumMeltingPointGradientType::instance(); m_gradients << KalziumElectronegativityGradientType::instance(); m_gradients << KalziumElectronaffinityGradientType::instance(); m_gradients << KalziumDiscoverydateGradientType::instance(); m_gradients << KalziumIonizationGradientType::instance(); } KalziumGradientTypeFactory* KalziumGradientTypeFactory::instance() { static KalziumGradientTypeFactory kttf; return &kttf; } KalziumGradientType* KalziumGradientTypeFactory::build(int id) const { if ((id < 0) || (id >= m_gradients.count())) return nullptr; return m_gradients.at(id); } KalziumGradientType* KalziumGradientTypeFactory::build(const QByteArray& id) const { for (int i = 0; i < m_gradients.count(); ++i) { if (m_gradients.at(i)->name() == id) { return m_gradients.at(i); } } return nullptr; } QStringList KalziumGradientTypeFactory::gradients() const { QStringList l; for (int i = 0; i < m_gradients.count(); ++i) { l << m_gradients.at(i)->description(); } return l; } KalziumGradientType::KalziumGradientType() { } KalziumGradientType::~KalziumGradientType() { } KalziumGradientType* KalziumGradientType::instance() { return nullptr; } double KalziumGradientType::elementCoeff(int el) const { double val = value(el); if (val == -1) { return val; } if (logarithmicGradient()) { double minVal = minValue(); double maxVal = maxValue(); // Fixing negative values for log calculation (no negative values allowed -> NaN) if (minVal < 0) { minVal = abs(minVal) + 1; // make sure it's bigger than 0 maxVal += minVal; val += minVal; minVal = 0.01; } double result = (log(val) - log(minVal)) / (log(maxVal) - log(minVal)); // now we perform a "gamma-correction" on the result. Indeed, logarithmic gradients // often have the problem that all high values have roughly the same color. Note that // as firstColor() is not necessarily black and secondColor() is not necessarily white, // this is not exactly a "gamma-correction" in the usual sense. const double gamma = 1.4; result = exp(gamma * log(result)); return result; } else { return (val - minValue()) / (maxValue() - minValue()); } } QColor KalziumGradientType::firstColor() const { return Prefs::minColor(); } QColor KalziumGradientType::secondColor() const { return Prefs::maxColor(); } QColor KalziumGradientType::notAvailableColor() const { return Qt::lightGray; } QColor KalziumGradientType::calculateColor(const double coeff) const { if ((coeff < 0.0) || (coeff > 1.0)) return notAvailableColor(); QColor color2 = secondColor(); QColor color1 = firstColor(); int red = static_cast((color2.red() - color1.red()) * coeff + color1.red()); int green = static_cast((color2.green() - color1.green()) * coeff + color1.green()); int blue = static_cast((color2.blue() - color1.blue()) * coeff + color1.blue()); return QColor(red, green, blue); } KalziumCovalentRadiusGradientType* KalziumCovalentRadiusGradientType::instance() { static KalziumCovalentRadiusGradientType kcrgt; return &kcrgt; } KalziumCovalentRadiusGradientType::KalziumCovalentRadiusGradientType() : KalziumGradientType() { } QByteArray KalziumCovalentRadiusGradientType::name() const { return "CovalentRadius"; } QString KalziumCovalentRadiusGradientType::description() const { return i18n("Covalent Radius"); } double KalziumCovalentRadiusGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el) ->dataAsVariant(ChemicalDataObject::radiusCovalent, Prefs::lengthUnit()); if (v.type() != QVariant::Double) return -1; return v.toDouble(); } QString KalziumCovalentRadiusGradientType::unit() const { return KalziumDataObject::instance()->unitAsString(Prefs::lengthUnit()); } int KalziumCovalentRadiusGradientType::decimals() const { return 2; } double KalziumCovalentRadiusGradientType::minValue() const { KUnitConversion::Value minValue(0.32, KUnitConversion::Angstrom); return minValue.convertTo(KUnitConversion::UnitId(Prefs::lengthUnit())).number(); } double KalziumCovalentRadiusGradientType::maxValue() const { KUnitConversion::Value minValue(2.25, KUnitConversion::Angstrom); return minValue.convertTo(KUnitConversion::UnitId(Prefs::lengthUnit())).number(); } bool KalziumCovalentRadiusGradientType::logarithmicGradient() const { return Prefs::logarithmicCovalentRadiusGradient(); } KalziumVanDerWaalsRadiusGradientType* KalziumVanDerWaalsRadiusGradientType::instance() { static KalziumVanDerWaalsRadiusGradientType kvdwrgt; return &kvdwrgt; } KalziumVanDerWaalsRadiusGradientType::KalziumVanDerWaalsRadiusGradientType() : KalziumGradientType() { } QByteArray KalziumVanDerWaalsRadiusGradientType::name() const { return "KalziumVanDerWaalsRadiusGradientType"; } QString KalziumVanDerWaalsRadiusGradientType::description() const { return i18n("van Der Waals"); } double KalziumVanDerWaalsRadiusGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el) ->dataAsVariant(ChemicalDataObject::radiusVDW, Prefs::lengthUnit()); if (v.type() != QVariant::Double) return -1; return v.toDouble(); } QString KalziumVanDerWaalsRadiusGradientType::unit() const { return KalziumDataObject::instance()->unitAsString(Prefs::lengthUnit()); } int KalziumVanDerWaalsRadiusGradientType::decimals() const { return 1; } double KalziumVanDerWaalsRadiusGradientType::minValue() const { KUnitConversion::Value minValue(1.2, KUnitConversion::Angstrom); return minValue.convertTo(KUnitConversion::UnitId(Prefs::lengthUnit())).number(); } double KalziumVanDerWaalsRadiusGradientType::maxValue() const { KUnitConversion::Value minValue(3.0, KUnitConversion::Angstrom); return minValue.convertTo(KUnitConversion::UnitId(Prefs::lengthUnit())).number(); } bool KalziumVanDerWaalsRadiusGradientType::logarithmicGradient() const { return Prefs::logarithmicVanDerWaalsRadiusGradient(); } KalziumMassGradientType* KalziumMassGradientType::instance() { static KalziumMassGradientType kargt; return &kargt; } KalziumMassGradientType::KalziumMassGradientType() : KalziumGradientType() { } QByteArray KalziumMassGradientType::name() const { return "AtomicMass"; } QString KalziumMassGradientType::description() const { return i18n("Atomic Mass"); } double KalziumMassGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::mass); if (v.type() != QVariant::Double) return -1; return v.toDouble(); } QString KalziumMassGradientType::unit() const { return i18n("u"); } int KalziumMassGradientType::decimals() const { return 5; } double KalziumMassGradientType::minValue() const { return 1.00794; } double KalziumMassGradientType::maxValue() const { return 294.0; } bool KalziumMassGradientType::logarithmicGradient() const { return Prefs::logarithmicMassGradient(); } KalziumBoilingPointGradientType* KalziumBoilingPointGradientType::instance() { static KalziumBoilingPointGradientType kbpgt; return &kbpgt; } KalziumBoilingPointGradientType::KalziumBoilingPointGradientType() : KalziumGradientType() { } QByteArray KalziumBoilingPointGradientType::name() const { return "BoilingPoint"; } QString KalziumBoilingPointGradientType::description() const { return i18n("Boiling Point"); } double KalziumBoilingPointGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::boilingpoint, Prefs::temperatureUnit()); if (v.type() != QVariant::Double) return -1; return v.toDouble(); } QString KalziumBoilingPointGradientType::unit() const { return KalziumDataObject::instance()->unitAsString(Prefs::temperatureUnit()); } int KalziumBoilingPointGradientType::decimals() const { return 3; } double KalziumBoilingPointGradientType::minValue() const { KUnitConversion::Value minValue(4.216, KUnitConversion::Kelvin); return minValue.convertTo(KUnitConversion::UnitId(Prefs::temperatureUnit())).number(); } double KalziumBoilingPointGradientType::maxValue() const { KUnitConversion::Value minValue(5870.0, KUnitConversion::Kelvin); return minValue.convertTo(KUnitConversion::UnitId(Prefs::temperatureUnit())).number(); } bool KalziumBoilingPointGradientType::logarithmicGradient() const { return Prefs::logarithmicBoilingPointGradient(); } KalziumMeltingPointGradientType* KalziumMeltingPointGradientType::instance() { static KalziumMeltingPointGradientType kmpgt; return &kmpgt; } KalziumMeltingPointGradientType::KalziumMeltingPointGradientType() : KalziumGradientType() { } QByteArray KalziumMeltingPointGradientType::name() const { return "MeltingPoint"; } QString KalziumMeltingPointGradientType::description() const { return i18n("Melting Point"); } double KalziumMeltingPointGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::meltingpoint, Prefs::temperatureUnit()); if (v.type() != QVariant::Double) return -1; return v.toDouble(); } QString KalziumMeltingPointGradientType::unit() const { return KalziumDataObject::instance()->unitAsString(Prefs::temperatureUnit()); } int KalziumMeltingPointGradientType::decimals() const { return 2; } double KalziumMeltingPointGradientType::minValue() const { KUnitConversion::Value minValue(0.94, KUnitConversion::Kelvin); return minValue.convertTo(KUnitConversion::UnitId(Prefs::temperatureUnit())).number(); } double KalziumMeltingPointGradientType::maxValue() const { KUnitConversion::Value minValue(3825.0, KUnitConversion::Kelvin); return minValue.convertTo(KUnitConversion::UnitId(Prefs::temperatureUnit())).number(); } bool KalziumMeltingPointGradientType::logarithmicGradient() const { return Prefs::logarithmicMeltingPointGradient(); } KalziumSOMGradientType* KalziumSOMGradientType::instance() { static KalziumSOMGradientType kargt; return &kargt; } KalziumSOMGradientType::KalziumSOMGradientType() : KalziumGradientType() { } QByteArray KalziumSOMGradientType::name() const { return "SOM"; } QString KalziumSOMGradientType::description() const { return i18n("State of matter"); } double KalziumSOMGradientType::value(int el) const { Q_UNUSED(el); return -1000; } QString KalziumSOMGradientType::unit() const { return KalziumDataObject::instance()->unitAsString(Prefs::temperatureUnit());; } int KalziumSOMGradientType::decimals() const { return 2; } double KalziumSOMGradientType::minValue() const { KUnitConversion::Value minValue(0.94, KUnitConversion::Kelvin); return minValue.convertTo(KUnitConversion::UnitId(Prefs::temperatureUnit())).number(); } double KalziumSOMGradientType::maxValue() const { KUnitConversion::Value minValue(5870.0, KUnitConversion::Kelvin); return minValue.convertTo(KUnitConversion::UnitId(Prefs::temperatureUnit())).number(); } bool KalziumSOMGradientType::logarithmicGradient() const { return true; // return Prefs::logarithmicSOMGradient(); } KalziumElectronegativityGradientType* KalziumElectronegativityGradientType::instance() { static KalziumElectronegativityGradientType kegt; return &kegt; } KalziumElectronegativityGradientType::KalziumElectronegativityGradientType() : KalziumGradientType() { } QByteArray KalziumElectronegativityGradientType::name() const { return "Electronegativity"; } QString KalziumElectronegativityGradientType::description() const { return i18n("Electronegativity (Pauling)"); } double KalziumElectronegativityGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::electronegativityPauling); if (v.type() != QVariant::Double) return -1; return v.toDouble(); } QString KalziumElectronegativityGradientType::unit() const { return QString(); } int KalziumElectronaffinityGradientType::decimals() const { return 2; } double KalziumElectronegativityGradientType::minValue() const { return 0.7; } double KalziumElectronegativityGradientType::maxValue() const { return 3.98; } bool KalziumElectronegativityGradientType::logarithmicGradient() const { return Prefs::logarithmicElectronegativityGradient(); } ///DISCOVERYDATE/// KalziumDiscoverydateGradientType* KalziumDiscoverydateGradientType::instance() { static KalziumDiscoverydateGradientType kegt; return &kegt; } KalziumDiscoverydateGradientType::KalziumDiscoverydateGradientType() : KalziumGradientType() { } QByteArray KalziumDiscoverydateGradientType::name() const { return "Discoverydate"; } QString KalziumDiscoverydateGradientType::description() const { return i18n("Discovery date"); } double KalziumDiscoverydateGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::date); if (v.value() == 0) return -1; return v.toDouble(); } QString KalziumDiscoverydateGradientType::unit() const { return QString(); } int KalziumDiscoverydateGradientType::decimals() const { return 0; } double KalziumDiscoverydateGradientType::minValue() const { return 1669.0; } double KalziumDiscoverydateGradientType::maxValue() const { return QDate::currentDate().year(); } bool KalziumDiscoverydateGradientType::logarithmicGradient() const { return Prefs::logarithmicDiscoverydateGradient(); } ///ELECTRONAFFINITY/// KalziumElectronaffinityGradientType* KalziumElectronaffinityGradientType::instance() { static KalziumElectronaffinityGradientType kegt; return &kegt; } KalziumElectronaffinityGradientType::KalziumElectronaffinityGradientType() : KalziumGradientType() { } QByteArray KalziumElectronaffinityGradientType::name() const { return "Electronaffinity"; } QString KalziumElectronaffinityGradientType::description() const { return i18n("Electronaffinity"); } double KalziumElectronaffinityGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::electronAffinity, Prefs::energiesUnit()); return v.toDouble(); } QString KalziumElectronaffinityGradientType::unit() const { return KalziumDataObject::instance()->unitAsString(Prefs::energiesUnit()); } int KalziumElectronegativityGradientType::decimals() const { return 2; } double KalziumElectronaffinityGradientType::minValue() const { KUnitConversion::Value minValue(-0.07, KUnitConversion::Electronvolt); return minValue.convertTo(KUnitConversion::UnitId(Prefs::energiesUnit())).number(); } double KalziumElectronaffinityGradientType::maxValue() const { KUnitConversion::Value minValue(3.7, KUnitConversion::Electronvolt); return minValue.convertTo(KUnitConversion::UnitId(Prefs::energiesUnit())).number(); } bool KalziumElectronaffinityGradientType::logarithmicGradient() const { return Prefs::logarithmicElectronaffinityGradient(); } ///FIRST IONIZATINO/// KalziumIonizationGradientType* KalziumIonizationGradientType::instance() { static KalziumIonizationGradientType kegt; return &kegt; } KalziumIonizationGradientType::KalziumIonizationGradientType() : KalziumGradientType() { } QByteArray KalziumIonizationGradientType::name() const { return "Ionization"; } QString KalziumIonizationGradientType::description() const { return i18n("First Ionization"); } double KalziumIonizationGradientType::value(int el) const { QVariant v = KalziumDataObject::instance()->element(el)->dataAsVariant(ChemicalDataObject::ionization, Prefs::energiesUnit()); return v.toDouble(); } QString KalziumIonizationGradientType::unit() const { return KalziumDataObject::instance()->unitAsString(Prefs::energiesUnit()); } int KalziumIonizationGradientType::decimals() const { return 2; } double KalziumIonizationGradientType::minValue() const { KUnitConversion::Value minValue(3.89, KUnitConversion::Electronvolt); return minValue.convertTo(KUnitConversion::UnitId(Prefs::energiesUnit())).number(); } double KalziumIonizationGradientType::maxValue() const { KUnitConversion::Value minValue(25.0, KUnitConversion::Electronvolt); return minValue.convertTo(KUnitConversion::UnitId(Prefs::energiesUnit())).number(); } bool KalziumIonizationGradientType::logarithmicGradient() const { return Prefs::logarithmicIonizationGradient(); } diff --git a/src/kalziumnumerationtype.cpp b/src/kalziumnumerationtype.cpp index 76388c47..a1e524c1 100644 --- a/src/kalziumnumerationtype.cpp +++ b/src/kalziumnumerationtype.cpp @@ -1,249 +1,249 @@ /*************************************************************************** * Copyright (C) 2005, 2006 by Pino Toscano, toscano.pino@tiscali.it * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "kalziumnumerationtype.h" #include "kalziumdataobject.h" -#include +#include KalziumNumerationTypeFactory::KalziumNumerationTypeFactory() { m_numerations << KalziumNoneNumerationType::instance(); m_numerations << KalziumIUPACNumerationType::instance(); m_numerations << KalziumCASNumerationType::instance(); m_numerations << KalziumOldIUPACNumerationType::instance(); } KalziumNumerationTypeFactory* KalziumNumerationTypeFactory::instance() { static KalziumNumerationTypeFactory kntf; return &kntf; } KalziumNumerationType* KalziumNumerationTypeFactory::build(int id) const { if ((id < 0) || (id >= m_numerations.count())) { return nullptr; } return m_numerations.at(id); } KalziumNumerationType* KalziumNumerationTypeFactory::build(const QByteArray& id) const { for (int i = 0; i < m_numerations.count(); ++i) { if (m_numerations.at(i)->name() == id) { return m_numerations.at(i); } } // not found return nullptr; } QStringList KalziumNumerationTypeFactory::numerations() const { QStringList l; for (int i = 0; i < m_numerations.count(); ++i) { l << m_numerations.at(i)->description(); } return l; } KalziumNumerationType* KalziumNumerationType::instance() { return nullptr; } KalziumNumerationType::KalziumNumerationType() { } KalziumNumerationType::~KalziumNumerationType() { } QString KalziumNumerationType::item(const int num) const { if ((num < 0) || (num >= m_items.count())) { return QString(); } return m_items.at(num); } QStringList KalziumNumerationType::items() const { return m_items; } KalziumNoneNumerationType* KalziumNoneNumerationType::instance() { static KalziumNoneNumerationType knnt; return &knnt; } KalziumNoneNumerationType::KalziumNoneNumerationType() : KalziumNumerationType() { } QByteArray KalziumNoneNumerationType::name() const { return "None"; } QString KalziumNoneNumerationType::description() const { return i18n("No Numeration"); } QString KalziumNoneNumerationType::item(const int num) const { Q_UNUSED(num); return QString(); } QStringList KalziumNoneNumerationType::items() const { return QStringList(); } KalziumIUPACNumerationType* KalziumIUPACNumerationType::instance() { static KalziumIUPACNumerationType kint; return &kint; } KalziumIUPACNumerationType::KalziumIUPACNumerationType() : KalziumNumerationType() { // cache them m_items << QString("1"); m_items << QString("2"); m_items << QString("3"); m_items << QString("4"); m_items << QString("5"); m_items << QString("6"); m_items << QString("7"); m_items << QString("8"); m_items << QString("9"); m_items << QString("10"); m_items << QString("11"); m_items << QString("12"); m_items << QString("13"); m_items << QString("14"); m_items << QString("15"); m_items << QString("16"); m_items << QString("17"); m_items << QString("18"); } QByteArray KalziumIUPACNumerationType::name() const { return "IUPAC"; } QString KalziumIUPACNumerationType::description() const { return i18n("IUPAC"); } KalziumCASNumerationType* KalziumCASNumerationType::instance() { static KalziumCASNumerationType kcnt; return &kcnt; } KalziumCASNumerationType::KalziumCASNumerationType() : KalziumNumerationType() { // cache them m_items << QString("IA"); m_items << QString("IIA"); m_items << QString("IIIB"); m_items << QString("IVB"); m_items << QString("VB"); m_items << QString("VIB"); m_items << QString("VIIB"); m_items << QString("VIII"); m_items << QString("VIII"); m_items << QString("VIII"); m_items << QString("IB"); m_items << QString("IIB"); m_items << QString("IIIA"); m_items << QString("IVA"); m_items << QString("VA"); m_items << QString("VIA"); m_items << QString("VIIA"); m_items << QString("VIIIA"); } QByteArray KalziumCASNumerationType::name() const { return "CAS"; } QString KalziumCASNumerationType::description() const { return i18n("CAS"); } KalziumOldIUPACNumerationType* KalziumOldIUPACNumerationType::instance() { static KalziumOldIUPACNumerationType koint; return &koint; } KalziumOldIUPACNumerationType::KalziumOldIUPACNumerationType() : KalziumNumerationType() { // cache them m_items << QString("1A"); m_items << QString("2A"); m_items << QString("3A"); m_items << QString("4A"); m_items << QString("5A"); m_items << QString("6A"); m_items << QString("7A"); m_items << QString("8"); m_items << QString("8"); m_items << QString("8"); m_items << QString("1B"); m_items << QString("2B"); m_items << QString("3B"); m_items << QString("4B"); m_items << QString("5B"); m_items << QString("6B"); m_items << QString("7B"); m_items << QString("0"); } QByteArray KalziumOldIUPACNumerationType::name() const { return "OldIUPAC"; } QString KalziumOldIUPACNumerationType::description() const { return i18n("Old IUPAC"); } diff --git a/src/kalziumschemetype.cpp b/src/kalziumschemetype.cpp index 1d962630..91a5cbf0 100644 --- a/src/kalziumschemetype.cpp +++ b/src/kalziumschemetype.cpp @@ -1,627 +1,625 @@ /*************************************************************************** * Copyright (C) 2005, 2006 by Pino Toscano, toscano.pino@tiscali.it * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "kalziumschemetype.h" #include "kalziumdataobject.h" #include "prefs.h" #ifdef HAVE_OPENBABEL2 #include #endif #include - -#include #include #include - +#include KalziumSchemeTypeFactory::KalziumSchemeTypeFactory() { m_schemes << KalziumMonoColorSchemeType::instance(); m_schemes << KalziumBlocksSchemeType::instance(); m_schemes << KalziumIconicSchemeType::instance(); m_schemes << KalziumFamilySchemeType::instance(); m_schemes << KalziumGroupsSchemeType::instance(); #ifdef HAVE_OPENBABEL2 m_schemes << KalziumColorSchemeType::instance(); #endif } KalziumSchemeTypeFactory* KalziumSchemeTypeFactory::instance() { static KalziumSchemeTypeFactory kstf; return &kstf; } KalziumSchemeType* KalziumSchemeTypeFactory::build(int id) const { if ((id < 0) || (id >= m_schemes.count())) { return nullptr; } return m_schemes.at(id); } KalziumSchemeType* KalziumSchemeTypeFactory::build(const QByteArray& id) const { for (int i = 0; i < m_schemes.count(); ++i) { if (m_schemes.at(i)->name() == id) { return m_schemes.at(i); } } return nullptr; } QStringList KalziumSchemeTypeFactory::schemes() const { QStringList l; for (int i = 0; i < m_schemes.count(); ++i) { l << m_schemes.at(i)->description(); } return l; } KalziumSchemeType* KalziumSchemeType::instance() { return nullptr; } KalziumSchemeType::KalziumSchemeType() { } KalziumSchemeType::~KalziumSchemeType() { } KalziumMonoColorSchemeType::KalziumMonoColorSchemeType() : KalziumSchemeType() { } KalziumMonoColorSchemeType* KalziumMonoColorSchemeType::instance() { static KalziumMonoColorSchemeType kmcst; return &kmcst; } QByteArray KalziumMonoColorSchemeType::name() const { return "MonoColor"; } QString KalziumMonoColorSchemeType::description() const { return i18n("Monochrome"); } QBrush KalziumMonoColorSchemeType::elementBrush(int el) const { Q_UNUSED(el); return QBrush(Prefs::noscheme()); } QColor KalziumMonoColorSchemeType::textColor(int el) const { Q_UNUSED(el); return Qt::black; } QList KalziumMonoColorSchemeType::legendItems() const { QList ll; ll << qMakePair(i18n("All the Elements"), QColor(Prefs::noscheme())); return ll; } KalziumBlocksSchemeType::KalziumBlocksSchemeType() : KalziumSchemeType() { } KalziumBlocksSchemeType* KalziumBlocksSchemeType::instance() { static KalziumBlocksSchemeType kbst; return &kbst; } QByteArray KalziumBlocksSchemeType::name() const { return "Blocks"; } QString KalziumBlocksSchemeType::description() const { return i18n("Blocks"); } QBrush KalziumBlocksSchemeType::elementBrush(int el) const { QString block = KalziumDataObject::instance()->element(el)->dataAsString(ChemicalDataObject::periodTableBlock); QColor c; if (block == QLatin1String("s")) { c = Prefs::block_s(); } else if (block == QLatin1String("p")) { c = Prefs::block_p(); } else if (block == QLatin1String("d")) { c = Prefs::block_d(); } else if (block == QLatin1String("f")) { c = Prefs::block_f(); } else { c = Qt::lightGray; } return QBrush(c); } QColor KalziumBlocksSchemeType::textColor(int el) const { Q_UNUSED(el); return Qt::black; } QList KalziumBlocksSchemeType::legendItems() const { QList ll; ll << qMakePair(i18n("s-Block"), QColor(Prefs::block_s())); ll << qMakePair(i18n("p-Block"), QColor(Prefs::block_p())); ll << qMakePair(i18n("d-Block"), QColor(Prefs::block_d())); ll << qMakePair(i18n("f-Block"), QColor(Prefs::block_f())); return ll; } ///ICONIC SCHEME/// KalziumIconicSchemeType::KalziumIconicSchemeType() : KalziumSchemeType() { } KalziumIconicSchemeType* KalziumIconicSchemeType::instance() { static KalziumIconicSchemeType kist; return &kist; } QByteArray KalziumIconicSchemeType::name() const { return "Iconic"; } QString KalziumIconicSchemeType::description() const { return i18n("Iconic"); } QBrush KalziumIconicSchemeType::elementBrush(int el) const { QPixmap pixmap = KalziumDataObject::instance()->pixmap(el); return QBrush(pixmap); } QColor KalziumIconicSchemeType::textColor(int) const { return Qt::transparent; } QList KalziumIconicSchemeType::legendItems() const { QList ll; ll << qMakePair(i18n("Each element is represented by an icon which represents its use."), QColor()); return ll; } ///Family/// KalziumFamilySchemeType::KalziumFamilySchemeType() : KalziumSchemeType() { } KalziumFamilySchemeType* KalziumFamilySchemeType::instance() { static KalziumFamilySchemeType kbst; return &kbst; } QByteArray KalziumFamilySchemeType::name() const { return "Family"; } QString KalziumFamilySchemeType::description() const { return i18n("Family"); } QBrush KalziumFamilySchemeType::elementBrush(int el) const { QString family = KalziumDataObject::instance()->element(el)->dataAsString(ChemicalDataObject::family); QColor c; if (family == QLatin1String("Noblegas")) { c = Prefs::noble_gas(); } else if (family == QLatin1String("Non-Metal")) { c = Prefs::nonmetal(); } else if (family == QLatin1String("Rare_Earth")) { c = Prefs::rare(); } else if (family == QLatin1String("Alkaline_Earth")) { c = Prefs::alkaline(); } else if (family == QLatin1String("Alkali_Earth")) { c = Prefs::alkalie(); } else if (family == QLatin1String("Transition")) { c = Prefs::transition(); } else if (family == QLatin1String("Other_Metal")) { c = Prefs::other_metal(); } else if (family == QLatin1String("Metalloids")) { c = Prefs::metalloid(); } else if (family == QLatin1String("Halogen")) { c = Prefs::halogene(); } else { c = Qt::lightGray; } return QBrush(c); } QColor KalziumFamilySchemeType::textColor(int) const { return Qt::black; } QList KalziumFamilySchemeType::legendItems() const { QList ll; ll << qMakePair(i18n("Alkaline"),QColor(Prefs::alkalie())); ll << qMakePair(i18n("Rare Earth"),QColor(Prefs::rare())); ll << qMakePair(i18n("Non-Metals"),QColor(Prefs::nonmetal())); ll << qMakePair(i18n("Alkalie Metal"),QColor(Prefs::alkaline())); ll << qMakePair(i18n("Other Metal"),QColor(Prefs::other_metal())); ll << qMakePair(i18n("Halogen"),QColor(Prefs::halogene())); ll << qMakePair(i18n("Transition Metal"),QColor(Prefs::transition())); ll << qMakePair(i18n("Noble Gas"),QColor(Prefs::noble_gas())); ll << qMakePair(i18n("Metalloid"),QColor(Prefs::metalloid())); return ll; } ///GROUPS/// KalziumGroupsSchemeType::KalziumGroupsSchemeType() : KalziumSchemeType() { } KalziumGroupsSchemeType* KalziumGroupsSchemeType::instance() { static KalziumGroupsSchemeType kbst; return &kbst; } QByteArray KalziumGroupsSchemeType::name() const { return "Groups"; } QString KalziumGroupsSchemeType::description() const { return i18n("Groups"); } QBrush KalziumGroupsSchemeType::elementBrush(int el) const { QString group = KalziumDataObject::instance()->element(el)->dataAsString(ChemicalDataObject::group); QColor c; if (group == QLatin1String("1")) { c = Prefs::group_1(); } else if (group == QLatin1String("2")) { c = Prefs::group_2(); } else if (group == QLatin1String("3")) { c = Prefs::group_3(); } else if (group == QLatin1String("4")) { c = Prefs::group_4(); } else if (group == QLatin1String("5")) { c = Prefs::group_5(); } else if (group == QLatin1String("6")) { c = Prefs::group_6(); } else if (group == QLatin1String("7")) { c = Prefs::group_7(); } else if (group == QLatin1String("8")) { c = Prefs::group_8(); } else { c = Qt::lightGray; } return QBrush(c); } QColor KalziumGroupsSchemeType::textColor(int) const { return Qt::black; } QList KalziumGroupsSchemeType::legendItems() const { QList ll; ll << qMakePair(i18n("Group 1"), QColor(Prefs::group_1())); ll << qMakePair(i18n("Group 2"), QColor(Prefs::group_2())); ll << qMakePair(i18n("Group 3"), QColor(Prefs::group_3())); ll << qMakePair(i18n("Group 4"), QColor(Prefs::group_4())); ll << qMakePair(i18n("Group 5"), QColor(Prefs::group_5())); ll << qMakePair(i18n("Group 6"), QColor(Prefs::group_6())); ll << qMakePair(i18n("Group 7"), QColor(Prefs::group_7())); ll << qMakePair(i18n("Group 8"), QColor(Prefs::group_8())); return ll; } #ifdef HAVE_OPENBABEL2 ///OpenBabel Color/// KalziumColorSchemeType::KalziumColorSchemeType() : KalziumSchemeType() { } KalziumColorSchemeType* KalziumColorSchemeType::instance() { static KalziumColorSchemeType kbst; return &kbst; } QByteArray KalziumColorSchemeType::name() const { return "Color"; } QString KalziumColorSchemeType::description() const { return i18n("Colors"); } QBrush KalziumColorSchemeType::elementBrush(int el) const { QColor c; std::vector color = OpenBabel::etab.GetRGB(el); c.setRgbF(color[0], color[1], color[2]); return QBrush(c); } QColor KalziumColorSchemeType::textColor(int) const { return Qt::black; } QList KalziumColorSchemeType::legendItems() const { QList ll; ll << qMakePair(i18n("Nice colors without meaning. (From the Openbabel project)"), QColor()); return ll; } #endif ///CRYSTAL/// //X KalziumCrystalSchemeType::KalziumCrystalSchemeType() //X : KalziumSchemeType() //X { //X } //X //X KalziumCrystalSchemeType* KalziumCrystalSchemeType::instance() //X { //X static KalziumCrystalSchemeType kbst; //X return &kbst; //X } //X //X QByteArray KalziumCrystalSchemeType::name() const //X { //X return "Crystal"; //X } //X //X QString KalziumCrystalSchemeType::description() const //X { //X return i18n("Crystal Structures"); //X } //X //X QBrush KalziumCrystalSchemeType::elementBrush(int el, const QRect& elrect) const //X { //X QString crystal = KalziumDataObject::instance()->element(el)->dataAsString(ChemicalDataObject::crystalstructure); //X //X qDebug() << "crystal is " << crystal; //X //X static QString resourcepath; //X if (resourcepath.isEmpty()) { //X resourcepath = QStandardPaths::locate(QStandardPaths::DataLocation, "data/latticeicons/"); //X } //X //X QString filename; //X if (crystal == "bcc") { //X filename = "ci.png"; //X } else if (crystal == "ccp") { //X filename = "cp.png"; //X } else if (crystal == "fcc") { //X filename = "cf.png"; //X } else if (crystal == "hcp") { //X filename = "hp.png"; //X } else if (crystal == "rh") { //X filename = "hr.png";//Rhombohedral primitive //X } else if (crystal == "or") { //X filename = "op.png";//Orthorhombic primitive //X } else if (crystal == "mono") { //X filename = "ms.png";//Monoclinic primitive //X } else if (crystal == "tri") { //X filename = "ap.png";//Triclinic //X } else if (crystal == "tp") { //X filename = "tp.png";//Tetragonal primitive //X } //X //X filename.prepend(resourcepath); //X //X QBrush ret; //X if (!filename.isEmpty()) { //X qDebug() << el << ": FILENAME is not EMPTY... " << filename; //X QPixmap pixmap(resourcepath + filename); //X ret = QBrush(pixmap.scaled(elrect.size(), Qt::KeepAspectRatio)); //X } else { //X qDebug() << el << ": FILENAME EMPTY... " << filename; //X ret.setColor(Qt::gray); //X } //X //X return ret; //X } //X //X QColor KalziumCrystalSchemeType::textColor(int) const //X { //X return Qt::black; //X } //X //X QList KalziumCrystalSchemeType::legendItems() const //X { //X static QString resourcepath; //X if (resourcepath.isEmpty()) //X { //X resourcepath = QStandardPaths::locate(QStandardPaths::DataLocation, "data/latticeicons/"); //X } //X //X QList ll; //X ll << qMakePair(i18n("bcc, body centered cubic"), QColor(QPixmap(resourcepath + "ci.png"))); //X ll << qMakePair(i18n("ccp, cubic close packed"), QColor(QPixmap(resourcepath + "cp.png"))); //X ll << qMakePair(i18n("fcc, face centered cubic"), QColor(QPixmap(resourcepath + "cf.png"))); //X ll << qMakePair(i18n("hcp, hexagonal close packed"), QColor(QPixmap(resourcepath + "hp.png"))); //X ll << qMakePair(i18n("rh, rhombohedral"), QColor(QPixmap(resourcepath + "hr.png"))); //X ll << qMakePair(i18n("or, orthorhombic primitive"), QColor(QPixmap(resourcepath + "op.png"))); //X ll << qMakePair(i18n("ms, monoclinic"), QColor(QPixmap(resourcepath + "ms.png"))); //X ll << qMakePair(i18n("ap, triclinic"), QColor(QPixmap(resourcepath + "ap.png"))); //X ll << qMakePair(i18n("tp, tetragonal primitive"), QColor(QPixmap(resourcepath + "tp.png"))); //X //X return ll; //X } //// //X KalziumDiscoverymapSchemeType::KalziumDiscoverymapSchemeType() //X : KalziumSchemeType() //X { //X } //X //X KalziumDiscoverymapSchemeType* KalziumDiscoverymapSchemeType::instance() //X { //X static KalziumDiscoverymapSchemeType kbst; //X return &kbst; //X } //X //X QByteArray KalziumDiscoverymapSchemeType::name() const //X { //X return "Crystal"; //X } //X //X QString KalziumDiscoverymapSchemeType::description() const //X { //X return i18n("Discovery Country"); //X } //X //X QBrush KalziumDiscoverymapSchemeType::elementBrush(int el, const QRect& elrect) const //X { //X QString map = KalziumDataObject::instance()->element(el)->dataAsString(ChemicalDataObject::discoveryCountry); //X //X static QString resourcepath; //X if (resourcepath.isEmpty()) { //X resourcepath = QStandardPaths::locate(QStandardPaths::DataLocation, "data/maps/"); //X } //X //X QString filename; //X if (map == "se") { //X filename = "se.png"; //X } else if (map == "uk") { //X filename = "uk.png"; //X } else if (map == "us") { //X filename = "us.png"; //X } else if (map == "ru") { //X filename = "ru.png"; //X } else if (map == "it") { //X filename = "it.png"; //X } else if (map == "de") { //X filename = "de.png"; //X } else if (map == "dk") { //X filename = "dk.png"; //X } else if (map == "fr") { //X filename = "fr.png"; //X } else if (map == "fi") { //X filename = "fi.png"; //X } else if (map == "es") { //X filename = "es.png"; //X } else if (map == "ancient") { //X return QBrush(Qt::lightGray); //X } else if (map == "uk,fr") { //X filename = "ukfr.png"; //X } else if (map == "se,uk") { //X filename = "ukse.png"; //X } else if (map == "ru,us") { //X filename = "ruus.png"; //X } else { //X return QBrush(Qt::blue); //X } //X //X QBrush ret; //X if (!filename.isEmpty()) { //X QPixmap pixmap(resourcepath + filename); //X ret = QBrush(pixmap.scaled(elrect.size(), Qt::KeepAspectRatio)); //X } else { //X ret.setColor(Qt::gray); //X } //X //X return ret; //X } //X //X QColor KalziumDiscoverymapSchemeType::textColor(int) const //X { //X return Qt::black; //X } //X //X QList KalziumDiscoverymapSchemeType::legendItems() const //X { //X static QString resourcepath; //X if (resourcepath.isEmpty()) { //X resourcepath = QStandardPaths::locate(QStandardPaths::DataLocation, "data/maps/"); //X } //X //X QList ll; //X ll << qMakePair(i18n("Germany"), QColor(QPixmap(resourcepath + "de.png"))); //X ll << qMakePair(i18n("United Kindom"), QColor(QPixmap(resourcepath + "uk.png"))); //X ll << qMakePair(i18n("Sweden"), QColor(QPixmap(resourcepath + "se.png"))); //X ll << qMakePair(i18n("USA"), QColor(QPixmap(resourcepath + "us.png"))); //X ll << qMakePair(i18n("Russia"), QColor(QPixmap(resourcepath + "ru.png"))); //X ll << qMakePair(i18n("Italy"), QColor(QPixmap(resourcepath + "it.png"))); //X ll << qMakePair(i18n("Denmark"), QColor(QPixmap(resourcepath + "dk.png"))); //X ll << qMakePair(i18n("France"), QColor(QPixmap(resourcepath + "fr.png"))); //X ll << qMakePair(i18n("Finland"), QColor(QPixmap(resourcepath + "fi.png"))); //X ll << qMakePair(i18n("Spain"), QColor(QPixmap(resourcepath + "es.png"))); //X //X return ll; //X } diff --git a/src/kalziumutils.cpp b/src/kalziumutils.cpp index 69755af4..b8ed4c92 100644 --- a/src/kalziumutils.cpp +++ b/src/kalziumutils.cpp @@ -1,189 +1,189 @@ /*************************************************************************** copyright : (C) 2005, 2006, 2007 by Carsten Niehaus email : cniehaus@kde.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "kalziumutils.h" #include #include #include #include #include -#include +#include #include #include #include "prefs.h" #include #if defined(HAVE_IEEEFP_H) #include #endif int KalziumUtils::maxSize(const QString& string, const QRect& rect, QFont font, QPainter* p, int minFontSize, int maxFontSize) { bool goodSizeFound = false; int size = maxFontSize; QRect r; do { font.setPointSize(size); p->setFont(font); r = p->boundingRect(QRect(), Qt::AlignTop | Qt::AlignLeft, string); r.translate(rect.left(), rect.top()); if (rect.contains(r)) { goodSizeFound = true; } else { --size; } } while (!goodSizeFound && (size > minFontSize)); return size; } int KalziumUtils::StringHeight(const QString& string, const QFont& font, QPainter* p) { Q_UNUSED(font); return p->boundingRect(QRect(), Qt::AlignTop | Qt::AlignLeft, string).height(); } int KalziumUtils::StringWidth(const QString& string, const QFont& font, QPainter* p) { Q_UNUSED(font); return p->boundingRect(QRect(), Qt::AlignTop | Qt::AlignLeft, string).width(); } double KalziumUtils::strippedValue(double num) { if (!finite(num)) { return num; } double power; power = 1e-6; while (power < num) { power *= 10; } num = num / power * 10000; num = qRound(num); return num * power / 10000; } QString KalziumUtils::prettyUnit(const Element* el, ChemicalDataObject::BlueObelisk kind) { if (!el) { return i18n("Error"); } QString result; double val = 0.0; //the value to convert switch (kind) { case ChemicalDataObject::meltingpoint: // a temperature case ChemicalDataObject::boilingpoint: result = el->dataAsStringWithUnit(kind, Prefs::temperatureUnit()); break; case ChemicalDataObject::electronegativityPauling: // electronegativity { val = el->dataAsVariant(kind).toDouble(); if (val <= 0.0) { result = i18n("Value not defined"); } else { result = i18nc("Just a number", "%1", val); } break; } case ChemicalDataObject::electronAffinity: // an energy case ChemicalDataObject::ionization: result = el->dataAsStringWithUnit(kind, Prefs::energiesUnit()); break; case ChemicalDataObject::mass: // a mass { val = el->dataAsVariant(kind).toDouble(); if (val <= 0.0) { result = i18n("Unknown Value"); } else { result = i18nc("x u (units). The atomic mass.", "%1 u", val); } break; } case ChemicalDataObject::date: // a date { //val = el->dataAsVariant(kind).toInt(); int v_int = el->dataAsVariant(kind).toInt(); if (val > 1600) { result = i18n("This element was discovered in the year %1.", val); } else if (v_int == -1) { result = i18n("The element has not yet been officially recognized by the IUPAC."); } else { // this should now really be 0. If not there is a bug in the database result = i18n("This element was known to ancient cultures."); } break; } case ChemicalDataObject::radiusCovalent: case ChemicalDataObject::radiusVDW: { result = el->dataAsStringWithUnit(kind, Prefs::lengthUnit()); break; } case ChemicalDataObject::electronicConfiguration: { QString newOrbit = el->dataAsString(kind); QRegExp reg("(.*)([spdf])(\\d+)(.*)"); while (newOrbit.contains(reg)) { newOrbit = newOrbit.replace(reg, "\\1\\2\\3\\4"); } result = newOrbit; break; } case ChemicalDataObject::oxidation: { QStringList oxidationList = el->dataAsString(kind).split(','); result = oxidationList.join(", "); break; } default: result = el->dataAsVariant(kind).toString(); } if (result.isEmpty()) { result = i18n("No Data"); } return result; } void KalziumUtils::populateUnitCombobox(QComboBox *comboBox, const QList &unitList) { comboBox->clear(); QString unitString; foreach (int unit, unitList) { unitString = KUnitConversion::Converter().unit(KUnitConversion::UnitId(unit)).description(); unitString.append(" ("); unitString.append(KUnitConversion::Converter().unit(KUnitConversion::UnitId(unit)).symbol()); unitString.append(")"); comboBox->addItem(unitString, unit); } } diff --git a/src/kdeeduglossary.cpp b/src/kdeeduglossary.cpp index 048d5bc3..fe2bd478 100644 --- a/src/kdeeduglossary.cpp +++ b/src/kdeeduglossary.cpp @@ -1,548 +1,555 @@ /*************************************************************************** * Copyright (C) 2005, 2006 by Carsten Niehaus * * Copyright (C) 2005 - 2007 by Pino Toscano * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "kdeeduglossary.h" -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include + #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include static const int FirstLetterRole = 0x00b00a00; static const int GlossaryTreeItemType = QTreeWidgetItem::UserType + 1; class GlossaryTreeItem : public QTreeWidgetItem { public: GlossaryTreeItem(Glossary * g, GlossaryItem * gi) : QTreeWidgetItem(GlossaryTreeItemType), m_g(g), m_gi(gi) { setText(0, m_gi->name()); } Glossary *glossary() const { return m_g; } GlossaryItem *glossaryItem() const { return m_gi; } private: Glossary *m_g; GlossaryItem *m_gi; }; struct GlossaryInfo { GlossaryInfo(Glossary* g) : glossary(g), folded(true) { } Glossary *glossary; bool folded; }; class GlossaryDialog::Private { public: Private(GlossaryDialog *qq) : q(qq) { } ~Private() { QList::ConstIterator it = m_glossaries.constBegin(); QList::ConstIterator itEnd = m_glossaries.constEnd(); for (; it != itEnd; ++it) { delete (*it).glossary; } delete m_htmlpart; } void rebuildTree(); QTreeWidgetItem* createItem(const GlossaryInfo& gi) const; QTreeWidgetItem* findTreeWithLetter(const QChar& l, QTreeWidgetItem* item) const; // slots void itemActivated(QTreeWidgetItem * item, int column); // The user clicked on a href. Find and display the right item void displayItem(const QUrl &url, const KParts::OpenUrlArguments& arguments, const KParts::BrowserArguments &browserArguments); GlossaryDialog *q; QList< GlossaryInfo > m_glossaries; KHTMLPart *m_htmlpart; QTreeWidget *m_glosstree; KTreeWidgetSearchLine *m_search; QString m_htmlbasestring; KActionCollection* m_actionCollection; }; Glossary::Glossary(const QUrl &url, const QString& path) { init(url, path); } Glossary::Glossary() { init(QUrl(), QString()); } Glossary::~Glossary() { qDeleteAll(m_itemlist); } void Glossary::init(const QUrl &url, const QString& path) { // setting a generic name for a new glossary m_name = i18n("Glossary"); setPicturePath(path); if (!url.isEmpty()) { QDomDocument doc("document"); if (loadLayout(doc, url)) { setItemlist(readItems(doc)); if (!m_picturepath.isEmpty()) { fixImagePath(); } } } } bool Glossary::loadLayout(QDomDocument &Document, const QUrl &url) { QFile layoutFile(url.path()); if (!layoutFile.exists()) { qDebug() << "no such file: " << layoutFile.fileName(); return false; } if (!layoutFile.open(QIODevice::ReadOnly)) { return false; } // check if document is well-formed if (!Document.setContent(&layoutFile)) { qDebug() << "wrong xml of " << layoutFile.fileName(); layoutFile.close(); return false; } layoutFile.close(); return true; } bool Glossary::isEmpty() const { return m_itemlist.count() == 0; } void Glossary::setName(const QString& name) { if (name.isEmpty()) { return; } m_name = name; } void Glossary::setPicturePath(const QString& path) { if (path.isEmpty()) { return; } m_picturepath = path; } void Glossary::setBackgroundPicture(const QString& filename) { if (filename.isEmpty()) { return; } m_backgroundpicture = filename; } void Glossary::fixImagePath() { QString imgtag = ""; QRegExp exp("\\[img\\]([^[]+)\\[/img\\]"); foreach (GlossaryItem * item, m_itemlist) { QString tmp = item->desc(); while (exp.indexIn(tmp) > -1) { tmp = tmp.replace(exp, imgtag); } item->setDesc(tmp); } } QList Glossary::readItems(QDomDocument &itemDocument) { QList list; QDomNodeList itemList; QDomNodeList refNodeList; QDomElement itemElement; QStringList reflist; itemList = itemDocument.elementsByTagName("item"); const uint num = itemList.count(); for (uint i = 0; i < num; ++i) { reflist.clear(); GlossaryItem *item = new GlossaryItem(); itemElement = (const QDomElement&) itemList.item(i).toElement(); QDomNode nameNode = itemElement.namedItem("name"); QDomNode descNode = itemElement.namedItem("desc"); QString picName = itemElement.namedItem("picture").toElement().text(); QDomElement refNode = (const QDomElement&) itemElement.namedItem("references").toElement(); QString desc = i18n(descNode.toElement().text().toUtf8().constData()); if (!picName.isEmpty()) { desc.prepend("[img]" + picName + "[/img][brclear][br]"); } item->setName(i18n(nameNode.toElement().text().toUtf8().constData())); desc = desc.replace("[b]", ""); desc = desc.replace("[/b]", ""); desc = desc.replace("[i]", ""); desc = desc.replace("[/i]", ""); desc = desc.replace("[sub]", ""); desc = desc.replace("[/sub]", ""); desc = desc.replace("[sup]", ""); desc = desc.replace("[/sup]", ""); desc = desc.replace("[br]", "
"); desc = desc.replace("[brclear]", "
"); item->setDesc(desc); refNodeList = refNode.elementsByTagName("refitem"); for (int it = 0; it < refNodeList.count(); ++it) { reflist << i18n(refNodeList.item(it).toElement().text().toUtf8().constData()); } item->setRef(reflist); list.append(item); } return list; } void Glossary::addItem(GlossaryItem* item) { m_itemlist.append(item); } QList Glossary::itemlist()const { return m_itemlist; } void Glossary::clear() { m_itemlist.clear(); } QString Glossary::name()const { return m_name; } void Glossary::setItemlist(QList list) { m_itemlist = list; } QString Glossary::picturePath()const { return m_picturepath; } QString Glossary::backgroundPicture()const { return m_backgroundpicture; } -GlossaryDialog::GlossaryDialog(QWidget *parent) : KDialog(parent), d(new Private(this)) +GlossaryDialog::GlossaryDialog(QWidget *parent) : QDialog(parent), d(new Private(this)) { - setCaption(i18n("Glossary")); - setButtons(Close); - setDefaultButton(Close); + setWindowTitle(i18n("Glossary")); //this string will be used for all items. If a backgroundpicture should //be used call Glossary::setBackgroundPicture(). d->m_htmlbasestring = ""; QWidget *main = new QWidget(this); - setMainWidget(main); QVBoxLayout *vbox = new QVBoxLayout(main); + setLayout(vbox); vbox->setMargin(0); QHBoxLayout *hbox = new QHBoxLayout(); QLabel *lbl = new QLabel(main); lbl->setText(i18n("&Search:")); hbox->addWidget(lbl); d->m_search = new KTreeWidgetSearchLine(main); d->m_search->setObjectName("search-line"); lbl->setBuddy(lbl); hbox->addWidget(d->m_search); vbox->addLayout(hbox); setFocusProxy(d->m_search); QSplitter *vs = new QSplitter(main); vbox->addWidget(vs); d->m_glosstree = new QTreeWidget(vs); d->m_glosstree->setObjectName("treeview"); d->m_glosstree->setHeaderLabel("entries"); d->m_glosstree->header()->hide(); d->m_glosstree->setRootIsDecorated(true); d->m_search->addTreeWidget(d->m_glosstree); d->m_htmlpart = new KHTMLPart(vs); connect(d->m_htmlpart->browserExtension(), SIGNAL(openUrlRequestDelayed(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)), this, SLOT(displayItem(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments))); connect(d->m_glosstree, SIGNAL(itemActivated(QTreeWidgetItem*,int)), this, SLOT(itemActivated(QTreeWidgetItem*,int))); - resize(600, 400); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); + connect(buttonBox, &QDialogButtonBox::rejected, this, &GlossaryDialog::reject); + buttonBox->button(QDialogButtonBox::Close)->setDefault(true); + vbox->addWidget(buttonBox); + + resize(800, 400); } GlossaryDialog::~GlossaryDialog() { delete d; } void GlossaryDialog::keyPressEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Return) { e->ignore(); } - KDialog::keyPressEvent(e); + QDialog::keyPressEvent(e); } void GlossaryDialog::Private::displayItem(const QUrl &url, const KParts::OpenUrlArguments &, const KParts::BrowserArguments &) { // using the "path" part of a qurl as reference QString myurl = url.path().toLower(); QTreeWidgetItemIterator it(m_glosstree); while (*it) { if ((*it)->type() == GlossaryTreeItemType && (*it)->text(0).toLower() == myurl) { // force the item to be selected m_glosstree->setCurrentItem(*it); // display its content itemActivated((*it), 0); break; } else { ++it; } } } void GlossaryDialog::Private::rebuildTree() { m_glosstree->clear(); QList< GlossaryInfo >::ConstIterator it = m_glossaries.constBegin(); QList< GlossaryInfo >::ConstIterator itEnd = m_glossaries.constEnd(); for (; it != itEnd; ++it) { m_glosstree->addTopLevelItem(createItem(*it)); } } QTreeWidgetItem* GlossaryDialog::Private::createItem(const GlossaryInfo& gi) const { Glossary *glossary = gi.glossary; bool folded = gi.folded; QTreeWidgetItem *main = new QTreeWidgetItem(); main->setText(0, glossary->name()); main->setFlags(Qt::ItemIsEnabled); foreach (GlossaryItem *item, glossary->itemlist()) { if (folded) { QChar thisletter = item->name().toUpper().at(0); QTreeWidgetItem *thisletteritem = findTreeWithLetter(thisletter, main); if (!thisletteritem) { thisletteritem = new QTreeWidgetItem(main); thisletteritem->setText(0, QString(thisletter)); thisletteritem->setFlags(Qt::ItemIsEnabled); thisletteritem->setData(0, FirstLetterRole, thisletter); } thisletteritem->addChild(new GlossaryTreeItem(glossary, item)); } else { main->addChild(new GlossaryTreeItem(glossary, item)); } } return main; } void GlossaryDialog::addGlossary(Glossary* newgloss, bool folded) { if (!newgloss || newgloss->isEmpty()) { return; } GlossaryInfo gi(newgloss); gi.folded = folded; d->m_glossaries.append(gi); d->m_glosstree->addTopLevelItem(d->createItem(gi)); d->m_glosstree->sortItems(0, Qt::AscendingOrder); } QTreeWidgetItem* GlossaryDialog::Private::findTreeWithLetter(const QChar& l, QTreeWidgetItem* item) const { int count = item->childCount(); for (int i = 0; i < count; ++i) { QTreeWidgetItem *itemchild = item->child(i); if (itemchild->data(0, FirstLetterRole).toChar() == l) { return itemchild; } } return nullptr; } void GlossaryDialog::Private::itemActivated(QTreeWidgetItem * item, int column) { Q_UNUSED(column) if (!item || item->type() != GlossaryTreeItemType) { return; } GlossaryTreeItem *glosstreeitem = static_cast(item); GlossaryItem *glossitem = glosstreeitem->glossaryItem(); QString html; QString bg_picture = glosstreeitem->glossary()->backgroundPicture(); if (!bg_picture.isEmpty()) { html = " background=\"file://" + bg_picture + "\""; } html = m_htmlbasestring.arg(html); html += glossitem->toHtml() + ""; m_htmlpart->begin(); m_htmlpart->write(html); m_htmlpart->end(); } void GlossaryItem::setRef(const QStringList& s) { m_ref = s; m_ref.sort(); } QString GlossaryItem::toHtml() const { QString code = "

" + m_name + "

" + m_desc + parseReferences(); return code; } QString GlossaryItem::parseReferences() const { if (m_ref.isEmpty()) { return QString(); } QString htmlcode = "

" + i18n("References") + "

    "; static QString basehref = QString("
  • %3
  • "); foreach (const QString& ref, m_ref) { htmlcode += basehref.arg(QUrl::toPercentEncoding(ref), i18n("Go to '%1'", ref), ref); } htmlcode += "
"; return htmlcode; } void GlossaryItem::setName(const QString& s) { m_name = s; } void GlossaryItem::setDesc(const QString& s) { m_desc = s; } void GlossaryItem::setPictures(const QString& s) { m_pic = QStringList(s); } QString GlossaryItem::name() const { return m_name; } QString GlossaryItem::desc() const { return m_desc; } QStringList GlossaryItem::ref() const { return m_ref; } QStringList GlossaryItem::pictures() const { return m_pic; } #include "moc_kdeeduglossary.cpp" diff --git a/src/kdeeduglossary.h b/src/kdeeduglossary.h index 1ae6d92f..1096cf4d 100644 --- a/src/kdeeduglossary.h +++ b/src/kdeeduglossary.h @@ -1,241 +1,241 @@ /*************************************************************************** * Copyright (C) 2005, 2006 by Carsten Niehaus * * Copyright (C) 2005 - 2007 by Pino Toscano * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #ifndef KDEEDUGLOSSARY_H #define KDEEDUGLOSSARY_H -#include +#include #include class QDomDocument; class GlossaryItem; /** * @class Glossary * @author Carsten Niehaus * @author Pino Toscano * * This class stores all items to be displayed. It also * has access-methods to the items */ class Glossary { public: /** * Creates a new glossary and add contents from an XML file. * Use isEmpty() to know if any items were loaded. * * @param url the path of the file to load * @param path the path of the pictures */ explicit Glossary(const QUrl& url, const QString& path = QString()); /** * Creates a new empty glossary */ Glossary(); virtual ~Glossary(); /** * add the item @p item to the glossary */ void addItem(GlossaryItem* item); QList itemlist()const; /** * clear the Glossary */ void clear(); /** * does this glossary have items? */ bool isEmpty() const; /** * Every glossary can have a name. It will be * set to @p name */ void setName(const QString& name); /** * @returns the name of the glossary */ QString name()const; /** * sets the internal list of items to @p list */ void setItemlist(QList list); /** * Every glossaryitem can show pictures. [img src="foo.png] * will look for the file foo.png in the path defined by * @p path */ void setPicturePath(const QString& path); QString picturePath()const; /** * defines which picture to use as the background * of the htmlview. The dialog * will use the file specifiec by the @p filename */ void setBackgroundPicture(const QString& filename); /** * @return the picuture used as the background in * this background */ QString backgroundPicture()const; protected: void init(const QUrl& url, const QString& path); private: /** * This methods parses the given XML code. It will extract * the information of the items and return them as a * QList */ virtual QList readItems(QDomDocument &itemDocument); QString m_backgroundpicture; /** * replaces the [img]-pseudocode with valid HTML. The path where * the pictures are stored will be used for pictures */ void fixImagePath(); /** * the path in which pictures of the glossary will be searched */ QString m_picturepath; /** * Load the layout from an XML file. * * @param doc The QDomDocument which will contain the read XML * contents. * @param url The path of the file to load * * @return a bool indicating whether the loading of the XML was * successful or not */ bool loadLayout(QDomDocument& doc, const QUrl& url); QList m_itemlist; /** * the name of the glossary */ QString m_name; }; /** * @class GlossaryItem * @author Carsten Niehaus * * A GlossaryItem stores the information of the content of * the item and its name. Furthermore, every item can have * a number of pictures or references associated to it. * These are stored as QStringLists. */ class GlossaryItem { public: GlossaryItem() {} ~GlossaryItem() {} void setName(const QString& s); void setDesc(const QString& s); /** * Set the references for the current GlossaryItem to * @p s. * There's no need to sort the list before, as they * will be sorted automatically */ void setRef(const QStringList& s); void setPictures(const QString& s); QString name() const; QString desc() const; QStringList ref() const; QStringList pictures() const; /** * @return the formated HTML code for current item. */ QString toHtml() const; /** * This method parses the references. * @return the HTML code with the references as HTML links */ QString parseReferences() const; private: QString m_name; QString m_desc; QStringList m_ref; QStringList m_pic; }; /** * @class GlossaryDialog * @author Pino Toscano * @author Carsten Niehaus */ -class GlossaryDialog : public KDialog +class GlossaryDialog : public QDialog { Q_OBJECT public: /** * Creates a new dialog for a glossary. * * @param parent the parent of the new dialog */ explicit GlossaryDialog(QWidget *parent = nullptr); ~GlossaryDialog() override; /** * Add a new glossary. * * @param newgloss the new glossary to add * @param folded whether to fold the various items in subtrees depending on the * first letter of every item */ void addGlossary(Glossary* newgloss, bool folded = true); protected: void keyPressEvent(QKeyEvent*) override; private: class Private; Private * const d; Q_PRIVATE_SLOT(d, void itemActivated(QTreeWidgetItem *, int)) Q_PRIVATE_SLOT(d, void displayItem(const QUrl &, const KParts::OpenUrlArguments &, const KParts::BrowserArguments &)) }; #endif // KDEEDUGLOSSARY_H diff --git a/src/legendwidget.cpp b/src/legendwidget.cpp index 5df7d4cf..9a6ca78c 100644 --- a/src/legendwidget.cpp +++ b/src/legendwidget.cpp @@ -1,228 +1,228 @@ /*************************************************************************** * Copyright (C) 2007 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "legendwidget.h" #include "prefs.h" -#include - #include #include #include +#include + LegendWidget::LegendWidget(QWidget *parent) : QWidget(parent) { m_update = true; m_dockArea = Qt::BottomDockWidgetArea; } LegendWidget::~LegendWidget() { qDeleteAll(m_legendItemList); } void LegendWidget::setDockArea(Qt::DockWidgetArea newDockArea) { qDebug() << "dock Area changed" << newDockArea; m_dockArea = newDockArea; updateContent(); } void LegendWidget::LockWidget() { m_update = false; } void LegendWidget::UnLockWidget() { m_update = true; } void LegendWidget::updateContent() { if (!m_update) { return; } QString gradientDesc; QList< QPair > items; KalziumElementProperty *elementProperty = KalziumElementProperty::instance(); // Handle different Gradients switch (elementProperty->gradientId()) { case KalziumElementProperty::NOGRADIENT: // None break; case KalziumElementProperty::SOMGradientType: items << qMakePair(elementProperty->gradient()->description(), QColor()); items << qMakePair(i18nc("one of the three states of matter (solid, liquid, vaporous or unknown)", "Solid"), QColor(Prefs::color_solid())); items << qMakePair(i18nc("one of the three states of matter (solid, liquid, vaporous or unknown)", "Liquid"), QColor(Prefs::color_liquid())); items << qMakePair(i18nc("one of the three states of matter (solid, liquid, vaporous or unknown)", "Vaporous"), QColor(Prefs::color_vapor())); items << qMakePair(i18nc("one of the three states of matter (solid, liquid, vaporous or unknown)", "Unknown"), QColor(Qt::lightGray)); break; default: if (elementProperty->gradient()->logarithmicGradient()) { gradientDesc = i18nc("one of the two types of gradients available", "logarithmic"); } else { gradientDesc = i18nc("one of the two types of gradients available", "linear"); } items << qMakePair(i18n("%1 (%2)", elementProperty->gradient()->description(), gradientDesc), QColor()); items << qMakePair(i18nc("Minimum value of the gradient", "Minimum: %1", QString::number(elementProperty->gradient()->minValue()) + ' ' + elementProperty->gradient()->unit()), QColor(elementProperty->gradient()->firstColor())); items << qMakePair(i18nc("Maximum value of the gradient", "Maximum: %1", QString::number(elementProperty->gradient()->maxValue()) + ' ' + elementProperty->gradient()->unit()), QColor(elementProperty->gradient()->secondColor())); break; } // schemes are always there items << qMakePair(i18n("Scheme: %1", elementProperty->scheme()->description()), QColor()); items << elementProperty->scheme()->legendItems(); updateLegendItemLayout(items); } void LegendWidget::updateLegendItemLayout(const QList& list) { if (layout()) { delete layout(); } foreach (LegendItem * i, m_legendItemList) { delete i; } m_legendItemList.clear(); QGridLayout * layout = new QGridLayout(this); layout->setSpacing(0); layout->setMargin(0); int x = 0; int y = 0; foreach (const legendPair &pair, list) { LegendItem *item = new LegendItem(pair, this); m_legendItemList.append(item); if ((m_dockArea == Qt::BottomDockWidgetArea || m_dockArea == Qt::TopDockWidgetArea)) { if (!pair.second.isValid()) { ++y; x = 0; } if (x >= 3) { ++y; x = 1; } } layout->addWidget(item, x, y); ++x; } setLayout(layout); } void LegendWidget::legendItemAction(QColor color) { emit resetElementMatch(); if (color.operator==(QColor())) { return; } for (int element = 1; element <= 118; ++element) { if (isElementMatch(element, color)) { emit elementMatched(element); } } } bool LegendWidget::isElementMatch(int element, QColor &color){ QColor elementBackgroundColor; QColor elementBorderColor; elementBackgroundColor = KalziumElementProperty::instance()->getElementColor(element); elementBorderColor = KalziumElementProperty::instance()->getBorderColor(element); switch(Prefs::colorgradientbox()){ case KalziumElementProperty::NOGRADIENT: if (elementBackgroundColor.operator!=(color)) { return true; } break; default: // all other gradients if (elementBorderColor.operator==(color) || elementBackgroundColor.operator==(color)) { return true; } } return false; } LegendItem::LegendItem(const QPair& pair, QWidget * parent) { QHBoxLayout *ItemLayout = new QHBoxLayout(this); ItemLayout->setMargin(0); if (pair.second.isValid()) { legendItemColor = pair.second; connect(this, SIGNAL(legenItemHoovered(QColor)), parent, SLOT(legendItemAction(QColor))); QPixmap LegendPixmap(20, height()); LegendPixmap.fill(pair.second); QLabel * LabelPixmap = new QLabel(this); LabelPixmap->setPixmap(LegendPixmap); ItemLayout->addWidget(LabelPixmap); setFrameShape(QFrame::StyledPanel); setFrameShadow(QFrame::Sunken); } QLabel * LegendLabel = new QLabel(this); LegendLabel->setText(pair.first); ItemLayout->addWidget(LegendLabel); ItemLayout->setAlignment(Qt::AlignLeft); setLayout(ItemLayout); } void LegendItem::enterEvent(QEvent* event) { emit legenItemHoovered(legendItemColor); QWidget::enterEvent(event); } void LegendItem::leaveEvent(QEvent* event) { emit legenItemHoovered(QColor()); QWidget::leaveEvent(event); } diff --git a/src/legendwidget.h b/src/legendwidget.h index 791392db..e6053b2c 100644 --- a/src/legendwidget.h +++ b/src/legendwidget.h @@ -1,100 +1,98 @@ /*************************************************************************** * Copyright (C) 2007 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef LEGENDWIDGET_H #define LEGENDWIDGET_H -#include - #include "kalziumelementproperty.h" #include class LegendItem; /** * @author Carsten Niehaus * * The LegendWidget displays the explanations of what the user is currently * seeing in the table */ class LegendWidget : public QWidget { Q_OBJECT public: explicit LegendWidget(QWidget *parent); ~LegendWidget(); void LockWidget(); void UnLockWidget(); Q_SIGNALS: void elementMatched(int element); void resetElementMatch(); public slots: void updateContent(); void setDockArea(Qt::DockWidgetArea newDockArea); /// is triggered when a LegenItem is Hoovered. void legendItemAction(QColor color); private: bool isElementMatch(int element, QColor &color); bool m_update; QPixmap m_pixmap; QList m_legendItemList; Qt::DockWidgetArea m_dockArea; void updateLegendItemLayout(const QList& list); }; /** * A LegendItem is displayed as one small rectangle which represents the * color in the table with a short explanation for it. * * @author Carsten Niehaus */ class LegendItem : public QLabel { Q_OBJECT public: LegendItem(const QPair& pair, QWidget * parent = nullptr); ~LegendItem() {} Q_SIGNALS: void legenItemHoovered(QColor color); private: QColor legendItemColor; protected: void enterEvent(QEvent * event) override; void leaveEvent(QEvent * event) override; }; #endif // LEGENDWIDGET_H diff --git a/src/molcalcwidget.cpp b/src/molcalcwidget.cpp index 0a477f65..0d8ce77d 100644 --- a/src/molcalcwidget.cpp +++ b/src/molcalcwidget.cpp @@ -1,332 +1,332 @@ /*************************************************************************** * Copyright (C) 2003-2005, 2006 by Carsten Niehaus, cniehaus@kde.org * * Copyright (C) 2005 by Inge Wallin, inge@lysator.liu.se * * Copyright (C) 2009 by Kashyap. R. Puranik, kashthealien@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * * ***************************************************************************/ #include "molcalcwidget.h" //libscience #include #include "kalziumdataobject.h" #include "kalziumutils.h" #include "search.h" #include "prefs.h" #include #include -#include +#include #include #include #include #include #include #include MolcalcWidget::MolcalcWidget(QWidget *parent) : QWidget(parent) { m_parser = new MoleculeParser(KalziumDataObject::instance()->ElementList); m_timer = new QTimer(this); m_timer->setSingleShot(true); ui.setupUi(this); connect(ui.calcButton, SIGNAL(clicked()), this, SLOT(slotCalculate())); connect(ui.formulaEdit, SIGNAL(returnPressed()), this, SLOT(slotCalculate())); connect(m_timer, SIGNAL(timeout()), this, SLOT(slotCalculate())); ui.formulaEdit->setClearButtonEnabled(true); clear(); if (!Prefs::addAlias()) { hideExtra(); ui.details->show(); } if (!Prefs::alias()) { ui.details->hide(); } if (Prefs::addAlias()) { connect(ui.alias, SIGNAL(clicked()), this, SLOT(addAlias())); QString shortForm, fullForm; // short form (symbol) and full form (expansion) QList shortList, fullList; // Used to store the short and full forms int i = 0; // loop counter // Search in User defined aliases. QString fileName = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "libkdeedu/data/symbols2.csv"); QFile file(fileName); // Check file validity if (!(!file.open(QIODevice::ReadOnly | QIODevice::Text))) { qDebug() << fileName << " opened"; QTextStream in(&file); // Get all shortForms and fullForms in the file. // eg the short form and full form extracted from ("Me","CH3") // are (Me) and (CH3) respectively while (!in.atEnd()) { QString line = in.readLine(); shortForm = line.section(',', 0, 0); shortForm.remove(QChar('\"')); fullForm = line.section(',', 1, 1); fullForm.remove(QChar('\"')); shortList << shortForm; fullList << fullForm; } int length = shortList.length(); ui.user_defined->setRowCount(length); // Put all the aliases on to the table in the user interface for (i = 0; i < length; ++i) { shortForm = shortList.takeFirst (); fullForm = fullList.takeFirst (); ui.user_defined->setItem((int)i, 0, new QTableWidgetItem (i18n("%1",shortForm + " : " + fullForm))); } } else { qDebug() << fileName << " could not be opened!"; } // Find the system defined aliases // Open the file fileName = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "libkdeedu/data/symbols.csv"); QFile file2(fileName); shortList.clear(); fullList.clear(); // Check file validity if (!(!file2.open(QIODevice::ReadOnly | QIODevice::Text))) { qDebug() << fileName << " opened"; QTextStream in(&file2); // Get all shortForms and fullForms in the file. while (!in.atEnd()) { QString line = in.readLine(); shortForm = line.section(',', 0, 0); shortForm.remove(QChar('\"')); fullForm = line.section(',', 1, 1); fullForm.remove(QChar('\"')); shortList << shortForm; fullList << fullForm; } int length = shortList.length(); ui.pre_defined->setRowCount(length); // Put all the aliases on to the table in the user interface for (i = 0; i < length; ++i) { shortForm = shortList.takeFirst(); fullForm = fullList.takeFirst(); ui.pre_defined->setItem((int)i, 0, new QTableWidgetItem (i18n("%1",shortForm + " : " + fullForm))); } } else { qDebug() << fileName << " could not be opened!"; } } } MolcalcWidget::~MolcalcWidget() { delete m_parser; } void MolcalcWidget::clear() { // Clear the data. m_mass = 0; m_elementMap.clear(); //stop the selection in the periodic table KalziumDataObject::instance()->search()->resetSearch(); // Clear the widgets. ui.resultLabel->clear(); ui.resultMass->clear(); ui.resultValue->hide(); ui.resultComposition->setText(i18n("Enter a formula in the\nwidget above and\nclick on 'Calc'.\nE.g. #Et#OH")); ui.resultMass->setToolTip(QString()); ui.resultComposition->setToolTip(QString()); ui.resultLabel->setToolTip(QString()); } void MolcalcWidget::updateUI() { qDebug() << "MolcalcWidget::updateUI()"; if (m_validInput) { qDebug() << "m_validInput == true"; // The complexString stores the whole molecule like this: // 1 Seaborgium. Cumulative Mass: 263.119 u (39.2564 %) QString complexString; if (Prefs::alias()) { double mass; QString str; int i = 0; // counter int rows = m_elementMap.elements().count(); // number of columns ui.table->setRowCount(rows); foreach (ElementCount *count, m_elementMap.map()) { // Update the resultLabel mass = count->element()->dataAsVariant(ChemicalDataObject::mass).toDouble(); ui.table->setItem(i, 0, new QTableWidgetItem (i18n("%1", count->element()->dataAsString(ChemicalDataObject::name)))); ui.table->setItem(i, 1, new QTableWidgetItem (i18n("%1", count->count()))); ui.table->setItem(i, 2, new QTableWidgetItem (i18n("%1", count->element()->dataAsString(ChemicalDataObject::mass)))); ui.table->setItem(i, 3, new QTableWidgetItem (i18n("%1", mass * count->count()))); ui.table->setItem(i, 4, new QTableWidgetItem (i18n("%1", mass * count->count()/ m_mass *100))); ++i; } // The alias list i = 0; rows = m_aliasList.count(); ui.alias_list->setRowCount(rows); foreach (const QString &alias, m_aliasList) { ui.alias_list->setItem(i++, 0, new QTableWidgetItem(alias)); } } // The composition ui.resultComposition->setText(compositionString(m_elementMap)); // The mass ui.resultMass->setText(i18n("Molecular mass: ")); ui.resultValue->setText(QString::number(m_mass) + " u"); ui.resultValue->show(); ui.resultMass->setToolTip(complexString); ui.resultComposition->setToolTip(complexString); #if 0 // FIXME //select the elements in the table QList list = m_elementMap.elements(); KalziumDataObject::instance()->findElements(list); #endif } else { //the input was invalid, so tell this the user qDebug() << "m_validInput == false"; ui.resultComposition->setText(i18n("Invalid input")); ui.resultLabel->setText(QString()); ui.resultMass->setText(QString()); ui.resultMass->setToolTip(i18n("Invalid input")); ui.resultComposition->setToolTip(i18n("Invalid input")); ui.resultLabel->setToolTip(i18n("Invalid input")); } } QString MolcalcWidget::compositionString(ElementCountMap &_map) { QString str; foreach (ElementCount * count, _map.map()) { str += i18n("%1%2 ", count->element()->dataAsString(ChemicalDataObject::symbol), count->count()); } return str; } // ---------------------------------------------------------------- // slots void MolcalcWidget::slotCalculate() { qDebug() << "MolcalcWidget::slotCalcButtonClicked()"; QString molecule = ui.formulaEdit->text(); // Parse the molecule, and at the same time calculate the total // mass, and the composition of it. if (!molecule.isEmpty()) { m_validInput = m_parser->weight(molecule, &m_mass, &m_elementMap); m_aliasList = m_parser->aliasList(); } qDebug() << "done calculating."; updateUI(); } void MolcalcWidget::keyPressEvent(QKeyEvent * /* e */) { m_timer->start(500); } void MolcalcWidget::addAlias() { QString shortForm = ui.shortForm->text(); QString fullForm = ui.fullForm ->text(); // Validate the alias double x; ElementCountMap y; ui.aliasMessage->setText(""); if (shortForm.length() < 2) { ui.aliasMessage->setText(i18n ("Symbol should consist of two or more letters.")); return; } if (m_parser->weight(shortForm, &x, &y)) { ui.aliasMessage->setText(i18n ("Symbol already being used")); return; } if (fullForm.isEmpty() || ! m_parser->weight(fullForm, & x, & y)) { ui.aliasMessage->setText(i18n ("Expansion is invalid, please specify a valid expansion")); return; } // Open the file to write QString fileName = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "libkdeedu/data/symbols2.csv"); QFile file(fileName); if (!(!file.open(QIODevice::WriteOnly| QIODevice::Append | QIODevice::Text))) { QTextStream out(&file); out << "\"" + shortForm + "\",\"" + fullForm + "\"\n"; qDebug() << fileName << "is the file."; qDebug() << "\"" + shortForm + "\",\"" + fullForm + "\"\n"; ui.aliasMessage->setText(i18n("done!")); return; } else { ui.aliasMessage->setText((i18n ("Unable to find the user defined alias file."))+fileName); return; } } void MolcalcWidget::hideExtra() { ui.details->hide(); ui.tabWidget->removeTab(1); } diff --git a/src/psetable/elementitem.cpp b/src/psetable/elementitem.cpp index 1b4f8a27..043817d0 100644 --- a/src/psetable/elementitem.cpp +++ b/src/psetable/elementitem.cpp @@ -1,156 +1,156 @@ /********************************************************************** ElementItem - Element Item, part of the Periodic Table Graphics View for Avogadro Copyright (C) 2007-2009 by Marcus D. Hanwell marcus@cryos.org Some portions (C) 2010 by Konstantin Tokarev Copyright (C) 2010 by Etienne Rebetez etienne.rebetez@oberwallis.ch This file is part of the Avogadro molecular editor project. For more information, see Avogadro is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Avogadro is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **********************************************************************/ #include "elementitem.h" #include -#include +#include #include #include #include #include #include #include ElementItem::ElementItem(KalziumElementProperty *elProperty, int elementNumber) : m_width(40), m_height(40), m_element(elementNumber), m_property(elProperty) { // Want these items to be selectable setFlags(QGraphicsItem::ItemIsSelectable); setAcceptsHoverEvents(true); m_symbol = KalziumDataObject::instance()->element(m_element)->dataAsString(ChemicalDataObject::symbol); // Set some custom data to make it easy to figure out which element we are setData(0, m_element); } ElementItem::~ElementItem() { } QRectF ElementItem::boundingRect() const { return QRectF(0, 0, m_width, m_height); } QPainterPath ElementItem::shape() const { QPainterPath path; path.addRect(0, 0, m_width, m_height); return path; } void ElementItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { QPen pen; pen.setColor(m_borderColor); pen.setWidth(1); painter->setPen(pen); painter->setBrush(m_brush); painter->drawRoundedRect(boundingRect(), m_width / 10, m_width / 10); if (isSelected()) { QColor selectedBackgroundColor = m_borderColor; selectedBackgroundColor.setAlpha(160); painter->setBrush(QBrush(QColor(selectedBackgroundColor))); painter->drawRoundedRect(boundingRect(), m_width / 10, m_width / 10); } pen.setColor(m_textColor); painter->setPen(pen); QFont symbolFont; switch (m_property->getMode()) { case KalziumElementProperty::NORMAL: symbolFont.setPointSize(12); symbolFont.setBold(true); painter->setFont(symbolFont); painter->drawText(boundingRect(), Qt::AlignCenter, m_symbol); symbolFont.setPointSize(7); symbolFont.setBold(false); painter->setFont(symbolFont); painter->drawText(QRectF(m_width / 14, m_height / 20, m_width, m_height / 2), Qt::AlignLeft, QString::number(m_element)); break; case KalziumElementProperty::GRADIENTVALUE: painter->drawText(QRectF(0, m_height / 20, m_width, m_height / 2), Qt::AlignCenter, m_symbol); symbolFont.setPointSize(7); painter->setFont(symbolFont); painter->drawText(QRectF(0, m_height / 2 - m_height / 20, m_width, m_height / 2), Qt::AlignCenter, m_textValue); break; } } void ElementItem::redraw() { m_brush = m_property->getElementBrush(m_element); m_textColor = m_property->getTextColor(m_element); m_borderColor = m_property->getBorderColor(m_element); m_textValue = getCurrentElementValue(); update(); } QString ElementItem::getCurrentElementValue() { double value = m_property->getValue(m_element); if (value == -1) { return i18n("n/a"); } return QString::number(value); } void ElementItem::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { setZValue(200); moveBy(-m_width / 4, -m_height / 4); scale(1.5, 1.5); QGraphicsItem::hoverEnterEvent(event); } void ElementItem::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { resetTransform(); moveBy(m_width / 4, m_height / 4); setZValue(100); QGraphicsItem::hoverLeaveEvent(event); } diff --git a/src/psetable/numerationitem.cpp b/src/psetable/numerationitem.cpp index f9044077..bbf16fe6 100644 --- a/src/psetable/numerationitem.cpp +++ b/src/psetable/numerationitem.cpp @@ -1,87 +1,87 @@ /********************************************************************** NumerationItem - Numeration Item, part of the Periodic Table Graphics View for Kalzium Copyright (C) 2007-2009 by Marcus D. Hanwell marcus@cryos.org Some portions (C) 2010 by Konstantin Tokarev Copyright (C) 2010 by Etienne Rebetez etienne.rebetez@oberwallis.ch This file is part of the Avogadro molecular editor project. For more information, see Kalzium is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Avogadro is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **********************************************************************/ #include "numerationitem.h" #include -#include +#include #include #include #include #include #include #include "kalziumnumerationtype.h" NumerationItem::NumerationItem(int xPosition) : m_width(40), m_height(20), m_xPosition(xPosition) { setNumerationType(Prefs::numeration()); } NumerationItem::~NumerationItem() { } QRectF NumerationItem::boundingRect() const { return QRectF(0, 0, m_width, m_height); } QPainterPath NumerationItem::shape() const { QPainterPath path; path.addRect(0, 0, m_width, m_height); return path; } void NumerationItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { QPen pen; QLinearGradient grad(QPointF(0, 0), QPointF(0, m_height)); grad.setColorAt(0, m_color); grad.setColorAt(1, m_color.darker()); painter->setBrush(grad); pen.setColor(m_color.dark(1000)); painter->setPen(pen); QRectF rect(0, 0, m_width, m_height); painter->drawRoundedRect(rect, m_width / 10, m_width / 10); painter->drawText(rect, Qt::AlignCenter, m_numeration); } void NumerationItem::setNumerationType(int type) { type == 0 ? m_color = QColor(Qt::transparent) : m_color = QColor(Qt::white); m_numeration = KalziumNumerationTypeFactory::instance()->build(type)->item(m_xPosition); update(); } diff --git a/src/rsdialog.cpp b/src/rsdialog.cpp index 90c1aff0..45eba7a3 100644 --- a/src/rsdialog.cpp +++ b/src/rsdialog.cpp @@ -1,322 +1,331 @@ /*************************************************************************** * Copyright (C) 2006, 2008 by Carsten Niehaus * * cniehaus@kde.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "rsdialog.h" +#include +#include #include +#include #include "kalziumdataobject.h" #include "kalziumutils.h" +#include +#include #include -#include #include -RSDialog::RSDialog(QWidget* parent) : KDialog(parent) +RSDialog::RSDialog(QWidget* parent) : QDialog(parent) { - setCaption(i18n("Risks/Security Phrases")); - setButtons(Help | Close); + setWindowTitle(i18n("Risks/Security Phrases")); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Close); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + connect(buttonBox, &QDialogButtonBox::rejected, this, &RSDialog::reject); + mainLayout->addWidget(buttonBox); createRPhrases(); createSPhrases(); - ui.setupUi(mainWidget()); + ui.setupUi(mainWidget); connect(ui.filterButton, SIGNAL(clicked()), this, SLOT(filter())); - connect(this, SIGNAL(helpClicked()), - this, SLOT(slotHelp())); + connect(buttonBox, &QDialogButtonBox::helpRequested, this, &RSDialog::slotHelp); filter(); } void RSDialog::filter() { //if the RS sentence starts or ends with a - invalidate it. //It is probably an user error if ( ui.r_le->text().startsWith('-') || ui.r_le->text().endsWith('-') || ui.s_le->text().startsWith('-') || ui.s_le->text().endsWith('-') ) { invalidPhaseString(); return; } QList r; QList s; //for now only separation by a - is allowed if (!ui.r_le->text().isEmpty()) { const QStringList rSplit = ui.r_le->text().split('-'); foreach (const QString &st, rSplit) { r << st.toInt(); } } //for now only separation by a - is allowed if (!ui.s_le->text().isEmpty()) { const QStringList sSplit = ui.s_le->text().split('-'); foreach (const QString &st, sSplit) { s << st.toInt(); } } filterRS(r, s); } void RSDialog::filterRS(const QList& r, const QList& s) { QString string(""); if (r.count() > 0) { string.append("

" + i18n("R-Phrases:") + "

"); foreach (int i, r) { QString phrase("" + QString::number(i) + " - "); phrase.append(rphrase(i) + ""); string.append(phrase + "
"); } } if (s.count() > 0) { string.append("

" + i18n("S-Phrases:") + "

"); foreach (int i, s) { QString phrase("" + QString::number(i) + " - "); phrase.append(sphrase(i) + ""); string.append(phrase + "
"); } } if (s.count() == 0 && r.count() == 0) string.append("

" + i18n("You asked for no R/S-Phrases.") + "

"); string.append("
"); ui.text->setHtml(string); } QString RSDialog::rphrase(int number) { QString p; QMap::const_iterator i = rphrases_map.constBegin(); while (i != rphrases_map.constEnd()) { if (i.key() == number) { return i.value(); } ++i; } return p; } QString RSDialog::sphrase(int number) { QString p; QMap::const_iterator i = sphrases_map.constBegin(); while (i != sphrases_map.constEnd()) { if (i.key() == number) { return i.value(); } ++i; } return p; } void RSDialog::createSPhrases() { QStringList sphrases; sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S1: Keep locked up"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S2: Keep out of the reach of children"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S3: Keep in a cool place"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S4: Keep away from living quarters"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S5: Keep contents under ... ( appropriate liquid to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S6: Keep under ... ( inert gas to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S7: Keep container tightly closed"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S8: Keep container dry"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S9: Keep container in a well-ventilated place"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S12: Do not keep the container sealed"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S13: Keep away from food, drink and animal feedingstuffs"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S14: Keep away from ... ( incompatible materials to be indicated by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S15: Keep away from heat"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S16: Keep away from sources of ignition - No smoking"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S17: Keep away from combustible material"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S18: Handle and open container with care"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S20: When using do not eat or drink"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S21: When using do not smoke"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S22: Do not breathe dust"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S23: Do not breathe gas/fumes/vapour/spray ( appropriate wording to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S24: Avoid contact with skin"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S25: Avoid contact with eyes"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S26: In case of contact with eyes, rinse immediately with plenty of water and seek medical advice"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S27: Take off immediately all contaminated clothing"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S28: After contact with skin, wash immediately with plenty of ... ( to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S29: Do not empty into drains"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S30: Never add water to this product"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S33: Take precautionary measures against static discharges"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S35: This material and its container must be disposed of in a safe way"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S36: Wear suitable protective clothing"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S37: Wear suitable gloves"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S38: In case of insufficient ventilation wear suitable respiratory equipment"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S39: Wear eye/face protection"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S40: To clean the floor and all objects contaminated by this material use ... ( to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S41: In case of fire and/or explosion do not breathe fumes"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S42: During fumigation/spraying wear suitable respiratory equipment ( appropriate wording to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S43: In case of fire use ... ( indicate in the space the precise type of fire-fighting equipment. If water increases the risk add - Never use water )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S45: In case of accident or if you feel unwell seek medical advice immediately ( show the label where possible )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S46: If swallowed, seek medical advice immediately and show this container or label"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S47: Keep at temperature not exceeding ... °C ( to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S48: Keep wet with ... ( appropriate material to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S49: Keep only in the original container"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S50: Do not mix with ... ( to be specified by the manufacturer )"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S51: Use only in well-ventilated areas"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S52: Not recommended for interior use on large surface areas"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S53: Avoid exposure - obtain special instructions before use"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S56: Dispose of this material and its container at hazardous or special waste collection point"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S57: Use appropriate containment to avoid environmental contamination"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S59: Refer to manufacturer/supplier for information on recovery/recycling"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S60: This material and its container must be disposed of as hazardous waste"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S61: Avoid release to the environment. Refer to special instructions/safety data sheet"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S62: If swallowed, do not induce vomiting: seek medical advice immediately and show this container or label"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S63: In case of accident by inhalation: remove casualty to fresh air and keep at rest"); sphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "S64: If swallowed, rinse mouth with water ( only if the person is conscious )"); QRegExp reg("(R|S)(\\d+): (.*)"); foreach (const QString &p, sphrases) { int number = 0; QString phrase(""); if (reg.indexIn(p) > -1) { QString part1 = reg.cap(2); QString part2 = reg.cap(3); phrase = part2; number = part1.toInt(); } sphrases_map.insert(number, phrase); } } void RSDialog::createRPhrases() { QStringList rphrases; rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R1: Explosive when dry"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R2: Risk of explosion by shock, friction, fire or other sources of ignition"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R3: Extreme risk of explosion by shock, friction, fire or other sources of ignition"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R4: Forms very sensitive explosive metallic compounds"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R5: Heating may cause an explosion"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R6: Explosive with or without contact with air"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R7: May cause fire"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R8: Contact with combustible material may cause fire"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R9: Explosive when mixed with combustible material"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R10: Flammable"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R11: Highly flammable"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R12: Extremely flammable"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R14: Reacts violently with water"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R15: Contact with water liberates extremely flammable gases"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R16: Explosive when mixed with oxidising substances"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R17: Spontaneously flammable in air"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R18: In use, may form flammable/explosive vapour-air mixture"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R19: May form explosive peroxides"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R20: Harmful by inhalation"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R21: Harmful in contact with skin"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R22: Harmful if swallowed"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R23: Toxic by inhalation"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R24: Toxic in contact with skin"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R25: Toxic if swallowed"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R26: Very toxic by inhalation"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R27: Very toxic in contact with skin"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R28: Very toxic if swallowed"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R29: Contact with water liberates toxic gas."); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R30: Can become highly flammable in use"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R31: Contact with acids liberates toxic gas"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R32: Contact with acids liberates very toxic gas"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R33: Danger of cumulative effects"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R34: Causes burns"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R35: Causes severe burns"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R36: Irritating to eyes"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R37: Irritating to respiratory system"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R38: Irritating to skin"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R39: Danger of very serious irreversible effects"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R40: Limited evidence of a carcinogenic effect"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R41: Risk of serious damage to eyes"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R42: May cause sensitisation by inhalation"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R43: May cause sensitisation by skin contact"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R44: Risk of explosion if heated under confinement"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R45: May cause cancer"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R46: May cause heritable genetic damage"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R48: Danger of serious damage to health by prolonged exposure"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R49: May cause cancer by inhalation"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R50: Very toxic to aquatic organisms"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R51: Toxic to aquatic organisms"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R52: Harmful to aquatic organisms"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R53: May cause long-term adverse effects in the aquatic environment"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R54: Toxic to flora"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R55: Toxic to fauna"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R56: Toxic to soil organisms"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R57: Toxic to bees"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R58: May cause long-term adverse effects in the environment"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R59: Dangerous for the ozone layer"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R60: May impair fertility"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R61: May cause harm to the unborn child"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R62: Possible risk of impaired fertility"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R63: Possible risk of harm to the unborn child"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R64: May cause harm to breast-fed babies"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R65: Harmful: may cause lung damage if swallowed"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R66: Repeated exposure may cause skin dryness or cracking"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R67: Vapours may cause drowsiness and dizziness"); rphrases << i18nc("Please take the official translations! You find them here: http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:32001L0059:EN:HTML", "R68: Possible risk of irreversible effects"); QRegExp reg("(R|S)(\\d+): (.*)"); foreach (const QString &p, rphrases) { int number = 0; QString phrase(""); if (reg.indexIn(p) > -1) { QString part1 = reg.cap(2); QString part2 = reg.cap(3); phrase = part2; number = part1.toInt(); } rphrases_map.insert(number, phrase); } } void RSDialog::slotHelp() { KHelpClient::invokeHelp("rs_phrases", QLatin1String("kalzium")); } void RSDialog::invalidPhaseString() { KMessageBox::error(nullptr, i18n("At least one of the specified phrases is invalid.")); } diff --git a/src/rsdialog.h b/src/rsdialog.h index 930276c4..e6154b94 100644 --- a/src/rsdialog.h +++ b/src/rsdialog.h @@ -1,68 +1,68 @@ /*************************************************************************** * Copyright (C) 2006-2008 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef RSDIALOG_H #define RSDIALOG_H -#include +#include #include #include #include "ui_rswidget.h" /** * This class * * @author Carsten Niehaus */ -class RSDialog : public KDialog +class RSDialog : public QDialog { Q_OBJECT public: RSDialog(QWidget * parent); Ui::RSWidget ui; /** * Filter the R- and S-Phrases. */ void filterRS(const QList& r, const QList& s); QString rphrase(int number); QString sphrase(int number); public slots: void filter(); private slots: void slotHelp(); private: QMap rphrases_map; QMap sphrases_map; void createSPhrases(); void createRPhrases(); void invalidPhaseString(); }; #endif // RSDIALOG_H diff --git a/src/spectrumwidget.cpp b/src/spectrumwidget.cpp index 081b53cf..c6ce5264 100644 --- a/src/spectrumwidget.cpp +++ b/src/spectrumwidget.cpp @@ -1,395 +1,394 @@ /*************************************************************************** * Copyright (C) 2005, 2006 by Carsten Niehaus * * cniehaus@kde.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "spectrumwidget.h" #include "spectrum.h" #include "kalziumutils.h" #include #include -#include #include #include #include #include #include #include #include #include #if defined(HAVE_IEEEFP_H) #include #endif SpectrumWidget::SpectrumWidget(QWidget *parent) : QWidget(parent) { m_startValue = 0; m_endValue = 0; m_LMBPointCurrent.setX(-1); m_LMBPointPress.setX(-1); m_realHeight = 200; m_gamma = 0.8; m_intensityMax = 255; setType(Prefs::spectrumType()); setMinimumSize(400, 230); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setAttribute(Qt::WA_OpaquePaintEvent, true); setContextMenuPolicy(Qt::PreventContextMenu); } void SpectrumWidget::paintEvent(QPaintEvent * /*e*/) { if (!m_spectrum) { return; } m_pixmap = QPixmap(width(), height()); m_pixmap.fill(this, width(), height()); QPainter p; p.begin(&m_pixmap); p.fillRect(0, 0, width(), m_realHeight, Qt::black); paintBands(&p); drawTickmarks(&p); if (m_LMBPointPress.x() != -1 && m_LMBPointCurrent.x() != -1) { drawZoomLine(&p); } p.end(); QPainter p2(this); p2.drawPixmap(0, 0, m_pixmap); } void SpectrumWidget::drawZoomLine(QPainter* p) { p->setPen(Qt::white); p->drawLine(m_LMBPointPress.x(), m_LMBPointPress.y(), m_LMBPointCurrent.x(), m_LMBPointPress.y()); p->drawLine(m_LMBPointCurrent.x(), m_LMBPointPress.y() + 10, m_LMBPointCurrent.x(), m_LMBPointPress.y() - 10); p->drawLine(m_LMBPointPress.x(), m_LMBPointPress.y() + 10, m_LMBPointPress.x(), m_LMBPointPress.y() - 10); } void SpectrumWidget::paintBands(QPainter* p) { if (m_type == AbsorptionSpectrum) { for (double va = m_startValue; va <= m_endValue; va += 0.1) { int x = xPos(va); p->setPen(wavelengthToRGB(va)); p->drawLine(x, 0, x, m_realHeight); } p->setPen(Qt::black); } int i = 0; int x = 0; double currentWavelength; foreach (Spectrum::peak *peak, m_spectrum->peaklist()) { currentWavelength = peak->wavelengthToUnit(Prefs::spectrumWavelengthUnit()); if (currentWavelength < m_startValue || currentWavelength > m_endValue) { continue; } x = xPos(currentWavelength); switch (m_type) { case EmissionSpectrum: p->setPen(wavelengthToRGB(currentWavelength)); p->drawLine(x, 0, x, m_realHeight - 1); p->setPen(Qt::black); p->drawLine(x, m_realHeight, x, m_realHeight); break; case AbsorptionSpectrum: p->setPen(Qt::black); p->drawLine(x, 0, x, m_realHeight - 1); break; } ++i; } } QColor SpectrumWidget::wavelengthToRGB(double wavelength) { double blue = 0.0, green = 0.0, red = 0.0, factor = 0.0; // wavelengthTo RGB function works with nanometers. wavelength = KUnitConversion::Value(wavelength,KUnitConversion::UnitId(Prefs::spectrumWavelengthUnit())) .convertTo(KUnitConversion::Nanometer).number(); int wavelength_ = (int)floor(wavelength); if (wavelength_ < 380 || wavelength_ > 780) { return QColor(Qt::white); } else if (wavelength_ >= 380 && wavelength_ < 440) { red = -(wavelength - 440) / (440 - 380); green = 0.0; blue = 1.0; } else if (wavelength_ >= 440 && wavelength_ < 490) { red = 0.0; green = (wavelength - 440) / (490 - 440); blue = 1.0; } else if (wavelength_ >= 490 && wavelength_ < 510) { red = 0.0; green = 1.0; blue = -(wavelength - 510) / (510 - 490); } else if (wavelength_ >= 510 && wavelength_ < 580) { red = (wavelength - 510) / (580 - 510); green = 1.0; blue = 0.0; } else if (wavelength_ >= 580 && wavelength_ < 645) { red = 1.0; green = -(wavelength - 645) / (645 - 580); blue = 0.0; } else if (wavelength_ >= 645 && wavelength_ < 780) { red = 1.0; green = 0.0; blue = 0.0; } if (wavelength_ > 380 && wavelength_ <= 420) { factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380); } else if (wavelength_ > 420 && wavelength_ <= 701) { factor = 1.0; } else if (wavelength_ > 701 && wavelength_ <= 780) { factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700); } else { factor = 0.0; } return QColor(Adjust(red, factor), Adjust(green, factor), Adjust(blue, factor)); } int SpectrumWidget::Adjust(double color, double /*factor*/) { if (color == 0.0) { return 0; } else { // return qRound(m_intensityMax * pow(color*factor, m_gamma)); FIXME return m_intensityMax * color; } } void SpectrumWidget::drawTickmarks(QPainter* p) { //the size of the text on the tickmarks const int space = 20; //the distance between the tickmarks in pixel const int d = 10; //the total number of tickmarks to draw (small and long) const int numberOfTickmarks = (int)floor((double)(width() / d)); double pos = 0.0; for (int i = 0; i < numberOfTickmarks; ++i) { if (i % 5 == 0) { //long tickmarks plus text p->drawLine(i * d, m_realHeight, i * d, m_realHeight + 10); if (i % 10 == 0 && i * d > space && i * d < width() - space) { pos = (double)(i * d) / width(); p->fillRect(i * d - space, m_realHeight + 12, 2 * space, 15, Qt::white); p->drawText(i * d - space, m_realHeight + 12, 2 * space, 15, Qt::AlignCenter, QString::number(KalziumUtils::strippedValue(Wavelength(pos)))); } } else { //small tickmarks p->drawLine(i * d, m_realHeight, i * d, m_realHeight + 5); } } } void SpectrumWidget::keyPressEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_Plus: slotZoomIn(); break; case Qt::Key_Minus: slotZoomOut(); break; } } void SpectrumWidget::slotZoomOut() { qDebug() << "SpectrumWidget::slotZoomOut() " << m_startValue << ":: " << m_endValue; double diff = m_endValue - m_startValue; double offset = diff * 0.05; m_endValue = m_endValue + offset; m_startValue = m_startValue - offset; //check for invalid values if (m_startValue < 0.0) { m_startValue = 0.0; } if (m_endValue > 10000.0) { // FIXME: Magic numbers... m_endValue = 40000.0; } setBorders(m_startValue, m_endValue); } void SpectrumWidget::setBorders(double left, double right) { qDebug() << "setBorders " << left << ".." << right; m_startValue = left; m_endValue = right; //round the startValue down and the endValue up emit bordersChanged(int(m_startValue + 0.5), int(m_endValue + 0.5)); update(); } void SpectrumWidget::slotZoomIn() { qDebug() << "SpectrumWidget::slotZoomIn() " << m_startValue << ":: " << m_endValue; double diff = m_endValue - m_startValue; double offset = diff * 0.05; m_endValue = m_endValue - offset; m_startValue = m_startValue + offset; setBorders(m_startValue, m_endValue); } void SpectrumWidget::mouseMoveEvent(QMouseEvent *e) { m_LMBPointCurrent = e->pos(); update(); } void SpectrumWidget::mousePressEvent(QMouseEvent *e) { if (e->button() == Qt::LeftButton) { m_LMBPointPress = e->pos(); } if (e->button() == Qt::RightButton) { resetSpectrum(); } findPeakFromMouseposition(Wavelength((double)e->pos().x() / width())); } void SpectrumWidget::findPeakFromMouseposition(double wavelength) { qDebug() << "SpectrumWidget::findPeakFromMouseposition()"; Spectrum::peak *peak = nullptr; //find the difference in percent (1.0 is 100%, 0.1 is 10%) double dif = 0.0; bool foundWavelength = false; //find the highest intensity foreach (Spectrum::peak *currentPeak, m_spectrum->peaklist()) { double currentWavelength = currentPeak->wavelengthToUnit(Prefs::spectrumWavelengthUnit()); double thisdif = currentWavelength / wavelength; if (thisdif < 0.9 || thisdif > 1.1) { continue; } if (thisdif > 1.0) { //convert for example 1.3 to 0.7 thisdif = thisdif - 1; thisdif = 1 - thisdif; } if (thisdif > dif) { dif = thisdif; peak = currentPeak; foundWavelength = true; } } if (foundWavelength) { emit peakSelected(peak); } } void SpectrumWidget::mouseReleaseEvent(QMouseEvent *e) { if (e->button() == Qt::LeftButton) { int left = (int)Wavelength((double)m_LMBPointPress.x() / width()); int right = (int)Wavelength((double)e->pos().x() / width()); if (left == right) { return; } if (left > right) { setBorders(right, left); } else { setBorders(left, right); } } m_LMBPointPress.setX(-1); m_LMBPointCurrent.setX(-1); } void SpectrumWidget::setSpectrum(Spectrum* spec) { m_spectrum = spec; resetSpectrum(); } void SpectrumWidget::resetSpectrum() { //set the minimum and maximum peak to the min/max wavelength //plus/minus ten. This makes then always visible double minimumPeak = m_spectrum->minPeak(Prefs::spectrumWavelengthUnit()) - 20.0; double maximumPeak = m_spectrum->maxPeak(Prefs::spectrumWavelengthUnit()) + 20.0; setBorders(minimumPeak, maximumPeak); } diff --git a/src/tableinfowidget.h b/src/tableinfowidget.h index dcfeea79..9de0fcc7 100644 --- a/src/tableinfowidget.h +++ b/src/tableinfowidget.h @@ -1,47 +1,47 @@ /*************************************************************************** * Copyright (C) 2007 by Carsten Niehaus * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef TABLEINFOWIDGET_H #define TABLEINFOWIDGET_H -#include +#include #include #include "kalziumschemetype.h" /** * @author Carsten Niehaus */ class TableInfoWidget : public QWidget { Q_OBJECT public: TableInfoWidget(QWidget *parent); ~TableInfoWidget() {} private: QLabel *m_tableType; public slots: void setTableType(int type); }; #endif // TABLEINFOWIDGET_H diff --git a/src/tablesdialog.cpp b/src/tablesdialog.cpp index 87f7040b..8518a90c 100644 --- a/src/tablesdialog.cpp +++ b/src/tablesdialog.cpp @@ -1,279 +1,280 @@ /*************************************************************************** copyright : (C) 2006 by Carsten Niehaus (C) 2007 by Ian Monroe ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "tablesdialog.h" -#include +#include #include #include #include #include #include #include -#include +#include #include #include #include #include #include #include #include #include +#include TablesDialog::TablesDialog(QWidget *parent) : KPageDialog(parent) { setFaceType(List); //setButtons(Help | Close); //setDefaultButton(Close); createGreekSymbolTable(); createNumbersTable(); } void TablesDialog::createGreekSymbolTable() { QWidget *frame = new QWidget(); KPageWidgetItem *item = addPage(frame, i18n("Greek alphabet")); item->setHeader(i18n("Greek alphabet")); item->setIcon(QIcon::fromTheme("numbers")); QVBoxLayout *layout = new QVBoxLayout(frame); layout->setMargin(0); QTableWidget *table = new MyTableWidget(frame); table->verticalHeader()->hide(); table->setColumnCount(3); table->setRowCount(24); table->setHorizontalHeaderLabels(QStringList() << i18n("Uppercase") << i18n("Lowercase") << i18nc("The name of the greek letter in your language. For example 'Alpha' for the first letter. ", "Name")); layout->addWidget(table); table->setItem(0, 0, new MyWidgetItem(QString(QChar(913)))); //capital Alpha table->setItem(1, 0, new MyWidgetItem(QString(QChar(914)))); table->setItem(2, 0, new MyWidgetItem(QString(QChar(915)))); table->setItem(3, 0, new MyWidgetItem(QString(QChar(916)))); table->setItem(4, 0, new MyWidgetItem(QString(QChar(917)))); table->setItem(5, 0, new MyWidgetItem(QString(QChar(918)))); table->setItem(6, 0, new MyWidgetItem(QString(QChar(919)))); table->setItem(7, 0, new MyWidgetItem(QString(QChar(920)))); table->setItem(8, 0, new MyWidgetItem(QString(QChar(921)))); table->setItem(9, 0, new MyWidgetItem(QString(QChar(922)))); table->setItem(10, 0, new MyWidgetItem(QString(QChar(923)))); table->setItem(11, 0, new MyWidgetItem(QString(QChar(924)))); table->setItem(12, 0, new MyWidgetItem(QString(QChar(925)))); table->setItem(13, 0, new MyWidgetItem(QString(QChar(926)))); table->setItem(14, 0, new MyWidgetItem(QString(QChar(927)))); table->setItem(15, 0, new MyWidgetItem(QString(QChar(928)))); table->setItem(16, 0, new MyWidgetItem(QString(QChar(929)))); table->setItem(17, 0, new MyWidgetItem(QString(QChar(931)))); table->setItem(18, 0, new MyWidgetItem(QString(QChar(932)))); table->setItem(19, 0, new MyWidgetItem(QString(QChar(933)))); table->setItem(20, 0, new MyWidgetItem(QString(QChar(934)))); table->setItem(21, 0, new MyWidgetItem(QString(QChar(935)))); table->setItem(22, 0, new MyWidgetItem(QString(QChar(936)))); table->setItem(23, 0, new MyWidgetItem(QString(QChar(937)))); //small letters table->setItem(0, 1, new MyWidgetItem(QString(QChar(945)))); //small alpha table->setItem(1, 1, new MyWidgetItem(QString(QChar(946)))); table->setItem(2, 1, new MyWidgetItem(QString(QChar(947)))); table->setItem(3, 1, new MyWidgetItem(QString(QChar(948)))); table->setItem(4, 1, new MyWidgetItem(QString(QChar(949)))); table->setItem(5, 1, new MyWidgetItem(QString(QChar(950)))); table->setItem(6, 1, new MyWidgetItem(QString(QChar(951)))); table->setItem(7, 1, new MyWidgetItem(QString(QChar(952)))); table->setItem(8, 1, new MyWidgetItem(QString(QChar(953)))); table->setItem(9, 1, new MyWidgetItem(QString(QChar(954)))); table->setItem(10, 1, new MyWidgetItem(QString(QChar(955)))); table->setItem(11, 1, new MyWidgetItem(QString(QChar(956)))); table->setItem(12, 1, new MyWidgetItem(QString(QChar(957)))); table->setItem(13, 1, new MyWidgetItem(QString(QChar(958)))); table->setItem(14, 1, new MyWidgetItem(QString(QChar(959)))); table->setItem(15, 1, new MyWidgetItem(QString(QChar(960)))); table->setItem(16, 1, new MyWidgetItem(QString(QChar(961)))); //there are two greek letters for sigma table->setItem(17, 1, new MyWidgetItem(QString(QChar(962)) + ", " + QString(QChar(963)))); table->setItem(18, 1, new MyWidgetItem(QString(QChar(964)))); table->setItem(19, 1, new MyWidgetItem(QString(QChar(965)))); table->setItem(20, 1, new MyWidgetItem(QString(QChar(966)))); table->setItem(21, 1, new MyWidgetItem(QString(QChar(967)))); table->setItem(22, 1, new MyWidgetItem(QString(QChar(968)))); table->setItem(23, 1, new MyWidgetItem(QString(QChar(969)))); //english names table->setItem(0, 2, new MyWidgetItem(i18n("alpha"))); table->setItem(1, 2, new MyWidgetItem(i18n("beta"))); table->setItem(2, 2, new MyWidgetItem(i18n("gamma"))); table->setItem(3, 2, new MyWidgetItem(i18n("delta"))); table->setItem(4, 2, new MyWidgetItem(i18n("epsilon"))); table->setItem(5, 2, new MyWidgetItem(i18n("zeta"))); table->setItem(6, 2, new MyWidgetItem(i18n("eta"))); table->setItem(7, 2, new MyWidgetItem(i18n("theta"))); table->setItem(8, 2, new MyWidgetItem(i18n("iota"))); table->setItem(9, 2, new MyWidgetItem(i18n("kappa"))); table->setItem(10, 2, new MyWidgetItem(i18n("lambda"))); table->setItem(11, 2, new MyWidgetItem(i18n("mu"))); table->setItem(12, 2, new MyWidgetItem(i18n("nu"))); table->setItem(13, 2, new MyWidgetItem(i18n("xi"))); table->setItem(14, 2, new MyWidgetItem(i18n("omicron"))); table->setItem(15, 2, new MyWidgetItem(i18n("pi"))); table->setItem(16, 2, new MyWidgetItem(i18n("rho"))); table->setItem(17, 2, new MyWidgetItem(i18n("sigma"))); table->setItem(18, 2, new MyWidgetItem(i18n("tau"))); table->setItem(19, 2, new MyWidgetItem(i18n("upsilon"))); table->setItem(20, 2, new MyWidgetItem(i18n("phi"))); table->setItem(21, 2, new MyWidgetItem(i18n("chi"))); table->setItem(22, 2, new MyWidgetItem(i18n("psi"))); table->setItem(23, 2, new MyWidgetItem(i18n("omega"))); table->resizeColumnsToContents(); frame->setMinimumWidth(qMax(table->columnWidth(0) + table->columnWidth(1) + table->columnWidth(2), table->horizontalHeader()->sizeHint().width()) + 25); } void TablesDialog::createNumbersTable() { QWidget *frame = new QWidget(); KPageWidgetItem *item = addPage(frame, i18n("Numbers")); item->setHeader(i18n("Numeric Prefixes and Roman Numerals")); item->setIcon(QIcon::fromTheme("numbers")); QVBoxLayout *layout = new QVBoxLayout(frame); layout->setMargin(0); QTableWidget *table = new MyTableWidget(frame); table->verticalHeader()->hide(); table->setColumnCount(3); table->setRowCount(28); table->setHorizontalHeaderLabels(QStringList() << i18n("Number") << i18nc("For example 'Mono' for 1 and 'Tri' for 3", "Prefix") << i18n("Roman Numerals")); layout->addWidget(table); table->setItem(0, 0, new MyWidgetItem(i18n("0.5"))); table->setItem(1, 0, new MyWidgetItem(i18n("1"))); table->setItem(2, 0, new MyWidgetItem(i18n("1.5"))); table->setItem(3, 0, new MyWidgetItem(i18n("2"))); table->setItem(4, 0, new MyWidgetItem(i18n("2.5"))); table->setItem(5, 0, new MyWidgetItem(i18n("3"))); table->setItem(6, 0, new MyWidgetItem(i18n("4"))); table->setItem(7, 0, new MyWidgetItem(i18n("5"))); table->setItem(8, 0, new MyWidgetItem(i18n("6"))); table->setItem(9, 0, new MyWidgetItem(i18n("7"))); table->setItem(10, 0, new MyWidgetItem(i18n("8"))); table->setItem(11, 0, new MyWidgetItem(i18n("9"))); table->setItem(12, 0, new MyWidgetItem(i18n("10"))); table->setItem(13, 0, new MyWidgetItem(i18n("11"))); table->setItem(14, 0, new MyWidgetItem(i18n("12"))); table->setItem(15, 0, new MyWidgetItem(i18n("13"))); table->setItem(16, 0, new MyWidgetItem(i18n("14"))); table->setItem(17, 0, new MyWidgetItem(i18n("15"))); table->setItem(18, 0, new MyWidgetItem(i18n("16"))); table->setItem(19, 0, new MyWidgetItem(i18n("17"))); table->setItem(20, 0, new MyWidgetItem(i18n("18"))); table->setItem(21, 0, new MyWidgetItem(i18n("19"))); table->setItem(22, 0, new MyWidgetItem(i18n("20"))); table->setItem(23, 0, new MyWidgetItem(i18n("40"))); table->setItem(24, 0, new MyWidgetItem(i18n("50"))); table->setItem(25, 0, new MyWidgetItem(i18n("60"))); table->setItem(26, 0, new MyWidgetItem(i18n("90"))); table->setItem(27, 0, new MyWidgetItem(i18n("100"))); //greek names of the numbers table->setItem(0, 1, new MyWidgetItem("hemi")); table->setItem(1, 1, new MyWidgetItem("mono")); table->setItem(2, 1, new MyWidgetItem("sesqui")); table->setItem(3, 1, new MyWidgetItem("di, bi")); table->setItem(4, 1, new MyWidgetItem("hemipenta")); table->setItem(5, 1, new MyWidgetItem("tri")); table->setItem(6, 1, new MyWidgetItem("tetra")); table->setItem(7, 1, new MyWidgetItem("penta")); table->setItem(8, 1, new MyWidgetItem("hexa")); table->setItem(9, 1, new MyWidgetItem("hepta")); table->setItem(10, 1, new MyWidgetItem("octa")); table->setItem(11, 1, new MyWidgetItem("nona, ennea")); table->setItem(12, 1, new MyWidgetItem("deca")); table->setItem(13, 1, new MyWidgetItem("hendeca, undeca")); table->setItem(14, 1, new MyWidgetItem("dodeca")); table->setItem(15, 1, new MyWidgetItem("trideca")); table->setItem(16, 1, new MyWidgetItem("tetradeca")); table->setItem(17, 1, new MyWidgetItem("pentadeca")); table->setItem(18, 1, new MyWidgetItem("hexadeca")); table->setItem(19, 1, new MyWidgetItem("heptadeca")); table->setItem(20, 1, new MyWidgetItem("octadeca")); table->setItem(21, 1, new MyWidgetItem("nonadeca")); table->setItem(22, 1, new MyWidgetItem("eicosa")); table->setItem(23, 1, new MyWidgetItem("tetraconta")); table->setItem(24, 1, new MyWidgetItem("pentaconta")); table->setItem(25, 1, new MyWidgetItem("hexaconta")); table->setItem(26, 1, new MyWidgetItem("nonaconta")); table->setItem(27, 1, new MyWidgetItem("hecta")); //roman symbols table->setItem(1, 2, new MyWidgetItem("I")); table->setItem(3, 2, new MyWidgetItem("II")); table->setItem(5, 2, new MyWidgetItem("III")); table->setItem(6, 2, new MyWidgetItem("IV")); table->setItem(7, 2, new MyWidgetItem("V")); table->setItem(8, 2, new MyWidgetItem("VI")); table->setItem(9, 2, new MyWidgetItem("VII")); table->setItem(10, 2, new MyWidgetItem("VIII")); table->setItem(11, 2, new MyWidgetItem("IX")); table->setItem(12, 2, new MyWidgetItem("X")); table->setItem(13, 2, new MyWidgetItem("XI")); table->setItem(14, 2, new MyWidgetItem("XII")); table->setItem(15, 2, new MyWidgetItem("XIII")); table->setItem(16, 2, new MyWidgetItem("XIV")); table->setItem(17, 2, new MyWidgetItem("XV")); table->setItem(18, 2, new MyWidgetItem("XVI")); table->setItem(19, 2, new MyWidgetItem("XVII")); table->setItem(20, 2, new MyWidgetItem("XVIII")); table->setItem(21, 2, new MyWidgetItem("XIV")); table->setItem(22, 2, new MyWidgetItem("XX")); table->setItem(23, 2, new MyWidgetItem("XL")); table->setItem(24, 2, new MyWidgetItem("L")); table->setItem(25, 2, new MyWidgetItem("LX")); table->setItem(26, 2, new MyWidgetItem("XC")); table->setItem(27, 2, new MyWidgetItem("C")); table->resizeColumnsToContents(); frame->setMinimumWidth(qMax(table->columnWidth(0) + table->columnWidth(1) + table->columnWidth(2), table->horizontalHeader()->sizeHint().width()) + 25); } TablesDialog::~TablesDialog() { } MyTableWidget::MyTableWidget(QWidget* parent) : QTableWidget(parent) { } void MyTableWidget::contextMenuEvent(QContextMenuEvent* event) { QMenu* menu = new QMenu((QWidget*) sender()); menu->addAction(i18n("&Copy"), this, SLOT(copyToClipboard()), QKeySequence(Qt::Key_C | Qt::CTRL)); menu->exec(event->globalPos()); } void MyTableWidget::copyToClipboard() { QApplication::clipboard()->setText(currentItem()->data(QTableWidgetItem::Type).toString()); } diff --git a/src/tools/moleculeview.cpp b/src/tools/moleculeview.cpp index e8b34f3b..193096b8 100644 --- a/src/tools/moleculeview.cpp +++ b/src/tools/moleculeview.cpp @@ -1,319 +1,336 @@ /*************************************************************************** * Copyright (C) 2006 by Carsten Niehaus * Copyright (C) 2007-2008 by Marcus D. Hanwell * Copyright (C) 2016 by Andreas Cord-Landwehr ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "moleculeview.h" #include #include #include #include #include +#include #include #include -#include -#include +#include + +#include #include -#include #include -#include -#include -#include +#include +#include #include "iowrapper.h" #include #include // This is needed to ensure that the forcefields are set up right with GCC vis #ifdef __KDE_HAVE_GCC_VISIBILITY #define HAVE_GCC_VISIBILITY #endif #include #include +#include +#include +#include +#include +#include +#include using namespace OpenBabel; using namespace Avogadro::QtGui; MoleculeDialog::MoleculeDialog(QWidget * parent) - : KDialog(parent) + : QDialog(parent) , m_path(QString()) , m_periodicTable(nullptr) { // use multi-sample (anti-aliased) OpenGL if available QGLFormat defFormat = QGLFormat::defaultFormat(); defFormat.setSampleBuffers(true); QGLFormat::setDefaultFormat(defFormat); - setCaption(i18n("Molecular Editor")); - setButtons(User3 | User2 | User1 | Close); + setWindowTitle(i18n("Molecular Editor")); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + QPushButton *user1Button = new QPushButton; + buttonBox->addButton(user1Button, QDialogButtonBox::ActionRole); + QPushButton *user2Button = new QPushButton; + buttonBox->addButton(user2Button, QDialogButtonBox::ActionRole); + QPushButton *user3Button = new QPushButton; + buttonBox->addButton(user3Button, QDialogButtonBox::ActionRole); + connect(buttonBox, &QDialogButtonBox::rejected, this, &MoleculeDialog::reject); - setDefaultButton(User1); + user1Button->setDefault(true); - setButtonGuiItem(User1, KGuiItem(i18n("Load Molecule"), "document-open", i18n("Loading a molecule"))); + KGuiItem::assign(user1Button, KGuiItem(i18n("Load Molecule"))); - setButtonGuiItem(User2, KGuiItem(i18n("Download New Molecules"), "get-hot-new-stuff", i18n("Download new molecule files"))); + KGuiItem::assign(user2Button, KGuiItem(i18n("Download New Molecules"))); - setButtonGuiItem(User3, KGuiItem(i18n("Save Molecule"), "document-save", i18n("Saving a molecule"))); + KGuiItem::assign(user3Button, KGuiItem(i18n("Save Molecule"))); - ui.setupUi(mainWidget()); + ui.setupUi(mainWidget); // Attempt to set up the UFF forcefield // m_forceField = OBForceField::FindForceField("UFF"); // if (!m_forceField) { // ui.optimizeButton->setEnabled(false); // } ui.styleCombo->addItems({"Ball and Stick", "Van der Waals", "Wireframe"}); connect(ui.styleCombo, static_cast(&QComboBox::currentIndexChanged), this, &MoleculeDialog::slotUpdateScenePlugin); slotUpdateScenePlugin(); connect(ui.tabWidget, &QTabWidget::currentChanged, this, &MoleculeDialog::setViewEdit); // Editing parameters // commented out until we find new API for pumbling to OpenBabel // connect(ui.optimizeButton, &QPushButton::clicked, // this, &MoleculeDialog::slotGeometryOptimize); connect(ui.clearDrawingButton, &QPushButton::clicked, this, &MoleculeDialog::clearAllElementsInEditor); connect(ui.glWidget->molecule(), &Avogadro::QtGui::Molecule::changed, this, &MoleculeDialog::slotUpdateStatistics); - connect(this, &KDialog::user1Clicked, + connect(user1Button, &QPushButton::clicked, this, &MoleculeDialog::slotLoadMolecule); - connect(this, &KDialog::user2Clicked, + connect(user2Button, &QPushButton::clicked, this, &MoleculeDialog::slotDownloadNewStuff); - connect(this, &KDialog::user3Clicked, + connect(user3Button, &QPushButton::clicked, this, &MoleculeDialog::slotSaveMolecule); + mainLayout->addWidget(buttonBox); + + // Check that we have managed to load up some tools and engines int nTools = ui.glWidget->tools().size(); if (!nTools) { QString error = i18n("No tools loaded - it is likely that the Avogadro plugins could not be located."); KMessageBox::error(this, error, i18n("Kalzium")); } // objectName is also used in Avogadro2 for identifying tools foreach (auto *tool, ui.glWidget->tools()) { if (tool->objectName() == "Editor") { ui.editTabLayout->insertWidget(0, tool->toolWidget()); break; } } } void MoleculeDialog::slotLoadMolecule() { // Check that we have managed to load up some tools and engines int nTools = ui.glWidget->tools().size(); if (!nTools) { QString error = i18n("No tools loaded - it is likely that the Avogadro plugins could not be located. " "No molecules can be viewed until this issue is resolved."); KMessageBox::information(this, error); } m_path = QStandardPaths::locate(QStandardPaths::DataLocation, "data/molecules/", QStandardPaths::LocateDirectory); QString commonMoleculeFormats = i18n("Common molecule formats"); QString allFiles = i18n("All files"); - QString filename = KFileDialog::getOpenFileName( - QUrl::fromLocalFile(m_path), - "*.cml *.xyz *.ent *.pdb *.alc *.chm *.cdx *.cdxml *.c3d1 *.c3d2" + QString filename = QFileDialog::getOpenFileName( + this, + i18n("Choose a file to open"), + m_path, + commonMoleculeFormats + "(*.cml *.xyz *.ent *.pdb *.alc *.chm *.cdx *.cdxml *.c3d1 *.c3d2" " *.gpr *.mdl *.mol *.sdf *.sd *.crk3d *.cht *.dmol *.bgf" " *.gam *.inp *.gamin *.gamout *.tmol *.fract" - " *.mpd *.mol2|" + commonMoleculeFormats + "\n" - "* *.*|" + allFiles, - this, - i18n("Choose a file to open")); + " *.mpd *.mol2);;" + allFiles + "(*.*)"); loadMolecule(filename); } void MoleculeDialog::slotUpdateScenePlugin() { const QString text = ui.styleCombo->currentText(); for (int i = 0; i < ui.glWidget->sceneModel().rowCount(QModelIndex()); ++i) { QModelIndex index = ui.glWidget->sceneModel().index(i, 0); if (text == ui.glWidget->sceneModel().data(index, Qt::DisplayRole)) { ui.glWidget->sceneModel().setData(index, Qt::Checked, Qt::CheckStateRole); } else { ui.glWidget->sceneModel().setData(index, Qt::Unchecked, Qt::CheckStateRole); } } } void MoleculeDialog::loadMolecule(const QString &filename) { if (filename.isEmpty()) { return; } // 1. workaround for missing copy-constructor: fixed in Avogadro2 > 0.9 // 2. another workaround for broken copy-constructor that does not // initialize the m_undoMolecule private member variable; // this molecule should be created on the heap instead of the stack m_molecule = *IoWrapper::readMolecule(filename); if (m_molecule.atomCount() != 0) { disconnect(ui.glWidget->molecule(), 0, this, 0); ui.glWidget->setMolecule(&m_molecule); ui.glWidget->update(); slotUpdateStatistics(); connect(&m_molecule, &Avogadro::QtGui::Molecule::changed, this, &MoleculeDialog::slotUpdateStatistics); } ui.glWidget->resetCamera(); ui.glWidget->updateScene(); } void MoleculeDialog::clearAllElementsInEditor() { ui.glWidget->molecule()->clearBonds(); ui.glWidget->molecule()->clearAtoms(); ui.glWidget->updateScene(); } void MoleculeDialog::slotSaveMolecule() { QString commonMoleculeFormats = i18n("Common molecule formats"); QString allFiles = i18n("All files"); - QString filename = KFileDialog::getSaveFileName(QUrl(), - "*.cml *.xyz *.ent *.pdb *.alc *.chm *.cdx *.cdxml *.c3d1 *.c3d2" + QString filename = QFileDialog::getSaveFileName(this, i18n("Choose a file to save to"), QString(), + commonMoleculeFormats + " (*.cml *.xyz *.ent *.pdb *.alc *.chm *.cdx *.cdxml *.c3d1 *.c3d2" " *.gpr *.mdl *.mol *.sdf *.sd *.crk3d *.cht *.dmol *.bgf" " *.gam *.inp *.gamin *.gamout *.tmol *.fract" - " *.mpd *.mol2|" + commonMoleculeFormats + "\n" - "* *.*|" + allFiles, - this, - i18n("Choose a file to save to")); + " *.mpd *.mol2);;" + allFiles + " (*.*)" + ); if (!filename.contains('.')) { filename.append(".cml"); } IoWrapper io; io.writeMolecule(filename, ui.glWidget->molecule()); } void MoleculeDialog::setViewEdit(int mode) { if (mode == 0) { ui.glWidget->setActiveTool("Navigator"); } else if (mode == 1) { ui.glWidget->setActiveTool("Editor"); } else if (mode == 2) { ui.glWidget->setActiveTool("MeasureTool"); } } MoleculeDialog::~MoleculeDialog() { } void MoleculeDialog::slotUpdateStatistics() { Molecule* mol = ui.glWidget->molecule(); if (!mol) { return; } const std::string name = mol->data(QString("name").toStdString()).toString(); ui.nameLabel->setText(QString::fromStdString(name)); ui.weightLabel->setText(i18nc("This 'u' stands for the chemical unit (u for 'units'). Most likely this does not need to be translated at all!", "%1 u", mol->mass())); ui.formulaLabel->setText(IoWrapper::getPrettyFormula(mol)); ui.glWidget->update(); } void MoleculeDialog::slotDownloadNewStuff() { qDebug() << "Kalzium new stuff"; KNS3::DownloadDialog dialog(this); dialog.exec(); // list of changed entries QString destinationDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); QDir dir(destinationDir); if (!dir.exists()) { destinationDir = QDir::homePath(); } bool anyError = false; bool anySuccess = false; bool moreOneInstalledFile = false; QString exactlyOneFile; foreach (const KNS3::Entry& entry, dialog.changedEntries()) { // care only about installed ones if (entry.status() == KNS3::Entry::Installed) { qDebug() << "Changed Entry: " << entry.installedFiles(); foreach (const QString &origFile, entry.installedFiles()) { const QString destFile = destinationDir + '/' + QFileInfo(origFile).fileName(); KJob *job = KIO::file_move(QUrl::fromLocalFile(origFile), QUrl::fromLocalFile(destFile));; const bool success = job->exec(); if (success) { if (exactlyOneFile.isEmpty()) { exactlyOneFile = destFile; } else { moreOneInstalledFile = true; } anySuccess = true; } else { KMessageBox::error(this, i18n("Failed to download molecule %1 to %2.", entry.name(), destFile)); anyError = true; } } } } if (anySuccess) { if (anyError) { KMessageBox::information(this, i18n("The molecules that could be downloaded have been saved to %1.", destinationDir)); } else { KMessageBox::information(this, i18n("The molecules have been saved to %1.", destinationDir)); } if (!moreOneInstalledFile) { loadMolecule(exactlyOneFile); } } } //TODO there is currently no API to perform the necessary OpenBabel-Avogadro // conversions, after the migration to Avogadro2; at least with v0.9 void MoleculeDialog::slotGeometryOptimize() { // // Perform a geometry optimization // if (!m_forceField) { // return; // } // // Molecule* molecule = ui.glWidget->molecule(); // OpenBabel::OBMol obmol;//(molecule->OBMol()); // // // Warn the user if the force field cannot be set up for the molecule // if (!m_forceField->Setup(obmol)) { // KMessageBox::error(this, // i18n("Could not set up force field for this molecule"), // i18n("Kalzium")); // return; // } // // // Reasonable default values for most users // m_forceField->SteepestDescentInitialize(500, 1.0e-5); // // Provide some feedback as the optimization runs // while (m_forceField->SteepestDescentTakeNSteps(5)) { // m_forceField->UpdateCoordinates(obmol); // molecule->setOBMol(&obmol); // molecule->update(); // } } diff --git a/src/tools/moleculeview.h b/src/tools/moleculeview.h index 9b29ab45..da7c5bf6 100644 --- a/src/tools/moleculeview.h +++ b/src/tools/moleculeview.h @@ -1,103 +1,103 @@ /*************************************************************************** * Copyright (C) 2006 by Carsten Niehaus * Copyright (C) 2007-2008 by Marcus D. Hanwell ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef MOLECULEVIEW_H #define MOLECULEVIEW_H -#include +#include #include #include "ui_moleculeviewerwidget.h" namespace OpenBabel { class OBForceField; } namespace Avogadro { namespace QtGui { class PeriodicTableView; } } class QSettings; /** * @author Carsten Niehaus */ -class MoleculeDialog : public KDialog +class MoleculeDialog : public QDialog { Q_OBJECT public: MoleculeDialog(QWidget * parent); ~MoleculeDialog(); void loadMolecule(const QString &filename); private: QString m_path;///to store the path were the molecules are located QList m_elementsIndex; // Index storing the element combo index Avogadro::QtGui::PeriodicTableView *m_periodicTable; OpenBabel::OBForceField* m_forceField; QSettings *m_drawSettings; Ui::moleculeViewerForm ui; private slots: /** * Load a molecule */ void slotLoadMolecule(); /** * Update the currently active scene plugin. */ void slotUpdateScenePlugin(); /** * Get a new molecule using hot new stuff */ void slotDownloadNewStuff(); /** * Save a molecule */ void slotSaveMolecule(); /** * Set view/edit mode */ void setViewEdit(int mode); /** * Update the statistical information about the current molecule */ void slotUpdateStatistics(); /** * Geometry optimization */ void slotGeometryOptimize(); /// Clears the view void clearAllElementsInEditor(); private: // workaround for broken copy-operator of QtGui::Molecule // whould be removed after next Avogadro release greater 0.9 Avogadro::QtGui::Molecule m_molecule; }; #endif // MOLECULEVIEW_H diff --git a/src/tools/obconverter.cpp b/src/tools/obconverter.cpp index 69d996b1..d2f7a967 100644 --- a/src/tools/obconverter.cpp +++ b/src/tools/obconverter.cpp @@ -1,249 +1,263 @@ /*************************************************************************** * Copyright (C) 2007, 2008 by Carsten Niehaus * * Copyright (C) 2006 by Georges Khaznadar * * Copyright (C) 2006, 2007 by Jerome Pansanel * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "obconverter.h" // Qt includes -#include -#include -#include +#include +#include #include -#include +#include +#include +#include #include - +#include +#include +#include // KDE includes -#include -#include -#include +#include +#include +#include #include -#include -#include -#include +#include using namespace std; using namespace OpenBabel; KOpenBabel::KOpenBabel(QWidget *parent) - : KDialog(parent) + : QDialog(parent) { - setCaption(i18n("OpenBabel Frontend")); - setButtons(Help | User1| Close); - setDefaultButton(User1); + setWindowTitle(i18n("OpenBabel Frontend")); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Close); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + QPushButton *user1Button = new QPushButton; + buttonBox->addButton(user1Button, QDialogButtonBox::ActionRole); + connect(buttonBox, &QDialogButtonBox::rejected, this, &KOpenBabel::reject); + connect(user1Button, &QPushButton::clicked, this, &KOpenBabel::slotConvert); + connect(buttonBox, &QDialogButtonBox::helpRequested, this, &KOpenBabel::slotHelpRequested); + + user1Button->setDefault(true); OBConvObject = new OBConversion(); - ui.setupUi(mainWidget()); + ui.setupUi(mainWidget); - setButtonGuiItem(User1, KGuiItem(i18n("Convert"), "edit-copy", i18n("Convert selected files"))); + KGuiItem::assign(user1Button, KGuiItem(i18n("Convert"))); + mainLayout->addWidget(buttonBox); setupWindow(); - setHelp(QString(), "kalzium"); } KOpenBabel::~KOpenBabel() { delete OBConvObject; OBConvObject = NULL; } void KOpenBabel::setupWindow() { // Set multiple selection possible ui.FileListView->setSelectionMode(QAbstractItemView::SelectionMode(3)); // Creating the main layout QStringList InputType; vector InputFormat = OBConvObject->GetSupportedInputFormat(); for (vector::iterator it = InputFormat.begin(); it!=InputFormat.end(); ++it) { InputType << QString((*it).c_str()); } ui.InputTypeComboBox->addItems(InputType); QStringList OutputType; vector OutputFormat = OBConvObject->GetSupportedOutputFormat(); for (vector::iterator it = OutputFormat.begin(); it!=OutputFormat.end(); ++it) { OutputType << QString((*it).c_str()); } ui.OutputTypeComboBox->addItems(OutputType); // Create connection connect(ui.addFileButton, SIGNAL(clicked()), SLOT(slotAddFile())); connect(ui.deleteFileButton, SIGNAL(clicked()), SLOT(slotDeleteFile())); connect(ui.selectAllFileButton, SIGNAL(clicked()), SLOT(slotSelectAll())); - connect(this, - SIGNAL(user1Clicked()), SLOT(slotConvert())); - connect(ui.FileListView, SIGNAL(itemSelectionChanged()), SLOT(slotGuessInput())); } void KOpenBabel::slotAddFile() { QStringList InputType; vector InputFormat = OBConvObject->GetSupportedInputFormat(); for (vector::iterator it = InputFormat.begin(); it!=InputFormat.end(); ++it) { InputType << QString((*it).c_str()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // InputType is now something like this: // // "acr -- ACR format [Read-only]", "alc -- Alchemy format", "arc -- Accelrys/MSI Biosym/Insight II CAR format [Read-only]" // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// QStringList tmpList = InputType; tmpList.replaceInStrings(QRegExp("^"), "*."); - tmpList.replaceInStrings(QRegExp(" -- "), "|"); - tmpList.replaceInStrings(QRegExp("/"), "\\/"); //escape all '/' (because of MimeTypes) + tmpList.replaceInStrings(QRegExp("(.*) -- (.*)"), "\\2(\\1)"); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // tmpList is now something like this: // - // "*.acr|ACR format [Read-only]", "*.alc|Alchemy format" // + // "ACR format [Read-only] (*.acr)", "Alchemy format (*.alc)" // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - QList fl = KFileDialog::getOpenUrls( + QList fl = QFileDialog::getOpenFileUrls( + this, + i18n("Open Molecule File"), QUrl(), - "*|" +i18n("All Files") + '\n' + tmpList.join("\n") //add all possible extensions like "*.cml *.mol" + i18n("All Files") + "(*.*);;" + tmpList.join(";;") //add all possible extensions like "*.cml *.mol" ); foreach (const QUrl &u , fl) { new QListWidgetItem(u.toDisplayString(), ui.FileListView); } } void KOpenBabel::slotSelectAll() { ui.FileListView->selectAll(); } void KOpenBabel::slotDeleteFile() { QList p = ui.FileListView->selectedItems(); foreach (QListWidgetItem *item, p) { delete item; } } void KOpenBabel::slotGuessInput() { QList p = ui.FileListView->selectedItems(); bool first = true; QString suffix; if (p.count()) { foreach (QListWidgetItem * item, p) { if (first) { first = false; suffix = item->text().remove(QRegExp("^.*\\.")); } else { if (item->text().remove(QRegExp("^.*\\.")) == suffix) { continue; } else { // All the file types are not same, set type to default ui.InputTypeComboBox->setCurrentIndex(0); return; } } } } for (int i = 0; i < ui.InputTypeComboBox->count(); ++i) { if (ui.InputTypeComboBox->itemText(i).indexOf(QRegExp('^' + suffix + " --")) >= 0) { ui.InputTypeComboBox->setCurrentIndex(i); return; } } // The suffix has not been found, set type to default ui.InputTypeComboBox->setCurrentIndex(0); } void KOpenBabel::slotConvert() { QString iformat = ui.InputTypeComboBox->currentText(); QString oformat = ui.OutputTypeComboBox->currentText(); iformat = iformat.remove(QRegExp(" --.*")); oformat = oformat.remove(QRegExp(" --.*")); QList p = ui.FileListView->selectedItems(); if (p.count() == 0) { KMessageBox::error(this, i18n("You must select some files first."), i18n("No files selected") ); return; } QListIterator it(p); QStringList cmdList; // Full command QLinkedList cmdArgList; // Arguments only foreach (QListWidgetItem * item, p) { QString ifname = QUrl(item->text()).toLocalFile(); QString ofname = ifname; ofname = ofname.remove(QRegExp("\\.([^\\.]*$)")); ofname = ofname + QLatin1String(".") + oformat; bool proceed = true; if (QFile::exists(ofname)) { //something named ofname already exists switch (KMessageBox::warningContinueCancel( this, i18n("The file %1 already exists. Do you want to overwrite if possible?", ofname), i18n("The File %1 Already Exists -- KOpenBabel", ofname) ) ) { case KMessageBox::No: proceed = false; break; default: break; } } if (proceed) { QStringList arguments; arguments << QString("-i") + iformat << ifname << QString("-o") + oformat << ofname; cmdArgList.append(arguments); cmdList.append(QString("babel ") + arguments.join(" ")); } } if (cmdArgList.count() > 0) { switch (KMessageBox::questionYesNo( this, cmdList.join("\n"), i18n("Is it okay to run these commands? -- KOpenBabel") ) ) { case KMessageBox::Yes: foreach (const QStringList &s, cmdArgList) { QProcess::startDetached("babel", s); } break; default: break; } } } +void KOpenBabel::slotHelpRequested() +{ + KHelpClient::invokeHelp("kalzium-mainwindow", "kalzium"); +} + void KOpenBabel::addFile(const QString &filename) { ui.FileListView->addItem(filename); } diff --git a/src/tools/obconverter.h b/src/tools/obconverter.h index f8ee5a7c..64e7ebd8 100644 --- a/src/tools/obconverter.h +++ b/src/tools/obconverter.h @@ -1,98 +1,103 @@ /*************************************************************************** * Copyright (C) 2007 by Carsten Niehaus * * Copyright (C) 2006 by Jerome Pansanel * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef OBCONVERTER_H #define OBCONVERTER_H #include "ui_obconverterwidget.h" // OpenBabel includes #include -#include +#include class QDialog; /** * @author Carsten Niehaus * @author Jerome Pansanel */ -class KOpenBabel : public KDialog +class KOpenBabel : public QDialog { Q_OBJECT public: /** * public constructor * * @param parent the parent widget */ KOpenBabel(QWidget *parent); /** * Destructor */ virtual ~KOpenBabel(); /** * Add file to the list */ void addFile(const QString &filename); private: Ui::OBConverterWidget ui; OpenBabel::OBConversion *OBConvObject; QString File; /** * Setup the interface for the window */ void setupWindow(); private slots: /** * Add file to the list */ void slotAddFile(); /** * Select every file in the list */ void slotSelectAll(); /** * Delete file from the list */ void slotDeleteFile(); /** * Try to guess the input file type from the selection */ void slotGuessInput(); /** * Convert the file in the selected type */ void slotConvert(); + /** + * Open help page + */ + void slotHelpRequested(); + }; #endif // OBCONVERTER_H