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

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 ca1535 was ca1535, checked in by Frederik Heber <heber@…>, 9 years ago

All QtMoleculeItem now heed QtObservedMolecule and QtMoleculeList takes InstanceBoard.

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