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

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 Candidate_v1.7.0 Candidate_v1.7.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 a39d72 was a39d72, checked in by Frederik Heber <heber@…>, 10 years ago

Fixed formula usage in Qt part of code.

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