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

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

Removed molecules_deprecated from World and unnecessary includes of MoleculeListClass and all insert/erase.

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