diff --git a/.arcconfig b/.arcconfig index 377c7ecb..9b28d2ae 100644 --- a/.arcconfig +++ b/.arcconfig @@ -1,3 +1,3 @@ { - "phabricator.uri" : "https://phabricator.kde.org/" -} + "phabricator.uri" : "https://phabricator.kde.org/source/kalzium/" +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..10e5c224 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +CMakeLists.txt.user +.directory +.gitignore diff --git a/compoundviewer/kalziumglwidget.cpp b/compoundviewer/kalziumglwidget.cpp index 12cde41b..065d8c33 100644 --- a/compoundviewer/kalziumglwidget.cpp +++ b/compoundviewer/kalziumglwidget.cpp @@ -1,112 +1,112 @@ /*************************************************************************** * 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 "kalziumglwidget.h" #include "iowrapper.h" #include #include #include #include #include #include #include #include #include #include KalziumGLWidget::KalziumGLWidget(QWidget *parent) : Avogadro::QtOpenGL::GLWidget(parent) { // work around a bug in OpenBabel: the chemical data files parsing // is dependent on the LC_NUMERIC locale. - m_lc_numeric = QByteArray(setlocale(LC_NUMERIC, 0)); + m_lc_numeric = QByteArray(setlocale(LC_NUMERIC, nullptr)); setlocale(LC_NUMERIC, "C"); // Prevent What's this from intercepting right mouse clicks setContextMenuPolicy(Qt::PreventContextMenu); // Load the tools and set navigate as the default // first set the Avogadro plugin directory, // avoiding overwriting an already set envvar static bool s_pluginDirSet = false; if (!s_pluginDirSet) { if (qgetenv("AVOGADRO_PLUGINS").isEmpty()) { qputenv("AVOGADRO_PLUGINS", AVOGADRO_PLUGIN_DIR); } s_pluginDirSet = true; } Avogadro::QtPlugins::PluginManager *manager = Avogadro::QtPlugins::PluginManager::instance(); manager->load(); // load render engines QList scenePluginFactories = manager->pluginFactories(); foreach (auto *factory, scenePluginFactories) { auto *scenePlugin = factory->createInstance(); // enable Ball-and-Sticks if (scenePlugin->objectName() == "BallStick") { scenePlugin->setEnabled(true); } sceneModel().addItem(scenePlugin); } // load tools if (!tools().isEmpty()) { qCritical() << "Updating non-empty toolset, erasing first."; qDeleteAll(tools()); } auto toolPluginFactories = manager->pluginFactories(); foreach (auto *factory, toolPluginFactories) { auto *tool = factory->createInstance(); if (tool) { addTool(tool); if (factory->identifier() == QStringLiteral("Navigator")) { setDefaultTool(tool); setActiveTool(tool); } } } setMolecule(new Avogadro::QtGui::Molecule(this)); update(); } KalziumGLWidget::~KalziumGLWidget() { //restore the LC_NUMERIC locale. setlocale(LC_NUMERIC, m_lc_numeric.constData()); } bool KalziumGLWidget::openFile(const QString &file) { // workaround for missing copy-constructor: fixed in Avogadra2 > 0.9 Avogadro::QtGui::Molecule temp; temp = *IoWrapper::readMolecule(file); auto mol = new Avogadro::QtGui::Molecule(temp); if (!mol) { return false; } Avogadro::QtGui::Molecule* oldmol = molecule(); if (oldmol) { oldmol->deleteLater(); } setMolecule(mol); update(); return true; } diff --git a/libscience/elementparser.cpp b/libscience/elementparser.cpp index 41257787..6d1d4c49 100644 --- a/libscience/elementparser.cpp +++ b/libscience/elementparser.cpp @@ -1,372 +1,372 @@ /*************************************************************************** copyright : (C) 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 "elementparser.h" #include "chemicaldataobject.h" #include #include "element.h" #include #include class ElementSaxParser::Private { public: Private() : currentUnit(KUnitConversion::NoUnit), - currentElement(0), + currentElement(nullptr), inElement(false), inName(false), inMass(false), inExactMass(false), inAtomicNumber(false), inSymbol(false), inIonization(false), inElectronAffinity(false), inElectronegativityPauling(false), inRadiusCovalent(false), inRadiusVDW(false), inBoilingPoint(false), inMeltingPoint(false), inPeriodTableBlock(false), inNameOrigin(false), inDiscoveryDate(false), inDiscoverers(false), inPeriod(false), inCrystalstructure(false), inAcidicbehaviour(false), inFamily(false), inGroup(false), inElectronicconfiguration(false), inDangerSymbol(false), inRPhrase(false), inSPhrase(false), inCountry(false), inOxidation(false) {} ~Private() { delete currentElement; //qDeleteAll(elements); } ChemicalDataObject currentDataObject; int currentUnit; // KUnitConversion::UnitId Element *currentElement; QList elements; bool inElement; bool inName; bool inMass; bool inExactMass; bool inAtomicNumber; bool inSymbol; bool inIonization; bool inElectronAffinity; bool inElectronegativityPauling; bool inRadiusCovalent; bool inRadiusVDW; bool inBoilingPoint; bool inMeltingPoint; bool inPeriodTableBlock; bool inNameOrigin; bool inDiscoveryDate; bool inDiscoverers; bool inPeriod; bool inCrystalstructure; bool inAcidicbehaviour; bool inFamily; bool inGroup; bool inElectronicconfiguration; bool inDangerSymbol; bool inRPhrase; bool inSPhrase; bool inCountry; bool inOxidation; }; ElementSaxParser::ElementSaxParser() : QXmlDefaultHandler(), d(new Private) { } ElementSaxParser::~ElementSaxParser() { delete d; } bool ElementSaxParser::startElement(const QString&, const QString &localName, const QString&, const QXmlAttributes &attrs) { if (localName == "atom") { d->currentElement = new Element(); d->inElement = true; } else if ((d->inElement && localName == "scalar") || localName == "array") { for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "units") { // qDebug() << "value of the unit: " << attrs.value(i); d->currentUnit = unit(attrs.value(i)); // qDebug() << "Took " << d->currentUnit; continue; } if (attrs.value(i) == "bo:atomicNumber") { d->inAtomicNumber = true; } else if (attrs.value(i) == "bo:mass") { d->inMass = true; } else if (attrs.value(i) == "bo:exactMass") { d->inExactMass = true; } else if (attrs.value(i) == "bo:ionization") { d->inIonization = true; } else if (attrs.value(i) == "bo:electronAffinity") { d->inElectronAffinity = true; } else if (attrs.value(i) == "bo:electronegativityPauling") { d->inElectronegativityPauling = true; } else if (attrs.value(i) == "bo:radiusCovalent") { d->inRadiusCovalent = true; } else if (attrs.value(i) == "bo:radiusVDW") { d->inRadiusVDW = true; } else if (attrs.value(i) == "bo:meltingpoint") { d->inMeltingPoint = true; } else if (attrs.value(i) == "bo:boilingpoint") { d->inBoilingPoint = true; } else if (attrs.value(i) == "bo:periodTableBlock") { d->inPeriodTableBlock = true; } else if (attrs.value(i) == "bo:nameOrigin") { d->inNameOrigin = true; } else if (attrs.value(i) == "bo:discoveryDate") { d->inDiscoveryDate = true; } else if (attrs.value(i) == "bo:discoverers") { d->inDiscoverers = true; } else if (attrs.value(i) == "bo:discoveryCountry") { d->inCountry = true; } else if (attrs.value(i) == "bo:period") { d->inPeriod = true; } else if (attrs.value(i) == "bo:crystalstructure") { d->inCrystalstructure = true; } else if (attrs.value(i) == "bo:acidicbehaviour") { d->inAcidicbehaviour = true; } else if (attrs.value(i) == "bo:family") { d->inFamily = true; } else if (attrs.value(i) == "bo:group") { d->inGroup = true; } else if (attrs.value(i) == "bo:electronicConfiguration") { d->inElectronicconfiguration = true; } else if (attrs.value(i) == "bo:dangerSymbol") { d->inDangerSymbol = true; } else if (attrs.value(i) == "bo:RPhrase") { d->inRPhrase = true; } else if (attrs.value(i) == "bo:SPhrase") { d->inSPhrase = true; } else if (attrs.value(i) == "bo:oxidation") { d->inOxidation = true; } } } else if (d->inElement && localName == "label") { for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) != "dictRef") { continue; } if (attrs.value(i) == "bo:symbol") { for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "value") { d->currentDataObject.setData(attrs.value(i)); d->currentDataObject.setType(ChemicalDataObject::symbol); if (d->currentElement) { d->currentElement->addData(d->currentDataObject); } } } } else if (attrs.value(i) == "bo:name") { for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "value") { d->currentDataObject.setData(i18n(attrs.value(i).toUtf8())); d->currentDataObject.setType(ChemicalDataObject::name); if (d->currentElement) { d->currentElement->addData(d->currentDataObject); } } } } } } return true; } bool ElementSaxParser::endElement(const QString &, const QString &localName, const QString &) { if (localName == "atom") { if (d->currentElement->dataAsString(ChemicalDataObject::symbol) != "Xx") { d->elements.append(d->currentElement); } else { delete d->currentElement; } - d->currentElement = 0; + d->currentElement = nullptr; d->inElement = false; } else if (localName == "scalar" || localName == "label" || localName == "array") { d->currentDataObject.setUnit(d->currentUnit); } return true; } bool ElementSaxParser::characters(const QString &ch) { d->currentDataObject = ChemicalDataObject(); ChemicalDataObject::BlueObelisk type; QVariant value; if (d->inMass) { value = ch.toDouble(); type = ChemicalDataObject::mass; d->inMass = false; } else if (d->inExactMass) { value = ch.toDouble(); type = ChemicalDataObject::exactMass; d->inExactMass = false; } else if (d->inAtomicNumber) { value = ch.toInt(); type = ChemicalDataObject::atomicNumber; d->inAtomicNumber = false; } else if (d->inIonization) { value = ch.toDouble();; type = ChemicalDataObject::ionization; d->inIonization = false; } else if (d->inElectronAffinity) { value = ch.toDouble(); type = ChemicalDataObject::electronAffinity; d->inElectronAffinity = false; } else if (d->inElectronegativityPauling) { value = ch.toDouble(); type = ChemicalDataObject::electronegativityPauling; d->inElectronegativityPauling = false; } else if (d->inRadiusCovalent) { value = ch.toDouble(); type = ChemicalDataObject::radiusCovalent; d->inRadiusCovalent = false; } else if (d->inRadiusVDW) { value = ch.toDouble(); type = ChemicalDataObject::radiusVDW; d->inRadiusVDW = false; } else if (d->inMeltingPoint) { value = ch.toDouble(); type = ChemicalDataObject::meltingpoint; d->inMeltingPoint = false; } else if (d->inBoilingPoint) { value = ch.toDouble(); type = ChemicalDataObject::boilingpoint; d->inBoilingPoint = false; } else if (d->inPeriodTableBlock) { value = ch; type = ChemicalDataObject::periodTableBlock; d->inPeriodTableBlock = false; } else if (d->inNameOrigin) { value = i18n(ch.toUtf8()); type = ChemicalDataObject::nameOrigin; d->inNameOrigin = false; } else if (d->inDiscoveryDate) { value = ch.toInt(); type = ChemicalDataObject::date; d->inDiscoveryDate = false; } else if (d->inDiscoverers) { value = ch; type = ChemicalDataObject::discoverers; d->inDiscoverers = false; } else if (d->inPeriod) { value = ch.toInt(); type = ChemicalDataObject::period; d->inPeriod = false; } else if (d->inCrystalstructure) { value = ch; type = ChemicalDataObject::crystalstructure; d->inCrystalstructure = false; } else if (d->inAcidicbehaviour) { value = ch.toInt(); type = ChemicalDataObject::acidicbehaviour; d->inAcidicbehaviour = false; } else if (d->inFamily) { value = ch; type = ChemicalDataObject::family; d->inFamily = false; } else if (d->inGroup) { value = ch.toInt(); type = ChemicalDataObject::group; d->inGroup = false; } else if (d->inElectronicconfiguration) { value = ch; type = ChemicalDataObject::electronicConfiguration; d->inElectronicconfiguration = false; } else if (d->inDangerSymbol) { value = ch; type = ChemicalDataObject::dangerSymbol; d->inDangerSymbol = false; } else if (d->inRPhrase) { value = ch; type = ChemicalDataObject::RPhrase; d->inRPhrase = false; } else if (d->inSPhrase) { value = ch; type = ChemicalDataObject::SPhrase; d->inSPhrase = false; } else if (d->inCountry) { if (ch == "ancient") { value = 0; type = ChemicalDataObject::date; } else { value = ch; type = ChemicalDataObject::discoveryCountry; } d->inCountry = false; } else if (d->inOxidation) { value = ch; type = ChemicalDataObject::oxidation; d->inOxidation = false; } else { //it is a non known value. Do not create a wrong object but return return true; } d->currentDataObject.setData(value); d->currentDataObject.setType(type); d->currentDataObject.setUnit(d->currentUnit); if (d->currentElement) { d->currentElement->addData(d->currentDataObject); } return true; } int ElementSaxParser::unit(const QString& unit) const { if (unit == "siUnits:kelvin") { return KUnitConversion::Kelvin; } else if (unit == "units:ev") { return KUnitConversion::Electronvolt; } else if (unit == "units:ang") { return KUnitConversion::Angstrom; } else if (unit == "bo:noUnit") { return KUnitConversion::NoUnit; } else { return KUnitConversion::NoUnit; } } QList ElementSaxParser::getElements() { return d->elements; } diff --git a/libscience/isotopeparser.cpp b/libscience/isotopeparser.cpp index 0e646c12..0cc451ab 100644 --- a/libscience/isotopeparser.cpp +++ b/libscience/isotopeparser.cpp @@ -1,261 +1,261 @@ /*************************************************************************** copyright : (C) 2005-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. * * * ***************************************************************************/ #include "isotopeparser.h" #include "chemicaldataobject.h" #include "isotope.h" #include #include class IsotopeParser::Private { public: Private() : currentUnit(KUnitConversion::NoUnit), currentErrorValue(QVariant()), currentElementSymbol(QString()), - currentIsotope(0), + currentIsotope(nullptr), inIsotope(false), inElement(false), inAtomicNumber(false), inExactMass(false), inSpin(false), inMagMoment(false), inHalfLife(false), inAlphaDecayLikeliness(false), inAlphaDecay(false), inBetaplusDecayLikeliness(false), inBetaplusDecay(false), inBetaminusDecayLikeliness(false), inBetaminusDecay(false), inECDecayLikeliness(false), inECDecay(false), inAbundance(false) { } ~Private() { delete currentIsotope; //qDeleteAll(isotopes); } ChemicalDataObject currentDataObject; int currentUnit; QVariant currentErrorValue; QString currentElementSymbol; Isotope* currentIsotope; QList isotopes; bool inIsotope; bool inElement; bool inAtomicNumber; bool inExactMass; bool inSpin; bool inMagMoment; bool inHalfLife; bool inAlphaDecayLikeliness; bool inAlphaDecay; bool inBetaplusDecayLikeliness; bool inBetaplusDecay; bool inBetaminusDecayLikeliness; bool inBetaminusDecay; bool inECDecayLikeliness; bool inECDecay; bool inAbundance; }; IsotopeParser::IsotopeParser() : QXmlDefaultHandler(), d(new Private) { } IsotopeParser::~IsotopeParser() { delete d; } bool IsotopeParser::startElement(const QString&, const QString &localName, const QString&, const QXmlAttributes &attrs) { if (localName == "isotopeList") { d->inElement = true; //now save the symbol of the current element for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "id") { d->currentElementSymbol = attrs.value(i); } } } else if (d->inElement && localName == "isotope") { d->currentIsotope = new Isotope(); d->currentIsotope->addData(ChemicalDataObject(QVariant(d->currentElementSymbol), ChemicalDataObject::symbol)); d->inIsotope = true; for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "number") { d->currentIsotope->setNucleons(attrs.value(i).toInt()); } } } else if (d->inIsotope && localName == "scalar") { for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "errorValue") { d->currentErrorValue = QVariant(attrs.value(i)); continue; } if (attrs.value(i) == "bo:atomicNumber") { d->inAtomicNumber = true; } else if (attrs.value(i) == "bo:exactMass") { d->inExactMass = true; } else if (attrs.value(i) == "bo:halfLife") { for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "units") { if (attrs.value(i) == "siUnits:s") { d->currentUnit = KUnitConversion::Second; } else if (attrs.value(i) == "units:y") { d->currentUnit = KUnitConversion::Year; } else { d->currentUnit = KUnitConversion::NoUnit; } } } d->currentDataObject.setUnit(d->currentUnit); d->inHalfLife = true; } else if (attrs.value(i) == "bo:alphaDecay") { d->inAlphaDecay = true; } else if (attrs.value(i) == "bo:alphaDecayLikeliness") { d->inAlphaDecayLikeliness = true; } else if (attrs.value(i) == "bo:ecDecay") { d->inECDecay = true; } else if (attrs.value(i) == "bo:ecDecayLikeliness") { d->inECDecayLikeliness = true; } else if (attrs.value(i) == "bo:betaminusDecay") { d->inBetaminusDecay = true; } else if (attrs.value(i) == "bo:betaminusDecayLikeliness") { d->inBetaminusDecayLikeliness = true; } else if (attrs.value(i) == "bo:betaplusDecay") { d->inBetaplusDecay = true; } else if (attrs.value(i) == "bo:betaplusDecayLikeliness") { d->inBetaplusDecayLikeliness = true; } else if (attrs.value(i) == "bo:spin") { d->inSpin = true; } else if (attrs.value(i) == "bo:magneticMoment") { d->inMagMoment = true; } else if (attrs.value(i) == "bo:relativeAbundance") { d->inAbundance = true; } } } return true; } bool IsotopeParser::endElement(const QString&, const QString& localName, const QString&) { if (localName == "isotope") { d->isotopes.append(d->currentIsotope); - d->currentIsotope = 0; + d->currentIsotope = nullptr; d->inIsotope = false; } else if (localName == "isotopeList") { //a new list of isotopes start... d->inElement = false; } return true; } bool IsotopeParser::characters(const QString &ch) { ChemicalDataObject::BlueObelisk type; QVariant value; if (d->inExactMass) { value = ch.toDouble(); type = ChemicalDataObject::exactMass; d->inExactMass = false; } else if (d->inAtomicNumber) { value = ch.toInt(); type = ChemicalDataObject::atomicNumber; d->inAtomicNumber = false; } else if (d->inSpin) { value = ch; type = ChemicalDataObject::spin; d->inSpin = false; } else if (d->inMagMoment) { value = ch; type = ChemicalDataObject::magneticMoment; d->inMagMoment = false; } else if (d->inHalfLife) { value = ch.toDouble(); type = ChemicalDataObject::halfLife; d->inHalfLife = false; } else if (d->inAlphaDecay) { value = ch.toDouble(); type = ChemicalDataObject::alphaDecay; d->inAlphaDecay = false; } else if (d->inAlphaDecayLikeliness) { value = ch.toDouble(); type = ChemicalDataObject::alphaDecayLikeliness; d->inAlphaDecayLikeliness = false; } else if (d->inBetaplusDecay) { value = ch.toDouble(); type = ChemicalDataObject::betaplusDecay; d->inBetaplusDecay = false; } else if (d->inBetaplusDecayLikeliness) { value = ch.toDouble(); type = ChemicalDataObject::betaplusDecayLikeliness; d->inBetaplusDecayLikeliness = false; } else if (d->inBetaminusDecay) { value = ch.toDouble(); type = ChemicalDataObject::betaminusDecay; d->inBetaminusDecay = false; } else if (d->inBetaminusDecayLikeliness) { value = ch.toDouble(); type = ChemicalDataObject::betaminusDecayLikeliness; d->inBetaminusDecayLikeliness = false; } else if (d->inECDecayLikeliness) { value = ch.toDouble(); type = ChemicalDataObject::ecDecayLikeliness; d->inECDecayLikeliness = false; } else if (d->inECDecay) { value = ch.toDouble(); type = ChemicalDataObject::ecDecay; d->inECDecay = false; } else if (d->inAbundance) { value = ch; type = ChemicalDataObject::relativeAbundance; d->inAbundance = false; } else { //it is a non known value. Do not create a wrong object but return return true; } if (type == ChemicalDataObject::exactMass) { d->currentDataObject.setErrorValue(d->currentErrorValue); } d->currentDataObject.setData(value); d->currentDataObject.setType(type); if (d->currentIsotope) { d->currentIsotope->addData(d->currentDataObject); } return true; } QList IsotopeParser::getIsotopes() { return d->isotopes; } diff --git a/libscience/moleculeparser.cpp b/libscience/moleculeparser.cpp index 76ca6c5e..c90c5c76 100644 --- a/libscience/moleculeparser.cpp +++ b/libscience/moleculeparser.cpp @@ -1,436 +1,436 @@ /*************************************************************************** copyright : (C) 2005 by Inge Wallin email : inge@lysator.liu.se ***************************************************************************/ /*************************************************************************** * * * 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 "moleculeparser.h" #include #include #include #include // ================================================================ // class ElementCountMap ElementCountMap::ElementCountMap() { m_map.clear(); } ElementCountMap::~ElementCountMap() { } ElementCount *ElementCountMap::search(Element *_element) { foreach (ElementCount *c, m_map) { if (c->element() == _element) { return c; } } - return 0; + return nullptr; } void ElementCountMap::add(ElementCountMap &_map) { foreach (ElementCount *c, _map.m_map) { add(c->m_element, c->m_count); } } QList ElementCountMap::elements() { QList list; foreach (ElementCount* c, m_map) { Element* e = c->m_element; if (!list.contains(e)) { list << e; } } return list; } void ElementCountMap::add(Element *_element, int _count) { ElementCount *elemCount; elemCount = search(_element); if (elemCount) { elemCount->m_count += _count; } else { m_map.append(new ElementCount(_element, _count)); } } void ElementCountMap::multiply(int _factor) { foreach (ElementCount * count, m_map) { count->multiply(_factor); } } // ================================================================ // class MoleculeParser MoleculeParser::MoleculeParser( const QList &list) : Parser() { m_elementList = list; m_aliasList = new QSet; } MoleculeParser::MoleculeParser(const QString &_str) : Parser(_str) { m_aliasList = new QSet; } MoleculeParser::~MoleculeParser() { delete m_aliasList; } // ---------------------------------------------------------------- // public methods // Try to parse the molecule and get the weight of it. // // This method also acts as the main loop. bool MoleculeParser::weight(const QString &_shortMoleculeString, double *_resultMass, ElementCountMap *_resultMap) { if (_shortMoleculeString.isEmpty()) { return false; } // Clear the list of aliases and start filling it again. m_aliasList -> clear(); QString _moleculeString; // Clear the result variables and set m_error to false _resultMap->clear(); m_error = false; *_resultMass = 0.0; // Expand the molecule string // Example : MeOH -> (CH3)OH qDebug() << _shortMoleculeString << "is going to be expanded"; _moleculeString = expandFormula(_shortMoleculeString); qDebug() << _moleculeString << "is the expanded string"; // Now set the expanded string // Initialize the parsing process, and parse te molecule. start(_moleculeString); parseSubmolecule(_resultMass, _resultMap); if (nextToken() != -1) { return false; } if (m_error) {//there was an error in the input... return false; } return true; } QSet MoleculeParser::aliasList() { return *m_aliasList; } // ---------------------------------------------------------------- // helper methods for the public methods // Parse a submolecule. This is a list of terms. // bool MoleculeParser::parseSubmolecule(double *_resultMass, ElementCountMap *_resultMap) { double subMass = 0.0; ElementCountMap subMap; *_resultMass = 0.0; _resultMap->clear(); while (parseTerm(&subMass, &subMap)) { //qDebug() << "Parsed a term, weight = " << subresult; // Add the mass and composition of the submolecule to the total. *_resultMass += subMass; _resultMap->add(subMap); } return true; } // Parse a term within the molecule, i.e. a single atom or a // submolecule within parenthesis followed by an optional number. // Examples: Bk, Mn2, (COOH)2 // // Return true if correct, otherwise return false. // If correct, the mass of the term is returned in *_resultMass, and // the flattened composition of the molecule in *_resultMap. // bool MoleculeParser::parseTerm(double *_resultMass, ElementCountMap *_resultMap) { *_resultMass = 0.0; _resultMap->clear(); if (nextToken() == ELEMENT_TOKEN) { //qDebug() << "Parsed an element: " << m_elementVal->symbol(); *_resultMass = m_elementVal->dataAsVariant( ChemicalDataObject::mass ).toDouble(); _resultMap->add(m_elementVal, 1); getNextToken(); } else if (nextToken() == '(') { // A submolecule. getNextToken(); parseSubmolecule(_resultMass, _resultMap); // Must end in a ")". if (nextToken() == ')') { //qDebug() << "Parsed a submolecule. weight = " << *_result; getNextToken(); } else { return false; } } else { // Neither an element nor a list within (). return false; } // Optional number. if (nextToken() == INT_TOKEN) { //qDebug() << "Parsed a number: " << intVal(); *_resultMass *= intVal(); _resultMap->multiply(intVal()); getNextToken(); } qDebug() << "Weight of term = " << *_resultMass; return true; } // ---------------------------------------------------------------- // protected methods // Extend Parser::getNextToken with elements. int MoleculeParser::getNextToken() { QString name; #if 0 qDebug() << "getNextToken(): Next character = " << nextChar() << endl; #endif // Check if the token is an element name. if ('A' <= nextChar() && nextChar() <= 'Z') { name = char(nextChar()); getNextChar(); if ('a' <= nextChar() && nextChar() <= 'z') { name.append(char(nextChar())); getNextChar(); } // Look up the element from the name.. m_elementVal = lookupElement(name); if (m_elementVal) { m_nextToken = ELEMENT_TOKEN; } else { m_nextToken = -1; } } else { return Parser::getNextToken(); } return m_nextToken; } // ---------------------------------------------------------------- // private methods Element *MoleculeParser::lookupElement(const QString& _name) { qDebug() << "looking up " << _name; foreach (Element* e, m_elementList) { if (e->dataAsVariant(ChemicalDataObject::symbol) == _name) { qDebug() << "Found element " << _name; return e; } } //if there is an error make m_error true. m_error = true; qDebug() << "no such element!: " << _name; - return NULL; + return nullptr; } QString MoleculeParser::expandFormula( const QString& _shortString) { QString _fullString; // the expanded string that will be returned QString::const_iterator i; // iterator QString temp; // a temporary string that will contain a single element/group QString expandedTerm; // expansion of a particular term // Go through all letters in the string. for (i = _shortString.constBegin(); i != _shortString.constEnd(); ) { temp = ""; // If a capital letter was found if ((*i).category() == QChar::Letter_Uppercase) { temp += (*i); ++i; // A small letter following a capital letter if (i != _shortString.end() && (*i).category() == QChar::Letter_Lowercase) { temp += (*i); ++i; } // If element is found, append it if (lookupElement(temp)) { _fullString += temp; } else if (!((expandedTerm = expandTerm(temp)).isEmpty())) { // If an expansion was made, return the expansion qDebug() << "expanded" << temp << "to" << expandedTerm; _fullString += '('+expandedTerm+')'; } else { // invalid term, append it. (Validation is done later anyway.) _fullString += temp; } } else if (*i == '(') { // Return parenthesis as and when found _fullString += '('; ++i; } else if (*i == ')') { _fullString += ')'; ++i; } else if (*i == '#') { // If # is found, we have a short-form eg #EDTA# ++i; // go to the next character // Get the term between # and # while (*i != '#' && i != _shortString.constEnd() ) { temp += *i; ++i; } // If the string ended, just add the part that comes after # if (i == _shortString.constEnd()) { _fullString += temp; break; } else if (!temp.isEmpty()) { // else expand the term between # and # // if alias is not found, just add without expanding the term if ((expandedTerm = expandTerm(temp)).isEmpty()) { _fullString += temp; } else { // else add the expanded term _fullString += expandedTerm; } } ++i; } else if ((*i).category() == QChar::Number_DecimalDigit) { // If number was found, return it _fullString += *i; ++i; } else { // invalid character, return it, validation is done again later _fullString += *i; ++i; qDebug() << *i << "invalid character!"; } } // Reset all "element not found" errors. m_error = false; return _fullString; } QString MoleculeParser::expandTerm (const QString& _group) { QString shortForm, fullForm; // short form (symbol) and full form (expansion) QString temp; // A temporary QString used in Regular expressions // 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. while (!in.atEnd()) { QString line = in.readLine(); shortForm = line.section(',', 0, 0); shortForm.remove(QChar('\"')); fullForm = line.section(',', 1, 1); fullForm.remove(QChar('\"')); // If short term is found, return fullForm if (shortForm == _group) { *m_aliasList << (_group + " : " + fullForm); return (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); // 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('\"')); if (shortForm == _group) { *m_aliasList << (_group + " : " + fullForm); return (fullForm); } } } else { qDebug() << fileName << " could not be opened!"; } // Sample expansions, work even when file is not found, testing purposes if (_group == "Me") { return ("CH3"); } else if (_group == "Et") { return ("C2H5"); } else { // If not found return an empty string. return (""); } } diff --git a/libscience/psetables.cpp b/libscience/psetables.cpp index 95942d38..376ffa27 100644 --- a/libscience/psetables.cpp +++ b/libscience/psetables.cpp @@ -1,414 +1,414 @@ /********************************************************************************* * Copyright (C) 2005, 2006 by Pino Toscano, toscano.pino@tiscali.it * * Copyright (C) 2007 by Carste Niehaus, cniehaus@kde.org * * 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 "psetables.h" #include #include pseTables::pseTables() { m_tables << pseRegularTable::init(); m_tables << pseShortTable::init(); m_tables << pseLongTable::init(); m_tables << pseDTable::init(); m_tables << pseDZTable::init(); } pseTables::~pseTables() { } pseTables *pseTables::instance() { static pseTables tables; return &tables; } QStringList pseTables::tables() const { QStringList l; for (int i = 0; i < m_tables.count(); ++i) { l << m_tables.at(i)->description(); } return l; } pseTable* pseTables::getTabletype(const int tableType) { if ((tableType < 0) || (tableType >= m_tables.count())) { - return 0; + return nullptr; } return m_tables.at(tableType); } pseTable* pseTables::getTabletype(const QString tableName) { for (int i = 0; m_tables.count(); ++i) { if (tableName == m_tables.at(i)->name()) { return m_tables.at(i); } } - return 0; + return nullptr; } pseTable::pseTable() { } pseTable::~pseTable() { } pseTable *pseTable::init() { - return 0; + return nullptr; } QString pseTable::name() const { return m_name; } QString pseTable::description() const { return m_description; } QList pseTable::elements() const { return m_elementList; } int pseTable::previousOf(int element) const { int index = m_elementList.indexOf(element); return index > 0 ? m_elementList.at(index - 1) : -1; } int pseTable::nextOf(int element) const { int index = m_elementList.indexOf(element); return index != -1 && (index < m_elementList.count() - 1) ? m_elementList.at(index + 1) : -1; } int pseTable::firstElement() const { return m_elementList.first(); } int pseTable::lastElement() const { return m_elementList.last(); } QPoint pseTable::elementCoords(const int element) const { int x = -1, y = -1; int elementIndex = m_elementList.indexOf(element); if (elementIndex >= 0 && elementIndex < m_elementList.count()) { // The positions lists are defined with the base of 1. // But coordinates start mostly with 0. x = m_posX.at(elementIndex) - 1; y = m_posY.at(elementIndex) - 1; } return QPoint(x, y); } QPoint pseTable::tableSize() const { int x = 0, y = 0, i; for (i = 0; i < m_posX.count(); ++i) { if (m_posX.at(i) > x) { x = m_posX.at(i); } if (m_posY.at(i) > y) { y = m_posY.at(i); } } return QPoint(x, y); } int pseTable::numerationAtPos(int xPos) const { if (xPos >= 0 && xPos < m_xCoordsNumeration.count()) { return m_xCoordsNumeration.at(xPos) - 1; } return -1; } /// Regular Table Data pseRegularTable::pseRegularTable() : pseTable() { m_name = "Classic"; m_description = i18n("Classic Periodic Table"); m_xCoordsNumeration << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 17 << 18; m_posX << 1 << 18 << 1 << 2 << 13 << 14 << 15 << 16 << 17 << 18 << 1 << 2 << 13 << 14 << 15 << 16 << 17 << 18 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 17 << 18 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 17 << 18 << //Element 54 (Xe) 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 17 << //Element 58 (Ce) 71 (Lu) 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 17 << 18 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 17 << //Element 71 (Lr) 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 17 << 18 ; m_posY << 1 << 1 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 3 << 3 << 3 << 3 << 3 << 3 << 3 << 3 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 4 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << 5 << //Element 54 (Xe) 6 << 6 << 6 << 9 << 9 << 9 << 9 << 9 << 9 << 9 << 9 << 9 << 9 << 9 << 9 << 9 << 9 << //Element 71 (Lr) 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 7 << 7 << 7 << 10 << 10 << 10 << 10 << 10 << 10 << 10 << 10 << 10 << 10 << 10 << 10 << 10 << 10 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 ; // The classic PS has all Elements if (m_posX.count() == m_posY.count()) { for (int i = 1; i <= m_posX.count(); ++i) { m_elementList.append(i); } } } pseRegularTable *pseRegularTable::init() { static pseRegularTable thisTable; return &thisTable; } /// Long Table Data pseLongTable::pseLongTable() : pseTable() { m_name = "Long"; m_description = i18n("Long Periodic Table"); m_xCoordsNumeration << 1 << 2 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 3 << 4 << 5 << 6 << 7 << 8 << 9 <<10 <<11 <<12 <<13 <<14 <<15 <<16 <<17 <<18; m_posX << 1 << 32 << 1 << 2 << 27 <<28 <<29 <<30 <<31 <<32 << 1 << 2 << 27 <<28 <<29 <<30 <<31 <<32 << 1 << 2 << 17 <<18 <<19 <<20 <<21 <<22 <<23 <<24 <<25 <<26 <<27 <<28 <<29 <<30 <<31 <<32 << 1 << 2 << 17 <<18 <<19 <<20 <<21 <<22 <<23 <<24 <<25 <<26 <<27 <<28 <<29 <<30 <<31 <<32 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 <<10 <<11 <<12 <<13 <<14 <<15 <<16 <<17 <<18 <<19 <<20 <<21 <<22 <<23 <<24 <<25 <<26 <<27 <<28 <<29 <<30 <<31 <<32 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 <<10 <<11 <<12 <<13 <<14 <<15 <<16 <<17 <<18 <<19 <<20 <<21 <<22 <<23 <<24 <<25 <<26 <<27 <<28 <<29 <<30 <<31 <<32 ; m_posY << 1 << 1 << 2 << 2 << 2 <<2 <<2 <<2 <<2 <<2 << 3 << 3 << 3 <<3 <<3 <<3 <<3 <<3 << 4 << 4 << 4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 <<4 << 5 << 5 << 5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 <<5 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 << 6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 <<6 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 << 7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 <<7 ; // The long PS has all Elements if (m_posX.count() == m_posY.count()) { for (int i = 1; i <= m_posX.count(); ++i) { m_elementList.append(i); } } } pseLongTable *pseLongTable::init() { static pseLongTable thisTable; return &thisTable; } /// Short Table Data pseShortTable::pseShortTable() : pseTable() { m_name = "Short"; m_description = i18n("Short Periodic Table"); m_xCoordsNumeration << 1 << 2 <<13 <<14 <<15 <<16 <<17 <<18; m_posX << 1 << 8 < #include #include #include class SpectrumParser::Private { public: Private() - : currentSpectrum(0), + : currentSpectrum(nullptr), inMetadata_(false), inSpectrum_(false), inSpectrumList_(false), inPeakList_(false), inPeak_(false) {} ~Private() { delete currentSpectrum; delete currentPeak; } Spectrum * currentSpectrum; Spectrum::peak * currentPeak; bool inMetadata_; bool inSpectrum_; bool inSpectrumList_; bool inPeakList_; bool inPeak_; double wavelength; int intensity; QList spectra; }; SpectrumParser::SpectrumParser() : QXmlDefaultHandler(), d(new Private) { } SpectrumParser::~SpectrumParser() { delete d; } bool SpectrumParser::startElement(const QString&, const QString &localName, const QString&, const QXmlAttributes &attrs) { if (localName == "spectrum") { d->currentSpectrum = new Spectrum(); d->inSpectrum_ = true; //now save the element of the current spectrum for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "id") { currentElementID = attrs.value(i); } } } else if (d->inSpectrum_ && localName == "peakList") { d->inPeakList_ = true; } else if (d->inSpectrum_ && d->inPeakList_ && localName == "peak") { d->inPeak_ = true; for (int i = 0; i < attrs.length(); ++i) { if (attrs.localName(i) == "xValue") { d->intensity = attrs.value(i).toInt(); } else if (attrs.localName(i) == "yValue") { d->wavelength = attrs.value(i).toDouble(); } } d->currentPeak = new Spectrum::peak(d->wavelength, d->intensity); } return true; } bool SpectrumParser::endElement(const QString&, const QString& localName, const QString &) { if (localName == "spectrum") { int num = currentElementID.mid(1).toInt(); d->currentSpectrum->setParentElementNumber(num); d->spectra.append(d->currentSpectrum); - d->currentSpectrum = 0; + d->currentSpectrum = nullptr; d->inSpectrum_ = false; } else if (localName == "peakList") { d->inSpectrumList_ = false; } else if (localName == "peak") { //X qDebug() << "in 'peak'" << " with this data: " << d->currentPeak->intensity << " (intesity)" ; d->currentSpectrum->addPeak(d->currentPeak); - d->currentPeak = 0; + d->currentPeak = nullptr; d->inPeak_ = false; } return true; } bool SpectrumParser::characters(const QString &ch) { Q_UNUSED(ch) return true; } QList SpectrumParser::getSpectrums() { return d->spectra; } diff --git a/src/detailedgraphicaloverview.cpp b/src/detailedgraphicaloverview.cpp index 606bb9cb..78038299 100644 --- a/src/detailedgraphicaloverview.cpp +++ b/src/detailedgraphicaloverview.cpp @@ -1,170 +1,170 @@ /*************************************************************************** copyright : (C) 2004, 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 "detailedgraphicaloverview.h" #include "kalziumdataobject.h" #include "kalziumutils.h" #include #include #include #include #include #include #include #include #include #include #include "prefs.h" DetailedGraphicalOverview::DetailedGraphicalOverview(QWidget *parent) - : QWidget(parent), m_element(0) + : QWidget(parent), m_element(nullptr) { setAttribute(Qt::WA_NoBackground, true); setMinimumSize(300, 200); // Set Hydrogen as initial element. setElement(1); } void DetailedGraphicalOverview::setElement(int el) { m_element = KalziumDataObject::instance()->element(el); setBackgroundColor(KalziumElementProperty::instance()->getElementColor(el)); update(); } void DetailedGraphicalOverview::setBackgroundColor(QColor bgColor) { if (bgColor == Qt::transparent) { bgColor = palette().background().color(); } // add a gradient QLinearGradient grad(QPointF(0, 0), QPointF(0, height())); grad.setColorAt(0,bgColor); qreal h, s, v, a; bgColor.getHsvF(&h, &s, &v, &a); bgColor.setHsvF(h, s, v*0.6, a); grad.setColorAt(1,bgColor); m_backgroundBrush = QBrush(grad); } void DetailedGraphicalOverview::paintEvent(QPaintEvent*) { QRect rect(0, 0, width(), height()); QPixmap pm(width(), height()); QPainter p; p.begin(&pm); p.setBrush(Qt::SolidPattern); if (!m_element) { pm.fill(palette().background().color()); p.drawText(0, 0, width(), height(), Qt::AlignCenter | Qt::TextWordWrap, i18n("No element selected")); } else if (Prefs::colorschemebox() == 2) { //The iconic view is the 3rd view (0,1,2,...) pm.fill(palette().background().color()); QString pathname = QStandardPaths::locate(QStandardPaths::DataLocation, "data/iconsets/", QStandardPaths::LocateDirectory); int enumii = m_element->dataAsVariant(ChemicalDataObject::atomicNumber).toInt(); QString filename = pathname + "school" + '/' + QString::number(enumii) + ".svg"; QSvgRenderer svgrenderer; if (QFile::exists(filename) && svgrenderer.load(filename)) { QSize size = svgrenderer.defaultSize(); size.scale(width(), height(), Qt::KeepAspectRatio); QRect bounds(QPoint(0, 0), size); bounds.moveCenter(QPoint(width()/2, height()/2)); svgrenderer.render(&p, bounds); } else { p.drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, i18n("No graphic found")); } } else { const int h_t = 20; //height of the texts p.setBrush(m_backgroundBrush); p.drawRect(rect); p.setBrush(Qt::black); p.setBrush(Qt::NoBrush); QFont fA = QFontDatabase::systemFont(QFontDatabase::GeneralFont); QFont fB = QFontDatabase::systemFont(QFontDatabase::GeneralFont); QFont fC = QFontDatabase::systemFont(QFontDatabase::GeneralFont); fA.setPointSize(fA.pointSize() + 20); //Huge font fA.setBold(true); fB.setPointSize(fB.pointSize() + 6); //Big font fC.setPointSize(fC.pointSize() + 4); //Big font fC.setBold(true); QFontMetrics fmA = QFontMetrics(fA); QFontMetrics fmB = QFontMetrics(fB); //coordinates for element symbol: near the center int xA = 4 * width() / 10; int yA = height() / 2; //coordinates for the atomic number: offset from element symbol to the upper left int xB = xA - fmB.width(m_element->dataAsString(ChemicalDataObject::atomicNumber)); int yB = yA + fmB.height()/2; //Element Symbol p.setFont(fA); p.drawText(xA, yA, m_element->dataAsString(ChemicalDataObject::symbol)); //Atomic number p.setFont(fB); p.drawText(xB, yB, m_element->dataAsString(ChemicalDataObject::atomicNumber)); //Name and other data fC.setPointSize(h_t); p.setFont(fC); //Name p.drawText(1, 0, width(), height(), Qt::AlignLeft, m_element->dataAsString(ChemicalDataObject::name)); //TODO Oxidationstates -> not there yet //Mass QString massString = i18nc("For example '1.0079u', the mass of an element in units", "%1 u", m_element->dataAsString(ChemicalDataObject::mass)); int size3 = KalziumUtils::maxSize(massString, rect, fC, &p); fC.setPointSize(size3); p.setFont(fC); int offset = KalziumUtils::StringHeight(massString, fC, &p); p.drawText(0, height() - offset, width(), offset, Qt::AlignRight, massString ); } p.end(); p.begin(this); p.drawPixmap(0, 0, pm); p.end(); } diff --git a/src/detailinfodlg.cpp b/src/detailinfodlg.cpp index 486f56a5..295d19e8 100644 --- a/src/detailinfodlg.cpp +++ b/src/detailinfodlg.cpp @@ -1,638 +1,638 @@ /*************************************************************************** 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 #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); if (m_elementNumber == 1) { enableButton(User2, false); } else if (m_elementNumber == KalziumDataObject::instance()->numberOfElements()) { enableButton(User1, 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 = 0; + 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); } 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/elementdataviewer.cpp b/src/elementdataviewer.cpp index e5552d96..bf54ad6b 100644 --- a/src/elementdataviewer.cpp +++ b/src/elementdataviewer.cpp @@ -1,534 +1,534 @@ /*************************************************************************** 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 //QT-Includes #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), m_yData(new AxisData(AxisData::Y)), m_xData(new AxisData(AxisData::X)) { setCaption(i18n("Plot Data")); setButtons(Help | Close); setDefaultButton(Close); KalziumDataObject *kdo = KalziumDataObject::instance(); 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())); 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 = 0; - KPlotObject* dataPointRed = 0; + 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/exportdialog.cpp b/src/exportdialog.cpp index 06ff386f..960c030b 100644 --- a/src/exportdialog.cpp +++ b/src/exportdialog.cpp @@ -1,241 +1,241 @@ /*************************************************************************** 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 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(0) + : KDialog(parent),m_outputStream(nullptr) { qDebug() << "ExportDialog::ExportDialog"; setButtons(Help | User1 | Cancel); qDebug() << "ExportDialog: setButtons"; ui.setupUi(mainWidget()); qDebug() << "ExportDialog: ui.setupUi(mainWidget());"; setButtonGuiItem(User1, 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")); 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\");"; } 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::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/kalzium.cpp b/src/kalzium.cpp index 4636308c..41b73514 100644 --- a/src/kalzium.cpp +++ b/src/kalzium.cpp @@ -1,654 +1,654 @@ /*************************************************************************** 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 #define IDS_ELEMENTINFO 7 -Kalzium::Kalzium() : KXmlGuiWindow(0) +Kalzium::Kalzium() : KXmlGuiWindow(nullptr) { setObjectName("KalziumMainWindow"); // Init pointers with null - m_infoDialog = 0; - m_isotopeDialog = 0; - m_elementDataPlotter = 0; - m_tablesDialog = 0; - m_rsDialog = 0; - m_calculator = 0; - m_exportDialog = 0; - m_glossarydlg = 0; - m_elementInfo = 0; + 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")); 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 NULL; + 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 NULL; + 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/kalziumdataobject.cpp b/src/kalziumdataobject.cpp index a12fbbb0..2b310564 100644 --- a/src/kalziumdataobject.cpp +++ b/src/kalziumdataobject.cpp @@ -1,225 +1,225 @@ /*************************************************************************** * Copyright (C) 2005, 2006, 2007 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 "kalziumdataobject.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include struct StaticKalziumDataObject { KalziumDataObject kdo; }; Q_GLOBAL_STATIC(StaticKalziumDataObject, s_kdo) KalziumDataObject* KalziumDataObject::instance() { return &s_kdo->kdo; } KalziumDataObject::KalziumDataObject() - : m_search(0) + : m_search(nullptr) { // 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(); qAddPostRoutine(KalziumDataObject::cleanup); } KalziumDataObject::~KalziumDataObject() { //Delete all elements qDeleteAll(ElementList); //Delete all isotopes QHashIterator > i(m_isotopes); while (i.hasNext()) { i.next(); qDeleteAll(i.value()); } //Delete the spectra qDeleteAll(m_spectra); } Element* KalziumDataObject::element(int number) { // checking that we are requesting a valid element if ((number <= 0) || (number > m_numOfElements)) - return 0; + return nullptr; return ElementList[ number-1 ]; } QString KalziumDataObject::unitAsString(const int unit) const { return KUnitConversion::Converter().unit(KUnitConversion::UnitId(unit)).symbol(); } QPixmap KalziumDataObject::pixmap(int number) { // checking that we are requesting a valid element if ((number <= 0) || (number > m_numOfElements)) return QPixmap(); if (PixmapList.isEmpty()) loadIconSet(); 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; + return nullptr; } void KalziumDataObject::setSearch(Search *srch) { m_search = srch; } Search* KalziumDataObject::search() const { return m_search; } void KalziumDataObject::cleanup() { KalziumDataObject::instance()->cleanPixmaps(); } void KalziumDataObject::loadIconSet() { //FIXME in case we ever get more than one theme we need //a settings-dialog where we can select the different iconsets... const QString setname = "school"; QString pathname = QStandardPaths::locate( QStandardPaths::DataLocation, "data/iconsets/" + setname + '/', QStandardPaths::LocateDirectory); QSvgRenderer renderer; for (int i = 0; i < m_numOfElements; ++i) { QString filename = pathname + QString::number(i + 1) + ".svg"; renderer.load(filename); QPixmap pix(40, 40); pix.fill(Qt::transparent); QPainter p(&pix); renderer.render(&p); 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; } } void KalziumDataObject::cleanPixmaps() { PixmapList.clear(); } diff --git a/src/kalziumgradienttype.cpp b/src/kalziumgradienttype.cpp index 13e46103..ea0219ae 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 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 0; + 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 0; + 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 0; + 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 52275d0d..76388c47 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 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 0; + 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 0; + 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 0; + 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 4e67cfde..1d962630 100644 --- a/src/kalziumschemetype.cpp +++ b/src/kalziumschemetype.cpp @@ -1,627 +1,627 @@ /*************************************************************************** * 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 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 0; + 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 0; + 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 0; + 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 5109d107..69755af4 100644 --- a/src/kalziumutils.cpp +++ b/src/kalziumutils.cpp @@ -1,188 +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 "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(); + //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 (val == -1) { + } 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 0820fe71..ed12fa1c 100644 --- a/src/kdeeduglossary.cpp +++ b/src/kdeeduglossary.cpp @@ -1,548 +1,548 @@ /*************************************************************************** * 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 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()); if (!picName.isEmpty()) { desc.prepend("[img]" + picName + "[/img][brclear][br]"); } item->setName(i18n(nameNode.toElement().text().toUtf8())); 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()); } 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)) { setCaption(i18n("Glossary")); setButtons(Close); setDefaultButton(Close); //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); 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); } GlossaryDialog::~GlossaryDialog() { delete d; } void GlossaryDialog::keyPressEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Return) { e->ignore(); } KDialog::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 0; + 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/main.cpp b/src/main.cpp index 7797fed2..88335089 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,176 +1,176 @@ /*************************************************************************** * Copyright (C) 2003-2008 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 #include #include #include #include #include #include "kalzium.h" #define APP_VERSION "2.5.0" static const char version[] = APP_VERSION; #ifdef HAVE_FACILE extern "C" { void caml_startup(char**); } #endif int main(int argc, char **argv) { #ifdef HAVE_FACILE caml_startup(argv); #endif QApplication app(argc, argv); KLocalizedString::setApplicationDomain("kalzium"); KAboutData about("kalzium", i18n("Kalzium"), version, i18n("A periodic table of the elements"), KAboutLicense::GPL, i18n("(C) 2002-2016 Carsten Niehaus & the KDE Edu Developers"), QString(), "http://edu.kde.org/kalzium"); about.addAuthor(i18n("Carsten Niehaus"), QString(), "cniehaus@kde.org"); about.addCredit(i18n("Pino Toscano"), i18n("Large code contributions; resident guru helping the other developers")); about.addCredit(i18n("Benoit Jacob"), i18n("Base work on the molecular viewer, mentored Marcus during his SoC")); about.addCredit(i18n("Marcus Hanwell"), i18n("SoC on the molecular viewer and libavogadro porting/integration")); about.addCredit(i18n("Kashyap R Puranik"), i18n("SoC on the calculator widget and a few smaller improvements")); about.addCredit(i18n("Thomas Nagy"), i18n("EqChem, the equation solver")); about.addCredit(i18n("Inge Wallin"), i18n("Code cleaning, parser for the molecule weight calculator, and a lot of smaller improvements")); about.addCredit(i18n("Anne-Marie Mahfouf"), i18n("A lot of small things and the documentation")); about.addCredit(i18n("Johannes Simon"), i18n("Code and documentation contributions to the equation solver and molecular viewer")); about.addCredit(i18n("Jarle Akselsen"), i18n("Many beautiful element icons")); about.addCredit(i18n("Noémie Scherer"), i18n("Many beautiful element icons, too!")); about.addCredit(i18n("Danny Allen"), i18n("Several icons")); about.addCredit(i18n("Lee Olson"), i18n("Several icons in the information dialog")); about.addCredit(i18n("Jörg Buchwald"), i18n("Contributed most isotope information")); about.addCredit(i18n("Marco Martin"), i18n("Some icons and inspiration for others")); about.addCredit(i18n("Daniel Haas"), i18n("The design of the information dialog")); about.addCredit(i18n("Brian Beck"), i18n("The orbits icon")); about.addCredit(i18n("Paulo Cattai"), i18n("New interface design and usability improvements")); about.addCredit(i18n("Danilo Balzaque"), i18n("New interface design and usability improvements")); about.addCredit(i18n("Roberto Cunha"), i18n("New interface design and usability improvements")); about.addCredit(i18n("Tadeu Araujo"), i18n("New interface design and usability improvements")); about.addCredit(i18n("Tiago Porangaba"), i18n("New interface design and usability improvements")); about.addCredit(i18n("Etienne Rebetez"), i18n("Adding new sizable Periodic System")); QApplication::setApplicationName("kalzium"); QApplication::setApplicationVersion(version); QApplication::setOrganizationDomain("kde.org"); KAboutData::setApplicationData(about); QCommandLineParser parser; parser.addVersionOption(); parser.addHelpOption(); parser.addPositionalArgument(i18n("[molecule]"), i18n("Open the given molecule file")); QCommandLineOption moleculeOption(i18n("molecule"), i18n("Open the given molecule file")); parser.addOption(moleculeOption); about.setupCommandLine(&parser); parser.process(app); about.processCommandLine(&parser); #if defined(HAVE_OPENBABEL2) && defined(HAVE_EIGEN) && defined(HAVE_AVOGADRO) parser.addOption(QCommandLineOption(QStringList() << QLatin1String("m") << QLatin1String("molecule"), i18n("Open the given molecule file"), QLatin1String("file"))); #endif - Kalzium *mainWin = 0; + Kalzium *mainWin = nullptr; if (app.isSessionRestored()) { RESTORE(Kalzium); } else { // no session.. just start up normally /// @todo do something with the command line args here mainWin = new Kalzium(); mainWin->show(); const QStringList molecules = parser.values("molecule"); if (molecules.count() == 1) { mainWin->loadMolecule(molecules[0]); } else if (molecules.count() > 1) { QTextStream ts(stderr); ts << i18n("Can't open more than one molecule at a time"); } } // mainWin has WDestructiveClose flag by default, so it will delete itself. return app.exec(); } diff --git a/src/rsdialog.cpp b/src/rsdialog.cpp index c46aa281..90c1aff0 100644 --- a/src/rsdialog.cpp +++ b/src/rsdialog.cpp @@ -1,322 +1,322 @@ /*************************************************************************** * 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 "kalziumdataobject.h" #include "kalziumutils.h" #include #include #include RSDialog::RSDialog(QWidget* parent) : KDialog(parent) { setCaption(i18n("Risks/Security Phrases")); setButtons(Help | Close); createRPhrases(); createSPhrases(); ui.setupUi(mainWidget()); connect(ui.filterButton, SIGNAL(clicked()), this, SLOT(filter())); connect(this, SIGNAL(helpClicked()), this, SLOT(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(0, i18n("At least one of the specified phrases is invalid.")); + KMessageBox::error(nullptr, i18n("At least one of the specified phrases is invalid.")); } diff --git a/src/searchwidget.cpp b/src/searchwidget.cpp index 8c781906..d9c46f68 100644 --- a/src/searchwidget.cpp +++ b/src/searchwidget.cpp @@ -1,95 +1,95 @@ /*************************************************************************** * Copyright (C) 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 "searchwidget.h" #include #include #include #include #include #include "kalziumdataobject.h" #include "search.h" -SearchWidget::SearchWidget(QWidget *parent) : QWidget(parent), m_timer(0) +SearchWidget::SearchWidget(QWidget *parent) : QWidget(parent), m_timer(nullptr) { QHBoxLayout *mainlay = new QHBoxLayout(this); mainlay->setMargin(2); mainlay->setSpacing(5); mainlay->addWidget(new QLabel(i18n("Search:"), this)); m_searchLine = new KLineEdit(this); m_searchLine->setClearButtonEnabled(true); m_searchLine->setTrapReturnKey(true); connect(m_searchLine, SIGNAL(textChanged(QString)), this, SLOT(searchTextChanged(QString))); connect(m_searchLine, SIGNAL(returnPressed()), this, SLOT(slotReturnPressed())); mainlay->addWidget(m_searchLine); } SearchWidget::~SearchWidget() { delete m_searchLine; delete m_timer; } void SearchWidget::giveFocus() { m_searchLine->setFocus(Qt::MouseFocusReason); m_searchLine->setCursorPosition(m_searchLine->text().length()); } void SearchWidget::searchTextChanged(const QString&) { if (m_timer) { m_timer->stop(); } else { m_timer = new QTimer(this); m_timer->setSingleShot(true); connect(m_timer, SIGNAL(timeout()), this, SLOT(doSearch())); } // 1/3 of second should be ok m_timer->start(333); } void SearchWidget::slotReturnPressed() { if (m_timer) { m_timer->stop(); } doSearch(); } void SearchWidget::doSearch() { Search *s = KalziumDataObject::instance()->search(); if (!s) { return; } QString txt = m_searchLine->text(); if (txt.length() > 0) { s->doSearch(txt, Search::SearchAll); } else { s->resetSearch(); } } diff --git a/src/spectrumviewimpl.cpp b/src/spectrumviewimpl.cpp index 5b05aad6..ef785068 100644 --- a/src/spectrumviewimpl.cpp +++ b/src/spectrumviewimpl.cpp @@ -1,130 +1,130 @@ /*************************************************************************** copyright : (C) 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 "spectrumviewimpl.h" #include #include #include #include #include "kalziumdataobject.h" #include #include "prefs.h" SpectrumViewImpl::SpectrumViewImpl(QWidget *parent) : QWidget(parent) { setupUi(this); QStringList headers = QStringList() << i18n("Wavelength") << i18n("Intensity"); peakListTable->setHeaderLabels(headers); peakListTable->setRootIsDecorated(false); QList length; length << KUnitConversion::Nanometer << KUnitConversion::Angstrom; m_lengthUnit->setUnitList(length); m_lengthUnit->setIndexWithUnitId(Prefs::spectrumWavelengthUnit()); m_spectrumType->setCurrentIndex(Prefs::spectrumType()); connect(minimumValue, SIGNAL(valueChanged(int)), this, SLOT(updateMin(int))); connect(maximumValue, SIGNAL(valueChanged(int)), this, SLOT(updateMax(int))); connect(m_spectrumWidget, SIGNAL(bordersChanged(int,int)), this, SLOT(updateUI(int,int))); connect(m_spectrumWidget, SIGNAL(peakSelected(Spectrum::peak*)), this, SLOT(updatePeakInformation(Spectrum::peak*))); connect(m_spectrumType, SIGNAL(currentIndexChanged(int)), m_spectrumWidget, SLOT(slotActivateSpectrum(int))); connect(btn_resetZoom, SIGNAL(pressed()), m_spectrumWidget, SLOT(resetSpectrum())); connect(this, SIGNAL(settingsChanged()), m_spectrumWidget, SLOT(resetSpectrum())); connect(m_lengthUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setUnit())); resize(minimumSizeHint()); } void SpectrumViewImpl::fillPeakList() { peakListTable->clear(); QList items; for (int i = 0; i < m_spectrumWidget->spectrum()->peaklist().count(); ++i) { Spectrum::peak * peak = m_spectrumWidget->spectrum()->peaklist().at(i); double peakWavelength = peak->wavelengthToUnit(Prefs::spectrumWavelengthUnit()); QStringList row = QStringList() << QString::number(peakWavelength) << QString::number(peak->intensity); - items.append(new QTreeWidgetItem((QTreeWidget*)0, row)); + items.append(new QTreeWidgetItem((QTreeWidget*)nullptr, row)); } peakListTable->insertTopLevelItems(0, items); } void SpectrumViewImpl::updateUI(int l, int r) { minimumValue->setValue(l); maximumValue->setValue(r); minimumValue->setSuffix(KalziumDataObject::instance()->unitAsString( Prefs::spectrumWavelengthUnit())); maximumValue->setSuffix(KalziumDataObject::instance()->unitAsString( Prefs::spectrumWavelengthUnit())); } void SpectrumViewImpl::updatePeakInformation(Spectrum::peak *peak) { double peakWavelength = peak->wavelengthToUnit(Prefs::spectrumWavelengthUnit()); QList foundItems = peakListTable->findItems(QString::number(peakWavelength), Qt::MatchExactly); if (foundItems.isEmpty()) { return; } foreach (QTreeWidgetItem * item, peakListTable->selectedItems()) item->setSelected(false); foundItems.first()->setSelected(true); peakListTable->scrollToItem(foundItems.first()); } void SpectrumViewImpl::setUnit() { Prefs::setSpectrumWavelengthUnit(m_lengthUnit->getCurrentUnitId()); Prefs::self()->save(); qDebug() << "Unit changed: " << m_lengthUnit->getCurrentUnitId(); emit settingsChanged(); fillPeakList(); } void SpectrumViewImpl::updateMin(int left) { m_spectrumWidget->setRightBorder(maximumValue->value()); m_spectrumWidget->setLeftBorder(left); } void SpectrumViewImpl::updateMax(int right) { m_spectrumWidget->setLeftBorder(minimumValue->value()); m_spectrumWidget->setRightBorder(right); } diff --git a/src/spectrumwidget.cpp b/src/spectrumwidget.cpp index c6e86b55..081b53cf 100644 --- a/src/spectrumwidget.cpp +++ b/src/spectrumwidget.cpp @@ -1,395 +1,395 @@ /*************************************************************************** * 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 = NULL; + 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); }