source: src/UIElements/Views/Qt4/MoleculeList/QtMoleculeList.cpp@ 4e6ffe

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 4e6ffe was b2c2e4, checked in by Frederik Heber <heber@…>, 9 years ago

FIX: Qt's parent properly set from QtMainWindow's point of view.

  • Property mode set to 100644
File size: 31.6 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * QtMoleculeList.cpp
25 *
26 * Created on: Jan 21, 2010
27 * Author: crueger
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "QtMoleculeList.hpp"
36
37#include <QModelIndex>
38#include <QDebug>
39
40#include "UIElements/Views/Qt4/MoleculeList/QtMoleculeItem.hpp"
41#include "UIElements/Views/Qt4/MoleculeList/QtMoleculeItemFactory.hpp"
42#include "UIElements/Qt4/InstanceBoard/QtObservedInstanceBoard.hpp"
43
44#include <boost/bind.hpp>
45#include <boost/thread/locks.hpp>
46#include <iostream>
47
48#include "CodePatterns/MemDebug.hpp"
49
50#include "CodePatterns/Log.hpp"
51#include "CodePatterns/Observer/Notification.hpp"
52
53#include "Atom/atom.hpp"
54#include "Actions/MoleculeAction/ChangeNameAction.hpp"
55#include "Actions/SelectionAction/Molecules/PopMoleculesAction.hpp"
56#include "Actions/SelectionAction/Molecules/PushMoleculesAction.hpp"
57#include "Actions/SelectionAction/Molecules/MoleculeByIdAction.hpp"
58#include "Actions/ActionQueue.hpp"
59#include "Actions/ActionSequence.hpp"
60#include "Actions/ActionTrait.hpp"
61#include "Actions/MakroAction.hpp"
62#include "Descriptors/MoleculeIdDescriptor.hpp"
63#include "Formula.hpp"
64#include "molecule.hpp"
65
66using namespace std;
67
68const unsigned int QtMoleculeList::update_times_per_second = 20;
69
70QtMoleculeList::QtMoleculeList(
71 QtObservedInstanceBoard *_board,
72 QObject *_parent) :
73 QStandardItemModel(_parent),
74 update_timer(NULL),
75 board(_board),
76 callback_DirtyItems(boost::bind(&QtMoleculeList::informDirtyState, this, _1, _2, _3))
77{
78 setColumnCount(QtMoleculeItemFactory::COLUMNCOUNT);
79
80 resetUpdateTimer();
81
82 connect(this,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(moleculeNameChanged(QStandardItem*)));
83 connect(this, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(checkForVisibilityChange(QStandardItem*)));
84 connect(board, SIGNAL(moleculeInserted(const moleculeId_t)), this, SLOT(moleculeInserted(const moleculeId_t)));
85 connect(board, SIGNAL(moleculeRemoved(const moleculeId_t)), this, SLOT(moleculeRemoved(const moleculeId_t)));
86 connect(board, SIGNAL(moleculeIndexChanged(const moleculeId_t,const moleculeId_t)),
87 this, SLOT(moleculeIndexChanged(const moleculeId_t, const moleculeId_t)));
88}
89
90QtMoleculeList::~QtMoleculeList()
91{}
92
93QVariant QtMoleculeList::headerData(int section, Qt::Orientation orientation, int role) const
94{
95 if (role == Qt::DisplayRole) {
96 if (orientation == Qt::Horizontal) {
97 if (section < QtMoleculeItem::COLUMNTYPES_MAX)
98 return QString(QtMoleculeItemFactory::COLUMNNAMES[section]);
99 }
100 }
101 return QVariant();
102}
103
104void QtMoleculeList::moleculeInserted(const moleculeId_t _id)
105{
106 // get ObservedMolecule from board
107 QtObservedMolecule::ptr ObservedMolecule = board->getObservedMolecule(_id);
108 boost::recursive_mutex::scoped_lock lock(listAccessing_mutex);
109 newMolecules.push_back( ObservedMolecule );
110}
111
112void QtMoleculeList::moleculeRemoved(const moleculeId_t _id)
113{
114 boost::recursive_mutex::scoped_lock lock(map_mutex);
115 KilledItemsPerMolecule_t::iterator iter = KilledItemsPerMolecule.find(_id);
116 if (iter == KilledItemsPerMolecule.end())
117 KilledItemsPerMolecule.insert( std::make_pair(_id, 1));
118 else
119 ++(iter->second);
120 if (iter->second == QtMoleculeItem::COLUMNTYPES_MAX) {
121 boost::recursive_mutex::scoped_lock lock(listAccessing_mutex);
122 removedMolecules.push_back( _id );
123 }
124}
125
126template<class T>
127void exchangeKeys(
128 T &_container,
129 const moleculeId_t _oldid,
130 const moleculeId_t _newid)
131{
132 typename T::iterator iter = _container.find(_oldid);
133 ASSERT(_container.find(_newid) == _container.end(),
134 "exchangeKeys() - new id "+toString(_newid)
135 +" already exists in container.");
136 _container.insert( std::make_pair(_newid, iter->second) );
137 _container.erase(iter);
138}
139
140template<class T>
141void exchangeKeysInSet(
142 T &_container,
143 const moleculeId_t _oldid,
144 const moleculeId_t _newid)
145{
146 typename T::iterator iter = _container.find(_oldid);
147 ASSERT(_container.find(_newid) == _container.end(),
148 "exchangeKeys() - new id "+toString(_newid)
149 +" already exists in container.");
150 _container.insert( _newid );
151 _container.erase(iter);
152}
153
154template<class T>
155void exchangeKeysOverAllColumns(
156 T &_container,
157 const moleculeId_t _oldid,
158 const moleculeId_t _newid)
159{
160 for (int i=0;i<QtMoleculeItem::COLUMNTYPES_MAX;++i) {
161 typename T::iterator iter =
162 _container.find( std::make_pair(_oldid, (enum QtMoleculeItem::COLUMNTYPES)i) );
163 if (iter == _container.end())
164 continue;
165 ASSERT(_container.find( std::make_pair(_newid,(enum QtMoleculeItem::COLUMNTYPES)i) ) == _container.end(),
166 "exchangeKeys() - new id "+toString(_newid)
167 +" already exists in container.");
168 _container.insert( std::make_pair(_newid, (enum QtMoleculeItem::COLUMNTYPES)i) );
169 _container.erase(iter);
170 }
171}
172
173void QtMoleculeList::moleculeIndexChanged(
174 const moleculeId_t _oldid,
175 const moleculeId_t _newid)
176{
177 // go through all list and change keys
178 exchangeKeys(MoleculeFormulaMap, _oldid, _newid);
179 {
180 MoleculeItemBiMap_t::left_iterator iter = MoleculeItemBiMap.left.find(_oldid);
181 ASSERT(MoleculeItemBiMap.left.count(_newid),
182 "QtMoleculeList::moleculeIndexChanged() - new id "+toString(_newid)
183 +" already exists in MoleculeItemBiMap.");
184 MoleculeItemBiMap.left.insert( std::make_pair(_newid, iter->second) );
185 MoleculeItemBiMap.left.erase(iter);
186 }
187 exchangeKeys(KilledItemsPerMolecule, _oldid, _newid);
188 exchangeKeysOverAllColumns(dirtyMolItems, _oldid, _newid);
189 exchangeKeysInSet(visibilityMolItems, _oldid, _newid);
190 {
191 std::vector<moleculeId_t>::iterator iter =
192 std::find(removedMolecules.begin(), removedMolecules.end(), _oldid);
193 removedMolecules.erase(iter);
194 removedMolecules.push_back(_newid);
195 }
196 exchangeKeysInSet(toBeMovedItems, _oldid, _newid);
197}
198
199bool QtMoleculeList::isMoleculeItemPresent(const moleculeId_t _molid) const
200{
201 boost::recursive_mutex::scoped_lock lock(map_mutex);
202 MoleculeItemBiMap_t::left_const_iterator iter =
203 MoleculeItemBiMap.left.find(_molid);
204 return ( iter != MoleculeItemBiMap.left.end());
205}
206
207QtMoleculeItem * QtMoleculeList::MoleculeIdToItem(const moleculeId_t _molid) const
208{
209 boost::recursive_mutex::scoped_lock lock(map_mutex);
210 MoleculeItemBiMap_t::left_const_iterator iter =
211 MoleculeItemBiMap.left.find(_molid);
212 ASSERT( iter != MoleculeItemBiMap.left.end(),
213 "QtMoleculeList::MoleculeIdToItem() - could not find item to id "
214 +toString(_molid));
215 return iter->second;
216}
217
218const moleculeId_t QtMoleculeList::ItemToMoleculeId(const QtMoleculeItem * const _item) const
219{
220 boost::recursive_mutex::scoped_lock lock(map_mutex);
221 const MoleculeItemBiMap_t::right_const_iterator iter =
222 MoleculeItemBiMap.right.find(const_cast<QtMoleculeItem * const>(_item));
223 if (iter != MoleculeItemBiMap.right.end())
224 return iter->second;
225 else
226 return -1;
227}
228
229QtMoleculeItem * QtMoleculeList::getSpecificMoleculeItem(
230 const QtMoleculeItem * const _item,
231 const enum QtMoleculeItem::COLUMNTYPES _type) const
232{
233 QStandardItem *parent_item = _item->parent();
234 ASSERT( parent_item != NULL,
235 "QtMoleculeList::getSpecificMoleculeItem() - parent of molecule item is NULL");
236 return static_cast<QtMoleculeItem *>(parent_item->child(_item->index().row(), _type));
237}
238
239bool QtMoleculeList::isGroupItemPresent(const std::string &_formula) const
240{
241 boost::recursive_mutex::scoped_lock lock(map_mutex);
242 FormulaTreeItemBiMap_t::left_const_iterator iter =
243 FormulaItemBiMap.left.find(_formula);
244 return ( iter != FormulaItemBiMap.left.end());
245}
246
247QStandardItem * QtMoleculeList::FormulaToGroupItem(const std::string &_formula) const
248{
249 boost::recursive_mutex::scoped_lock lock(map_mutex);
250 FormulaTreeItemBiMap_t::left_const_iterator iter =
251 FormulaItemBiMap.left.find(_formula);
252 ASSERT( iter != FormulaItemBiMap.left.end(),
253 "QtMoleculeList::FormulaToGroupItem() - could not find item to formula "
254 +toString(_formula));
255 return iter->second;
256}
257
258const std::string& QtMoleculeList::GroupItemToFormula(const QStandardItem * const _item) const
259{
260 boost::recursive_mutex::scoped_lock lock(map_mutex);
261 static std::string emptystring;
262 const FormulaTreeItemBiMap_t::right_const_iterator iter =
263 FormulaItemBiMap.right.find(const_cast<QStandardItem * const>(_item));
264 if (iter != FormulaItemBiMap.right.end())
265 return iter->second;
266 else
267 return emptystring;
268}
269
270QStandardItem * QtMoleculeList::getSpecificGroupItem(
271 const QStandardItem * const _item,
272 const enum QtMoleculeItem::COLUMNTYPES _type) const
273{
274 return invisibleRootItem()->child(_item->index().row(), _type);
275}
276
277const QModelIndex QtMoleculeList::MoleculeIdToIndex(const moleculeId_t _id) const
278{
279 boost::recursive_mutex::scoped_lock lock(refill_mutex);
280 QtMoleculeItem * const item = MoleculeIdToItem(_id);
281 ASSERT(item != NULL,
282 "QtMoleculeList::MoleculeIdToIndex() - could not find item to "
283 +toString(_id));
284 return indexFromItem(item);
285}
286
287const moleculeId_t QtMoleculeList::IndexToMoleculeId(const QModelIndex &_index) const
288{
289 boost::recursive_mutex::scoped_lock lock(refill_mutex);
290 QtMoleculeItem * const item = dynamic_cast<QtMoleculeItem *>(itemFromIndex(_index));
291 if (item == NULL)
292 return -1;
293 else
294 return ItemToMoleculeId(item);
295}
296
297void QtMoleculeList::addGroupItem(
298 QStandardItem *&mainitem,
299 const std::string &_molecule_formula)
300{
301 QList<QStandardItem *> groupItems =
302 QtMoleculeItemFactory::getInstance().createGroupItems(_molecule_formula);
303 mainitem = groupItems.front();
304 {
305 boost::recursive_mutex::scoped_lock lock(map_mutex);
306 FormulaItemBiMap.left.insert( std::make_pair(_molecule_formula, mainitem) );
307 }
308 invisibleRootItem()->appendRow(groupItems);
309}
310
311QList<QStandardItem *> QtMoleculeList::createMoleculeItems(
312 QtObservedMolecule::ptr &_ObservedMolecule,
313 std::string &_molecule_formula)
314{
315 QList<QStandardItem *> molItems =
316 QtMoleculeItemFactory::getInstance().createMoleculeItems(
317 _ObservedMolecule,
318 callback_DirtyItems);
319 QtMoleculeItem *mol_item = dynamic_cast<QtMoleculeItem *>(molItems.front());
320 ASSERT( mol_item != NULL,
321 "QtMoleculeList::createMoleculeItems() - item from factory was not a QtMoleculeItem?");
322 MoleculeItemBiMap.left.insert( std::make_pair(_ObservedMolecule->getMolIndex(), mol_item) );
323
324 QStandardItem *formulaitem = molItems.at(QtMoleculeItem::FORMULA);
325 ASSERT( formulaitem != NULL,
326 "QtMoleculeList::createMoleculeItems() - Formula item not created by factory?");
327 _molecule_formula = formulaitem->text().toStdString();
328
329 LOG(1, "Adding " << _molecule_formula << " for "
330 << _ObservedMolecule->getMolIndex() << " to MoleculeFormulaMap.");
331 MoleculeFormulaMap.insert( std::make_pair( _ObservedMolecule->getMolIndex(), _molecule_formula) );
332// LOG(1, "Inserting molecule " << _molid << ": " << _molecule_formula);
333 return molItems;
334}
335
336std::string QtMoleculeList::addMolecule(QtObservedMolecule::ptr &_ObservedMolecule)
337{
338 // find group if already in list
339 QStandardItem *groupItem = NULL;
340
341 // create molecule items and obtain the molecule's formula
342 std::string molecule_formula;
343 QList<QStandardItem *> molItems = createMoleculeItems(_ObservedMolecule, molecule_formula);
344
345 // new molecule type -> create new group
346 if (!isGroupItemPresent(molecule_formula)){
347 // insert new formula entry into visibility
348#ifndef NDEBUG
349 std::pair< FormulaVisibilityCountMap_t::iterator, bool> visibilityinserter =
350#endif
351 FormulaVisibilityCountMap.insert(
352 std::make_pair( molecule_formula, (unsigned int)0) );
353 ASSERT( visibilityinserter.second,
354 "QtMoleculeList::refill() - molecule with formula "
355 +molecule_formula+" already in FormulaVisibilityCountMap.");
356
357 // create item and place into Map with formula as key
358 addGroupItem(groupItem, molecule_formula);
359 } else {
360 groupItem = FormulaToGroupItem(molecule_formula);
361 }
362 ASSERT( groupItem != NULL,
363 "QtMoleculeList::addMolecule() - item with id "+toString(_ObservedMolecule->getMolIndex())
364 +" has no parent?");
365 groupItem->appendRow(molItems);
366
367 return molecule_formula;
368}
369
370void QtMoleculeList::removeMoleculeItem(QtMoleculeItem * const _item)
371{
372 boost::recursive_mutex::scoped_lock lock(refill_mutex);
373 const QModelIndex mol_index = indexFromItem(_item);
374 QStandardItem *groupitem = _item->parent();
375 const QModelIndex group_index = groupitem->index();
376 {
377 boost::recursive_mutex::scoped_lock lock(map_mutex);
378 MoleculeItemBiMap_t::right_iterator removeiter =
379 MoleculeItemBiMap.right.find(_item);
380 ASSERT( removeiter != MoleculeItemBiMap.right.end(),
381 "QtMoleculeList::removeMoleculeItem() - could not find item in MoleculeBiMap.");
382 // LOG(1, "Erasing molecule " << (removeiter->second));
383 {
384 MoleculeFormulaMap_t::iterator removeformulaiter =
385 MoleculeFormulaMap.find(removeiter->second);
386 ASSERT( removeformulaiter != MoleculeFormulaMap.end(),
387 "QtMoleculeList::removeMoleculeItem() - could not find id "
388 +toString(removeiter->second)+" in MoleculeFormulaMap.");
389 LOG(1, "Removing " << removeformulaiter->second << " for "
390 << removeformulaiter->first << " from MoleculeFormulaMap.");
391 MoleculeFormulaMap.erase( removeformulaiter );
392 }
393 MoleculeItemBiMap.right.erase(removeiter);
394 }
395 removeRows(mol_index.row(), 1, group_index);
396}
397
398void QtMoleculeList::resetUpdateTimer()
399{
400 // check timer's presence
401 if (update_timer == NULL) {
402 update_timer = new QTimer(this);
403 connect( update_timer, SIGNAL(timeout()), this, SLOT(checkState()));
404 } else
405 update_timer->stop();
406
407 // activate timer
408 update_timer->start(1000/update_times_per_second);
409}
410
411bool QtMoleculeList::areAnyItemsDirty()
412{
413 // get whether any items are dirty
414 boost::recursive_mutex::scoped_lock lock(listAccessing_mutex);
415 bool dirty = false;
416 dirty |= !dirtyMolItems.empty();
417 dirty |= !visibilityMolItems.empty();
418 dirty |= !dirtyGroupItems.empty();
419 dirty |= !visibilityGroupItems.empty();
420 dirty |= !newMolecules.empty();
421 dirty |= !removedMolecules.empty();
422 dirty |= !toBeMovedItems.empty();
423 return dirty;
424}
425
426void QtMoleculeList::checkState()
427{
428 const bool dirty = areAnyItemsDirty();
429 // update if required
430 if (dirty)
431 updateItemStates();
432}
433
434void QtMoleculeList::checkForVisibilityChange(QStandardItem* _item)
435{
436// qDebug() << "Item changed called.";
437
438 boost::recursive_mutex::scoped_lock lock(refill_mutex);
439 if (_item->index().column() == QtMoleculeItem::VISIBILITY) {
440// qDebug() << "visibilityItem changed: " << (_item->checkState() ? "checked" : "unchecked");
441 boost::recursive_mutex::scoped_lock lock(listAccessing_mutex);
442 if ((_item->parent() == NULL) || (_item->parent() == invisibleRootItem()))
443 visibilityGroupItems.insert( std::make_pair(
444 GroupItemToFormula(_item->parent()), QtMoleculeItem::VISIBILITY) );
445 else
446 visibilityMolItems.insert(
447 static_cast<QtMoleculeItem *>(_item)->getMoleculeId()
448 );
449 }
450}
451
452void QtMoleculeList::setVisibilityForMoleculeItem(QtMoleculeItem* _item)
453{
454 if (ChangingChildrensVisibility)
455 return;
456
457 boost::recursive_mutex::scoped_lock lock(refill_mutex);
458 const bool visible = _item->checkState();
459 const moleculeId_t molid = _item->getMoleculeId();
460 std::string molecule_formula("illegal");
461 {
462 boost::recursive_mutex::scoped_lock lock(map_mutex);
463 MoleculeFormulaMap_t::const_iterator formulaiter =
464 MoleculeFormulaMap.find(molid);
465 ASSERT( formulaiter != MoleculeFormulaMap.end(),
466 "QtMoleculeList::setVisibilityForMoleculeItem() - formula of molecule "
467 +toString(molid)+" unknown.");
468 molecule_formula = formulaiter->second;
469 }
470 ASSERT( FormulaVisibilityCountMap.count(molecule_formula) != 0,
471 "QtMoleculeList::setVisibilityForMoleculeItem() - molecule with formula " +molecule_formula
472 +" is not present in FormulaVisibilityCountMap.");
473
474 // get parent
475 QStandardItem *groupItem = _item->parent();
476 QStandardItem *visgroupItem = getSpecificGroupItem(groupItem, QtMoleculeItem::VISIBILITY);
477 ASSERT( groupItem != NULL,
478 "QtMoleculeList::setVisibilityForMoleculeItem() - item with id "
479 +toString(_item->getMoleculeId())+" has not parent?");
480 // check whether we have to set the group item
481
482 ChangingChildrensVisibility = true;
483 if (visible) {
484 ++(FormulaVisibilityCountMap[molecule_formula]);
485 // compare with occurence/total number of molecules
486 if (FormulaVisibilityCountMap[molecule_formula] ==
487 (unsigned int)(groupItem->rowCount()))
488 visgroupItem->setCheckState(Qt::Checked);
489 } else {
490 --(FormulaVisibilityCountMap[molecule_formula]);
491 // none selected anymore?
492 if (FormulaVisibilityCountMap[molecule_formula] == 0)
493 visgroupItem->setCheckState(Qt::Unchecked);
494 }
495 ChangingChildrensVisibility = false;
496
497 emit moleculesVisibilityChanged(_item->getMoleculeId(), visible);
498}
499
500void QtMoleculeList::setVisibilityForGroupItem(QStandardItem* _item)
501{
502 if (ChangingChildrensVisibility)
503 return;
504
505 ChangingChildrensVisibility = true;
506
507 boost::recursive_mutex::scoped_lock lock(refill_mutex);
508 // go through all children, but don't enter for groupItem once more
509 const bool visible = _item->checkState();
510 QStandardItem *groupitem = getSpecificGroupItem(_item, QtMoleculeItem::NAME);
511 for (int i=0;i<groupitem->rowCount();++i) {
512 QtMoleculeItem *molItem = dynamic_cast<QtMoleculeItem *>(
513 groupitem->child(i, QtMoleculeItem::VISIBILITY));
514 if (molItem->checkState() != visible) {
515 molItem->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
516
517 // emit signal
518 emit moleculesVisibilityChanged(molItem->getMoleculeId(), visible);
519 }
520 }
521 // set current number of visible children
522 const std::string molecule_formula =
523 GroupItemToFormula( getSpecificGroupItem(_item, QtMoleculeItem::NAME) );
524 FormulaVisibilityCountMap_t::iterator countiter =
525 FormulaVisibilityCountMap.find(molecule_formula);
526 ASSERT( countiter != FormulaVisibilityCountMap.end(),
527 "QtMoleculeList::setVisibilityForGroupItem() - molecules "+molecule_formula
528 +" have no entry in visibility count map?");
529 countiter->second = visible ? groupitem->rowCount() : 0;
530
531 ChangingChildrensVisibility = false;
532}
533
534static
535MoleCuilder::MakroAction *constructMakroRenameAction(
536 MoleCuilder::ActionSequence &sequence,
537 const std::string &_new_name,
538 const moleculeId_t _molid
539 )
540{
541 MoleCuilder::ActionQueue &AQ = MoleCuilder::ActionQueue::getInstance();
542 MoleCuilder::ActionTrait trait("change-single-molecule-name");
543 sequence.addAction(AQ.getActionByName("push-molecule-selection").clone(MoleCuilder::Action::NonInteractive));
544 MoleCuilder::Action * const selectaction =
545 AQ.getActionByName("select-molecule-by-id").clone(MoleCuilder::Action::NonInteractive);
546 {
547 std::stringstream molid_string;
548 molid_string << toString(_molid);
549 selectaction->setOptionValue("select-molecule-by-id", molid_string.str());
550 }
551 sequence.addAction(selectaction);
552 MoleCuilder::Action * const changeaction =
553 AQ.getActionByName("change-molname").clone(MoleCuilder::Action::NonInteractive);
554 changeaction->setOptionValue("change-molname", _new_name);
555 sequence.addAction(changeaction);
556 sequence.addAction(AQ.getActionByName("pop-molecule-selection").clone(MoleCuilder::Action::NonInteractive));
557
558 MoleCuilder::MakroAction* makroaction =
559 new MoleCuilder::MakroAction(trait, sequence);
560 return makroaction;
561}
562
563void QtMoleculeList::moleculeNameChanged(QStandardItem* item)
564{
565 boost::recursive_mutex::scoped_lock lock(refill_mutex);
566 // obtain molecule id
567 if ( item->index().column() == QtMoleculeItem::NAME) {
568 QtMoleculeItem *molitem = assert_cast<QtMoleculeItem *>(item);
569 MoleculeItemBiMap_t::right_const_iterator iter = MoleculeItemBiMap.right.find(molitem);
570 ASSERT( iter != MoleculeItemBiMap.right.end(),
571 "QtMoleculeList::moleculeChanged() - name of unknown molecule changed.");
572 const moleculeId_t molid = iter->second;
573 // change the name
574 molecule * const mol = World::getInstance().getMolecule(MoleculeById(molid));
575 std::string cellValue = item->text().toStdString();
576 if ((mol->getName() != cellValue) && (!cellValue.empty())) {
577 // create actions such that we may undo
578 static MoleCuilder::ActionSequence sequence;
579 MoleCuilder::MakroAction *makroaction =
580 constructMakroRenameAction(sequence, cellValue, molid);
581 MoleCuilder::ActionQueue &AQ = MoleCuilder::ActionQueue::getInstance();
582 AQ.registerAction(makroaction);
583 AQ.queueAction("change-single-molecule-name", MoleCuilder::Action::NonInteractive);
584 } else if(cellValue=="") {
585 item->setText(QString(mol->getName().c_str()));
586 }
587}
588}
589
590
591int QtMoleculeList::setOccurrence(QStandardItem * const _groupitem)
592{
593 boost::recursive_mutex::scoped_lock lock(refill_mutex);
594 QModelIndex modelindex = _groupitem->index();
595 ASSERT( modelindex.isValid(),
596 "QtMoleculeList::setOccurrence() - groupitem not associated to model anymore.");
597 const int index = modelindex.row();
598 QStandardItem *parent_item =
599 _groupitem->parent() == NULL ? invisibleRootItem() : _groupitem->parent();
600 ASSERT( parent_item != NULL,
601 "QtMoleculeList::setOccurrence() - group item at "+toString(index)
602 +" does not have a parent?");
603 QStandardItem *occ_item = parent_item->child(index, QtMoleculeItem::OCCURRENCE);
604 ASSERT( occ_item != NULL,
605 "QtMoleculeList::setOccurrence() - group item at "+toString(index)
606 +" does not have an occurrence?");
607 const int count = _groupitem->rowCount();
608 if (count == 0) {
609 // we have to remove the group item completely
610 boost::recursive_mutex::scoped_lock lock(map_mutex);
611 const std::string molecule_formula = _groupitem->text().toStdString();
612 FormulaItemBiMap.left.erase(molecule_formula);
613 FormulaVisibilityCountMap.erase(molecule_formula);
614 return index;
615 } else {
616 occ_item->setText(QString::number(count));
617 return -1;
618 }
619}
620
621std::string QtMoleculeList::readdItem(QtMoleculeItem *_molitem)
622{
623 boost::recursive_mutex::scoped_lock lock(refill_mutex);
624 // use takeRows of molecule ..
625 QStandardItem *groupitem = _molitem->parent();
626 ASSERT( groupitem != NULL,
627 "QtMoleculeList::readdItem() - mol item at "+toString(_molitem->index().row())
628 +" does not have a groupitem?");
629 // get updated formula from the item
630 QStandardItem *formulaitem =
631 _molitem->parent()->child(_molitem->index().row(), QtMoleculeItem::FORMULA);
632 const std::string molecule_formula = formulaitem->text().toStdString();
633 QList<QStandardItem *> mol_row = _molitem->parent()->takeRow(_molitem->index().row());
634 // .. and re-add where new formula fits
635 if (!isGroupItemPresent(molecule_formula)) {
636 // add new group item and formula entry
637 addGroupItem(groupitem, molecule_formula);
638 } else {
639 groupitem = FormulaToGroupItem(molecule_formula);
640 }
641 ASSERT( groupitem != NULL,
642 "QtMoleculeList::readdItem() - failed to create a sensible new groupitem");
643 // finally add again
644 groupitem->appendRow(mol_row);
645
646 return molecule_formula;
647}
648
649void QtMoleculeList::informDirtyState(
650 const moleculeId_t _id,
651 const QtMoleculeItem::COLUMNTYPES _type,
652 const QtMoleculeItem::MoveTypes _movetype)
653{
654 listAccessing_mutex.lock();
655 dirtyMolItems.insert( std::make_pair(_id, _type) );
656 listAccessing_mutex.unlock();
657
658 if (_movetype == QtMoleculeItem::NeedsMove) {
659 // we have to convert whatever item raised the dirty signal to the first
660 // item in the row as otherwise multiple items in the row are selected
661 // as to be moved, i.e. the same row is moved multiple times
662 listAccessing_mutex.lock();
663 toBeMovedItems.insert(_id);
664 listAccessing_mutex.unlock();
665 }
666}
667
668void QtMoleculeList::updateItemStates()
669{
670 /// copy lists such that new signals for dirty/.. may come in right away
671 // TODO: if we had move semantics ...
672 listAccessing_mutex.lock();
673 list_of_molecule_items_t dirtyMolItems_copy = dirtyMolItems;
674 dirtyMolItems.clear();
675 list_of_molecules_t visibilityMolItems_copy = visibilityMolItems;
676 visibilityMolItems.clear();
677 list_of_group_items_t dirtyGroupItems_copy = dirtyGroupItems;
678 dirtyGroupItems.clear();
679 list_of_group_items_t visibilityGroupItems_copy = visibilityGroupItems;
680 visibilityGroupItems.clear();
681 std::vector<QtObservedMolecule::ptr> newMolecules_copy = newMolecules;
682 newMolecules.clear();
683 std::vector<moleculeId_t> removedMolecules_copy = removedMolecules;
684 removedMolecules.clear();
685 list_of_molecules_t toBeMovedItems_copy = toBeMovedItems;
686 toBeMovedItems.clear();
687 listAccessing_mutex.unlock();
688
689 // wait till initial refill has been executed
690 boost::recursive_mutex::scoped_lock lock(refill_mutex);
691
692// LOG(1, "Starting update.");
693
694 // remove removedMolecules from other lists.
695 for (std::vector<moleculeId_t>::const_iterator removeiter = removedMolecules_copy.begin();
696 removeiter != removedMolecules_copy.end(); ++removeiter) {
697 for (unsigned int i=0;i< QtMoleculeItem::COLUMNTYPES_MAX; ++i)
698 dirtyMolItems_copy.erase( std::make_pair(*removeiter,(QtMoleculeItem::COLUMNTYPES)i) );
699 toBeMovedItems_copy.erase(*removeiter);
700 visibilityMolItems_copy.erase(*removeiter);
701 }
702
703 /// 1a. do the update for each dirty item
704 for (list_of_molecule_items_t::const_iterator dirtyiter = dirtyMolItems_copy.begin();
705 dirtyiter != dirtyMolItems_copy.end(); ++dirtyiter) {
706 if (!isMoleculeItemPresent(dirtyiter->first))
707 continue;
708 QtMoleculeItem * const mol_item =
709 getSpecificMoleculeItem(
710 MoleculeIdToItem(dirtyiter->first),
711 dirtyiter->second);
712// LOG(1, "Updating item " << mol_item);
713 mol_item->updateState();
714 }
715
716 /// 1b. do the visibility update for each dirty item
717 for (list_of_molecules_t::const_iterator visiter = visibilityMolItems_copy.begin();
718 visiter != visibilityMolItems_copy.end(); ++visiter) {
719 if (!isMoleculeItemPresent(*visiter))
720 continue;
721 QtMoleculeItem * const visitem =
722 getSpecificMoleculeItem(
723 MoleculeIdToItem(*visiter),
724 QtMoleculeItem::VISIBILITY );
725// LOG(1, "Updating visibility of item " << visitem);
726 setVisibilityForMoleculeItem(visitem);
727 }
728
729 /// 2. move all items that need to be moved
730 typedef std::set<std::string> formulas_t;
731 formulas_t toBeSetOccurrence;
732 for (list_of_molecules_t::const_iterator moveiter = toBeMovedItems_copy.begin();
733 moveiter != toBeMovedItems_copy.end(); ++moveiter) {
734 boost::recursive_mutex::scoped_lock lock(map_mutex);
735// LOG(1, "Moving item " << molitem);
736 MoleculeFormulaMap_t::iterator formulaiter =
737 MoleculeFormulaMap.find(*moveiter);
738 ASSERT( formulaiter != MoleculeFormulaMap.end(),
739 "QtMoleculeList::updateItemStates() - formula of molecule "
740 +toString(*moveiter)+" unknown.");
741// LOG(1, "Adding " << formulaiter->second << " to toBeSetOccurrence.");
742 toBeSetOccurrence.insert( formulaiter->second );
743 if (!isMoleculeItemPresent(*moveiter))
744 continue;
745 QtMoleculeItem *const molitem = MoleculeIdToItem(*moveiter);
746 LOG(1, "Moving item " << molitem);
747 // remove from formula<->molecule bimap with old formula
748 LOG(1, "Removing " << formulaiter->second << " for " << formulaiter->first << " from MoleculeFormulaMap.");
749 MoleculeFormulaMap.erase( formulaiter );
750 const std::string formula = readdItem(molitem);
751 // and add to formula<->molecule bimap with updated formula
752 LOG(1, "Adding " << formula << " for " << *moveiter << " to MoleculeFormulaMap.");
753 MoleculeFormulaMap.insert( std::make_pair(*moveiter, formula) );
754// LOG(1, "Adding " << formula << " to toBeSetOccurrence.");
755 toBeSetOccurrence.insert( formula );
756 }
757
758 /// 3. remove all items whose molecules have been removed
759 for (std::vector<moleculeId_t>::const_iterator removeiter = removedMolecules_copy.begin();
760 removeiter != removedMolecules_copy.end(); ++removeiter) {
761// LOG(1, "Removing molecule " << *removeiter);
762 if (!isMoleculeItemPresent(*removeiter))
763 continue;
764 QtMoleculeItem *item = MoleculeIdToItem(*removeiter);
765 if (item != NULL) {
766 const std::string formula = item->parent()->text().toStdString();
767// LOG(1, "Adding " << formula << " to toBeSetOccurrence.");
768 toBeSetOccurrence.insert( formula );
769 removeMoleculeItem(item);
770 KilledItemsPerMolecule.erase( *removeiter );
771 }
772 }
773
774 // throw out items that we added by an update() while we are in this function
775 listAccessing_mutex.lock();
776 for (std::vector<moleculeId_t>::const_iterator removeiter = removedMolecules_copy.begin();
777 removeiter != removedMolecules_copy.end(); ++removeiter) {
778 for (unsigned int i=0;i< QtMoleculeItem::COLUMNTYPES_MAX; ++i)
779 dirtyMolItems.erase( std::make_pair(*removeiter,(QtMoleculeItem::COLUMNTYPES)i) );
780 toBeMovedItems.erase(*removeiter);
781 visibilityMolItems.erase(*removeiter);
782 }
783 listAccessing_mutex.unlock();
784 // after that it is not a problem as items have been removed (hence signOff() was called)
785
786 /// 4. instantiate all new items
787 for (std::vector<QtObservedMolecule::ptr>::iterator moliter = newMolecules_copy.begin();
788 moliter != newMolecules_copy.end(); ++moliter) {
789// LOG(1, "Adding molecule " << *moliter);
790 // check that World knows the molecule still
791 const std::string formula = addMolecule(*moliter);
792// LOG(1, "Adding " << formula << " to toBeSetOccurrence.");
793 toBeSetOccurrence.insert( formula );
794 }
795
796 /// 5a. update the group item's occurrence and visibility
797 std::set<int> RowsToRemove;
798 for (std::set<std::string>::const_iterator groupiter = toBeSetOccurrence.begin();
799 groupiter != toBeSetOccurrence.end(); ++groupiter) {
800// LOG(1, "Updating group item's occurence " << *groupiter);
801 QStandardItem *groupitem = FormulaToGroupItem(*groupiter);
802 const int index = setOccurrence(groupitem);
803 if (index != -1) {
804// LOG(1, "Removing row of group item " << groupitem);
805 RowsToRemove.insert(index);
806 }
807 }
808 toBeSetOccurrence.clear();
809
810 // remove all visibility updates whose row is removed
811 for (list_of_group_items_t::iterator visiter = visibilityGroupItems_copy.begin();
812 visiter != visibilityGroupItems_copy.end(); ) {
813 QStandardItem * const groupitem = FormulaToGroupItem(visiter->first);
814 if (RowsToRemove.count(groupitem->index().row()) != 0) {
815// LOG(1, "Removing vis item " << *visiter << " because of removed group item.");
816 visibilityGroupItems_copy.erase(visiter++);
817 } else
818 ++visiter;
819 }
820
821 // update visibility of all group items
822 for (list_of_group_items_t::iterator visiter = visibilityGroupItems_copy.begin();
823 visiter != visibilityGroupItems_copy.end(); ++visiter) {
824// LOG(1, "Updating visibility of item " << *visiter);
825 QStandardItem * const groupitem =
826 getSpecificGroupItem(FormulaToGroupItem(visiter->first),
827 visiter->second);
828 setVisibilityForGroupItem(groupitem);
829 }
830
831 /// 5b. remove all rows with 0 occurrence starting from last
832 for (std::set<int>::reverse_iterator riter = RowsToRemove.rbegin();
833 riter != RowsToRemove.rend(); ++riter) {
834// LOG(1, "Removing group item at row " << *riter);
835 removeRows(*riter, 1, invisibleRootItem()->index());
836 }
837
838 // and done
839// LOG(1, "Done with update.");
840}
Note: See TracBrowser for help on using the repository browser.