vymmodel.cpp
author insilmaril
Wed, 29 Oct 2008 17:42:34 +0000
changeset 727 96402b172173
parent 726 7f43b93242aa
child 728 a8a98a94899a
permissions -rw-r--r--
subtrees can be deleted now
     1 #include <QApplication>
     2 #include <typeinfo>
     3 
     4 #include "vymmodel.h"
     5 
     6 #include "editxlinkdialog.h"
     7 #include "exports.h"
     8 #include "exportxhtmldialog.h"
     9 #include "file.h"
    10 #include "geometry.h"		// for addBBox
    11 #include "mainwindow.h"
    12 #include "mapcenterobj.h"
    13 #include "misc.h"
    14 #include "parser.h"
    15 #include "selection.h"
    16 
    17 
    18 #include "warningdialog.h"
    19 #include "xml-freemind.h"
    20 #include "xmlobj.h"
    21 #include "xml-vym.h"
    22 
    23 
    24 extern bool debug;
    25 extern Main *mainWindow;
    26 extern Settings settings;
    27 extern QString tmpVymDir;
    28 
    29 extern TextEditor *textEditor;
    30 
    31 
    32 extern QString clipboardDir;
    33 extern QString clipboardFile;
    34 extern bool clipboardEmpty;
    35 
    36 extern ImageIO imageIO;
    37 
    38 extern QString vymName;
    39 extern QString vymVersion;
    40 extern QDir vymBaseDir;
    41 
    42 extern QDir lastImageDir;
    43 extern QDir lastFileDir;
    44 
    45 extern FlagRowObj *standardFlagsDefault;
    46 
    47 extern Settings settings;
    48 
    49 
    50 
    51 int VymModel::mapNum=0;	// make instance
    52 
    53 VymModel::VymModel() 
    54 {
    55 //    cout << "Const VymModel\n";
    56 	init();
    57 }
    58 
    59 
    60 VymModel::~VymModel() 
    61 {
    62 //    cout << "Destr VymModel\n";
    63 	autosaveTimer->stop();
    64 	fileChangedTimer->stop();
    65 	clear();
    66 }	
    67 
    68 void VymModel::clear() 
    69 {
    70 	cout << "VymModel::clear   rows="<<rowCount(index(rootItem))<<endl;	
    71 	selection.clear();
    72 
    73 	// Remove stuff    
    74 	while (!mapCenters.isEmpty())			// FIXME VM needs to be in treemodel only...
    75 		delete mapCenters.takeFirst();
    76 
    77 	QModelIndex ri=index(rootItem);
    78 	removeRows (0, rowCount(ri),ri);	
    79 }
    80 
    81 void VymModel::init () 
    82 {
    83 	// We should have at least one map center to start with
    84 	// addMapCenter();  FIXME VM create this in MapEditor as long as model is part of that
    85 
    86 	// No MapEditor yet
    87 	mapEditor=NULL;
    88 
    89 	// History 
    90 	mapNum++;
    91     mapChanged=false;
    92 	mapDefault=true;
    93 	mapUnsaved=false;
    94 
    95 	curStep=0;
    96 	redosAvail=0;
    97 	undosAvail=0;
    98 
    99  	stepsTotal=settings.readNumEntry("/history/stepsTotal",100);
   100 	undoSet.setEntry ("/history/stepsTotal",QString::number(stepsTotal));
   101 	mainWindow->updateHistory (undoSet);
   102 
   103 	// Create tmp dirs
   104 	makeTmpDirectories();
   105 	
   106 	// Files
   107 	zipped=true;
   108 	filePath="";
   109 	fileName=tr("unnamed");
   110 	mapName="";
   111 	blockReposition=false;
   112 	blockSaveState=false;
   113 
   114 	autosaveTimer=new QTimer (this);
   115 	connect(autosaveTimer, SIGNAL(timeout()), this, SLOT(autosave()));
   116 
   117 	fileChangedTimer=new QTimer (this);
   118 	fileChangedTimer->start(3000);
   119 	connect(fileChangedTimer, SIGNAL(timeout()), this, SLOT(fileChanged()));
   120 
   121 
   122 	// selections
   123 	selection.setModel (this);
   124 	selection.unselect();
   125 
   126 	// find routine
   127 	itFind=NULL;				
   128 	EOFind=false;
   129 
   130 	// animations
   131 	animationUse=settings.readBoolEntry("/animation/use",false);
   132 	animationTicks=settings.readNumEntry("/animation/ticks",10);
   133 	animationInterval=settings.readNumEntry("/animation/interval",50);
   134 	animObjList.clear();
   135 	animationTimer=new QTimer (this);
   136 	connect(animationTimer, SIGNAL(timeout()), this, SLOT(animate()));
   137 
   138 	// View - map
   139 	defLinkColor=QColor (0,0,255);
   140 	defXLinkColor=QColor (180,180,180);
   141 	linkcolorhint=LinkableMapObj::DefaultColor;
   142 	linkstyle=LinkableMapObj::PolyParabel;
   143 	defXLinkWidth=1;
   144 	defXLinkColor=QColor (230,230,230);
   145 
   146 	hidemode=HideNone;
   147 
   148 
   149 
   150 	// Network
   151 	netstate=Offline;
   152 
   153 	// Create MapCenter
   154 	//  addMapCenter();  FIXME VM create this in MapEditor until BO and MCO are independent of scene
   155 
   156 }
   157 
   158 void VymModel::makeTmpDirectories()
   159 {
   160 	// Create unique temporary directories
   161 	tmpMapDir = tmpVymDir+QString("/model-%1").arg(mapNum);
   162 	histPath = tmpMapDir+"/history";
   163 	QDir d;
   164 	d.mkdir (tmpMapDir);
   165 }
   166 
   167 
   168 MapEditor* VymModel::getMapEditor()	// FIXME VM better return favourite editor here
   169 {
   170 	return mapEditor;
   171 }
   172 
   173 bool VymModel::isRepositionBlocked()
   174 {
   175 	return blockReposition;
   176 }
   177 
   178 void VymModel::updateActions()	// FIXME  maybe don't update if blockReposition is set
   179 {
   180 	// Tell mainwindow to update states of actions
   181 	mainWindow->updateActions();
   182 }
   183 
   184 
   185 
   186 QString VymModel::saveToDir(const QString &tmpdir, const QString &prefix, bool writeflags, const QPointF &offset, LinkableMapObj *saveSel)
   187 {
   188 	// tmpdir		temporary directory to which data will be written
   189 	// prefix		mapname, which will be appended to images etc.
   190 	// writeflags	Only write flags for "real" save of map, not undo
   191 	// offset		offset of bbox of whole map in scene. 
   192 	//				Needed for XML export
   193 	
   194 
   195 	XMLObj xml;
   196 
   197 	// Save Header
   198 	QString ls;
   199 	switch (linkstyle)
   200 	{
   201 		case LinkableMapObj::Line: 
   202 			ls="StyleLine";
   203 			break;
   204 		case LinkableMapObj::Parabel:
   205 			ls="StyleParabel";
   206 			break;
   207 		case LinkableMapObj::PolyLine:	
   208 			ls="StylePolyLine";
   209 			break;
   210 		default:
   211 			ls="StylePolyParabel";
   212 			break;
   213 	}	
   214 
   215 	QString s="<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE vymmap>\n";
   216 	QString colhint="";
   217 	if (linkcolorhint==LinkableMapObj::HeadingColor) 
   218 		colhint=xml.attribut("linkColorHint","HeadingColor");
   219 
   220 	QString mapAttr=xml.attribut("version",vymVersion);
   221 	if (!saveSel)
   222 		mapAttr+= xml.attribut("author",author) +
   223 				  xml.attribut("comment",comment) +
   224 			      xml.attribut("date",getDate()) +
   225 		          xml.attribut("backgroundColor", mapScene->backgroundBrush().color().name() ) +
   226 		          xml.attribut("selectionColor", selection.getColor().name() ) +
   227 		          xml.attribut("linkStyle", ls ) +
   228 		          xml.attribut("linkColor", defLinkColor.name() ) +
   229 		          xml.attribut("defXLinkColor", defXLinkColor.name() ) +
   230 		          xml.attribut("defXLinkWidth", QString().setNum(defXLinkWidth,10) ) +
   231 		          colhint; 
   232 	s+=xml.beginElement("vymmap",mapAttr);
   233 	xml.incIndent();
   234 
   235 	// Find the used flags while traversing the tree
   236 	standardFlagsDefault->resetUsedCounter();
   237 	
   238 	// Reset the counters before saving
   239 	// TODO constr. of FIO creates lots of objects, better do this in some other way...
   240 	FloatImageObj (mapScene).resetSaveCounter();
   241 
   242 	// Build xml recursivly
   243 	if (!saveSel || typeid (*saveSel) == typeid (MapCenterObj))
   244 		// Save complete map, if saveSel not set
   245 		s+=saveToDir(tmpdir,prefix,writeflags,offset);
   246 	else
   247 	{
   248 		if ( typeid(*saveSel) == typeid(BranchObj) )
   249 			// Save Subtree
   250 			s+=((BranchObj*)(saveSel))->saveToDir(tmpdir,prefix,offset);
   251 		else if ( typeid(*saveSel) == typeid(FloatImageObj) )
   252 			// Save image
   253 			s+=((FloatImageObj*)(saveSel))->saveToDir(tmpdir,prefix);
   254 	}
   255 
   256 	// Save local settings
   257 	s+=settings.getDataXML (destPath);
   258 
   259 	// Save selection
   260 	if (!selection.isEmpty() && !saveSel ) 
   261 		s+=xml.valueElement("select",selection.getSelectString());
   262 
   263 	xml.decIndent();
   264 	s+=xml.endElement("vymmap");
   265 
   266 	if (writeflags)
   267 		standardFlagsDefault->saveToDir (tmpdir+"/flags/","",writeflags);
   268 	return s;
   269 }
   270 
   271 void VymModel::setFilePath(QString fpath, QString destname)
   272 {
   273 	if (fpath.isEmpty() || fpath=="")
   274 	{
   275 		filePath="";
   276 		fileName="";
   277 		destPath="";
   278 	} else
   279 	{
   280 		filePath=fpath;		// becomes absolute path
   281 		fileName=fpath;		// gets stripped of path
   282 		destPath=destname;	// needed for vymlinks and during load to reset fileChangedTime
   283 
   284 		// If fpath is not an absolute path, complete it
   285 		filePath=QDir(fpath).absPath();
   286 		fileDir=filePath.left (1+filePath.findRev ("/"));
   287 
   288 		// Set short name, too. Search from behind:
   289 		int i=fileName.findRev("/");
   290 		if (i>=0) fileName=fileName.remove (0,i+1);
   291 
   292 		// Forget the .vym (or .xml) for name of map
   293 		mapName=fileName.left(fileName.findRev(".",-1,true) );
   294 	}
   295 }
   296 
   297 void VymModel::setFilePath(QString fpath)
   298 {
   299 	setFilePath (fpath,fpath);
   300 }
   301 
   302 QString VymModel::getFilePath()
   303 {
   304 	return filePath;
   305 }
   306 
   307 QString VymModel::getFileName()
   308 {
   309 	return fileName;
   310 }
   311 
   312 QString VymModel::getMapName()
   313 {
   314 	return mapName;
   315 }
   316 
   317 QString VymModel::getDestPath()
   318 {
   319 	return destPath;
   320 }
   321 
   322 ErrorCode VymModel::load (QString fname, const LoadMode &lmode, const FileType &ftype)
   323 {
   324 	ErrorCode err=success;
   325 
   326 	parseBaseHandler *handler;
   327 	fileType=ftype;
   328 	switch (fileType)
   329 	{
   330 		case VymMap: handler=new parseVYMHandler; break;
   331 		case FreemindMap : handler=new parseFreemindHandler; break;
   332 		default: 
   333 			QMessageBox::critical( 0, tr( "Critical Parse Error" ),
   334 				   "Unknown FileType in VymModel::load()");
   335 		return aborted;	
   336 	}
   337 	if (lmode==NewMap)
   338 	{
   339 		selection.clear();
   340 		// FIXME VM not needed??? model->setMapEditor(this);
   341 		// (map state is set later at end of load...)
   342 	} else
   343 	{
   344 		BranchObj *bo=selection.getBranch();
   345 		if (!bo) return aborted;
   346 		if (lmode==ImportAdd)
   347 			saveStateChangingPart(
   348 				bo,
   349 				bo,
   350 				QString("addMapInsert (%1)").arg(fname),
   351 				QString("Add map %1 to %2").arg(fname).arg(getObjectName(bo)));
   352 		else	
   353 			saveStateChangingPart(
   354 				bo,
   355 				bo,
   356 				QString("addMapReplace(%1)").arg(fname),
   357 				QString("Add map %1 to %2").arg(fname).arg(getObjectName(bo)));
   358 	}	
   359     
   360 
   361 	// Create temporary directory for packing
   362 	bool ok;
   363 	QString tmpZipDir=makeTmpDir (ok,"vym-pack");
   364 	if (!ok)
   365 	{
   366 		QMessageBox::critical( 0, tr( "Critical Load Error" ),
   367 		   tr("Couldn't create temporary directory before load\n"));
   368 		return aborted; 
   369 	}
   370 
   371 	// Try to unzip file
   372 	err=unzipDir (tmpZipDir,fname);
   373 	QString xmlfile;
   374 	if (err==nozip)
   375 	{
   376 		xmlfile=fname;
   377 		zipped=false;
   378 	} else
   379 	{
   380 		zipped=true;
   381 		
   382 		// Look for mapname.xml
   383 		xmlfile= fname.left(fname.findRev(".",-1,true));
   384 		xmlfile=xmlfile.section( '/', -1 );
   385 		QFile mfile( tmpZipDir + "/" + xmlfile + ".xml");
   386 		if (!mfile.exists() )
   387 		{
   388 			// mapname.xml does not exist, well, 
   389 			// maybe someone renamed the mapname.vym file...
   390 			// Try to find any .xml in the toplevel 
   391 			// directory of the .vym file
   392 			QStringList flist=QDir (tmpZipDir).entryList("*.xml");
   393 			if (flist.count()==1) 
   394 			{
   395 				// Only one entry, take this one
   396 				xmlfile=tmpZipDir + "/"+flist.first();
   397 			} else
   398 			{
   399 				for ( QStringList::Iterator it = flist.begin(); it != flist.end(); ++it ) 
   400 					*it=tmpZipDir + "/" + *it;
   401 				// TODO Multiple entries, load all (but only the first one into this ME)
   402 				//mainWindow->fileLoadFromTmp (flist);
   403 				//returnCode=1;	// Silently forget this attempt to load
   404 				qWarning ("MainWindow::load (fn)  multimap found...");
   405 			}	
   406 				
   407 			if (flist.isEmpty() )
   408 			{
   409 				QMessageBox::critical( 0, tr( "Critical Load Error" ),
   410 						   tr("Couldn't find a map (*.xml) in .vym archive.\n"));
   411 				err=aborted;				   
   412 			}	
   413 		} //file doesn't exist	
   414 		else
   415 			xmlfile=mfile.name();
   416 	}
   417 
   418 	QFile file( xmlfile);
   419 
   420 	// I am paranoid: file should exist anyway
   421 	// according to check in mainwindow.
   422 	if (!file.exists() )
   423 	{
   424 		QMessageBox::critical( 0, tr( "Critical Parse Error" ),
   425 				   tr(QString("Couldn't open map %1").arg(file.name())));
   426 		err=aborted;	
   427 	} else
   428 	{
   429 		bool blockSaveStateOrg=blockSaveState;
   430 		blockReposition=true;
   431 		blockSaveState=true;
   432 		QXmlInputSource source( file);
   433 		QXmlSimpleReader reader;
   434 		reader.setContentHandler( handler );
   435 		reader.setErrorHandler( handler );
   436 		handler->setModel ( this);
   437 
   438 
   439 		// We need to set the tmpDir in order  to load files with rel. path
   440 		QString tmpdir;
   441 		if (zipped)
   442 			tmpdir=tmpZipDir;
   443 		else
   444 			tmpdir=fname.left(fname.findRev("/",-1));	
   445 		handler->setTmpDir (tmpdir);
   446 		handler->setInputFile (file.name());
   447 		handler->setLoadMode (lmode);
   448 		bool ok = reader.parse( source );
   449 		blockReposition=false;
   450 		blockSaveState=blockSaveStateOrg;
   451 		file.close();
   452 		if ( ok ) 
   453 		{
   454 			reposition();	// FIXME VM reposition the view instead...
   455 			selection.update();
   456 			if (lmode==NewMap)
   457 			{
   458 				mapDefault=false;
   459 				mapChanged=false;
   460 				mapUnsaved=false;
   461 				autosaveTimer->stop();
   462 			}
   463 
   464 			// Reset timestamp to check for later updates of file
   465 			fileChangedTime=QFileInfo (destPath).lastModified();
   466 		} else 
   467 		{
   468 			QMessageBox::critical( 0, tr( "Critical Parse Error" ),
   469 					   tr( handler->errorProtocol() ) );
   470 			// returnCode=1;	
   471 			// Still return "success": the map maybe at least
   472 			// partially read by the parser
   473 		}	
   474 	}	
   475 
   476 	// Delete tmpZipDir
   477 	removeDir (QDir(tmpZipDir));
   478 
   479 	updateActions();
   480 	return err;
   481 }
   482 
   483 ErrorCode VymModel::save (const SaveMode &savemode)
   484 {
   485 	QString tmpZipDir;
   486 	QString mapFileName;
   487 	QString safeFilePath;
   488 
   489 	ErrorCode err=success;
   490 
   491 	if (zipped)
   492 		// save as .xml
   493 		mapFileName=mapName+".xml";
   494 	else
   495 		// use name given by user, even if he chooses .doc
   496 		mapFileName=fileName;
   497 
   498 	// Look, if we should zip the data:
   499 	if (!zipped)
   500 	{
   501 		QMessageBox mb( vymName,
   502 			tr("The map %1\ndid not use the compressed "
   503 			"vym file format.\nWriting it uncompressed will also write images \n"
   504 			"and flags and thus may overwrite files in the "
   505 			"given directory\n\nDo you want to write the map").arg(filePath),
   506 			QMessageBox::Warning,
   507 			QMessageBox::Yes | QMessageBox::Default,
   508 			QMessageBox::No ,
   509 			QMessageBox::Cancel | QMessageBox::Escape);
   510 		mb.setButtonText( QMessageBox::Yes, tr("compressed (vym default)") );
   511 		mb.setButtonText( QMessageBox::No, tr("uncompressed") );
   512 		mb.setButtonText( QMessageBox::Cancel, tr("Cancel"));
   513 		switch( mb.exec() ) 
   514 		{
   515 			case QMessageBox::Yes:
   516 				// save compressed (default file format)
   517 				zipped=true;
   518 				break;
   519 			case QMessageBox::No:
   520 				// save uncompressed
   521 				zipped=false;
   522 				break;
   523 			case QMessageBox::Cancel:
   524 				// do nothing
   525 				return aborted;
   526 				break;
   527 		}
   528 	}
   529 
   530 	// First backup existing file, we 
   531 	// don't want to add to old zip archives
   532 	QFile f(destPath);
   533 	if (f.exists())
   534 	{
   535 		if ( settings.value ("/mapeditor/writeBackupFile").toBool())
   536 		{
   537 			QString backupFileName(destPath + "~");
   538 			QFile backupFile(backupFileName);
   539 			if (backupFile.exists() && !backupFile.remove())
   540 			{
   541 				QMessageBox::warning(0, tr("Save Error"),
   542 									 tr("%1\ncould not be removed before saving").arg(backupFileName));
   543 			}
   544 			else if (!f.rename(backupFileName))
   545 			{
   546 				QMessageBox::warning(0, tr("Save Error"),
   547 									 tr("%1\ncould not be renamed before saving").arg(destPath));
   548 			}
   549 		}
   550 	}
   551 
   552 	if (zipped)
   553 	{
   554 		// Create temporary directory for packing
   555 		bool ok;
   556 		tmpZipDir=makeTmpDir (ok,"vym-zip");
   557 		if (!ok)
   558 		{
   559 			QMessageBox::critical( 0, tr( "Critical Load Error" ),
   560 			   tr("Couldn't create temporary directory before save\n"));
   561 			return aborted; 
   562 		}
   563 
   564 		safeFilePath=filePath;
   565 		setFilePath (tmpZipDir+"/"+ mapName+ ".xml", safeFilePath);
   566 	} // zipped
   567 
   568 	// Create mapName and fileDir
   569 	makeSubDirs (fileDir);
   570 
   571 	QString saveFile;
   572 	if (savemode==CompleteMap || selection.isEmpty())
   573 	{
   574 		// Save complete map
   575 		saveFile=saveToDir (fileDir,mapName+"-",true,QPointF(),NULL);
   576 		mapChanged=false;
   577 		mapUnsaved=false;
   578 		autosaveTimer->stop();
   579 	}
   580 	else	
   581 	{
   582 		// Save part of map
   583 		if (selection.type()==Selection::FloatImage)
   584 			saveFloatImage();
   585 		else	
   586 			saveFile=saveToDir (fileDir,mapName+"-",true,QPointF(),selection.getBranch());	
   587 		// TODO take care of multiselections
   588 	}	
   589 
   590 	if (!saveStringToDisk(fileDir+mapFileName,saveFile))
   591 	{
   592 		err=aborted;
   593 		qWarning ("ME::saveStringToDisk failed!");
   594 	}
   595 
   596 	if (zipped)
   597 	{
   598 		// zip
   599 		if (err==success) err=zipDir (tmpZipDir,destPath);
   600 
   601 		// Delete tmpDir
   602 		removeDir (QDir(tmpZipDir));
   603 
   604 		// Restore original filepath outside of tmp zip dir
   605 		setFilePath (safeFilePath);
   606 	}
   607 
   608 	updateActions();
   609 	fileChangedTime=QFileInfo (destPath).lastModified();
   610 	return err;
   611 }
   612 
   613 void VymModel::addMapReplaceInt(const QString &undoSel, const QString &path)
   614 {
   615 	QString pathDir=path.left(path.findRev("/"));
   616 	QDir d(pathDir);
   617 	QFile file (path);
   618 
   619 	if (d.exists() )
   620 	{
   621 		// We need to parse saved XML data
   622 		parseVYMHandler handler;
   623 		QXmlInputSource source( file);
   624 		QXmlSimpleReader reader;
   625 		reader.setContentHandler( &handler );
   626 		reader.setErrorHandler( &handler );
   627 		handler.setModel ( this);
   628 		handler.setTmpDir ( pathDir );	// needed to load files with rel. path
   629 		if (undoSel.isEmpty())
   630 		{
   631 			unselect();
   632 			clear();
   633 			handler.setLoadMode (NewMap);
   634 		} else	
   635 		{
   636 			select (undoSel);
   637 			handler.setLoadMode (ImportReplace);
   638 		}	
   639 		blockReposition=true;
   640 		bool ok = reader.parse( source );
   641 		blockReposition=false;
   642 		if (! ok ) 
   643 		{	
   644 			// This should never ever happen
   645 			QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
   646 								    handler.errorProtocol());
   647 		}
   648 	} else	
   649 		QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
   650 }
   651 
   652 void VymModel::addMapInsertInt (const QString &path, int pos)
   653 {
   654 	BranchObj *sel=selection.getBranch();
   655 	if (sel)
   656 	{
   657 		QString pathDir=path.left(path.findRev("/"));
   658 		QDir d(pathDir);
   659 		QFile file (path);
   660 
   661 		if (d.exists() )
   662 		{
   663 			// We need to parse saved XML data
   664 			parseVYMHandler handler;
   665 			QXmlInputSource source( file);
   666 			QXmlSimpleReader reader;
   667 			reader.setContentHandler( &handler );
   668 			reader.setErrorHandler( &handler );
   669 			handler.setModel (this);
   670 			handler.setTmpDir ( pathDir );	// needed to load files with rel. path
   671 			handler.setLoadMode (ImportAdd);
   672 			blockReposition=true;
   673 			bool ok = reader.parse( source );
   674 			blockReposition=false;
   675 			if (! ok ) 
   676 			{	
   677 				// This should never ever happen
   678 				QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
   679 										handler.errorProtocol());
   680 			}
   681 			if (sel->getDepth()>0)
   682 				sel->getLastBranch()->linkTo (sel,pos);
   683 		} else	
   684 			QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
   685 	}		
   686 }
   687 
   688 FloatImageObj* VymModel::loadFloatImageInt (QString fn)
   689 {
   690 	BranchObj *bo=selection.getBranch();
   691 	if (bo)
   692 	{
   693 		FloatImageObj *fio;
   694 		bo->addFloatImage();
   695 		fio=bo->getLastFloatImage();
   696 		fio->load(fn);
   697 		reposition();
   698 		// FIXME VM needed? scene()->update();
   699 		return fio;
   700 	}
   701 	return NULL;
   702 }	
   703 
   704 void VymModel::loadFloatImage ()
   705 {
   706 	BranchObj *bo=selection.getBranch();
   707 	if (bo)
   708 	{
   709 
   710 		Q3FileDialog *fd=new Q3FileDialog( NULL);
   711 		fd->setMode (Q3FileDialog::ExistingFiles);
   712 		fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
   713 		ImagePreview *p =new ImagePreview (fd);
   714 		fd->setContentsPreviewEnabled( TRUE );
   715 		fd->setContentsPreview( p, p );
   716 		fd->setPreviewMode( Q3FileDialog::Contents );
   717 		fd->setCaption(vymName+" - " +tr("Load image"));
   718 		fd->setDir (lastImageDir);
   719 		fd->show();
   720 
   721 		if ( fd->exec() == QDialog::Accepted )
   722 		{
   723 			// TODO loadFIO in QT4 use:	lastImageDir=fd->directory();
   724 			lastImageDir=QDir (fd->dirPath());
   725 			QString s;
   726 			FloatImageObj *fio;
   727 			for (int j=0; j<fd->selectedFiles().count(); j++)
   728 			{
   729 				s=fd->selectedFiles().at(j);
   730 				fio=loadFloatImageInt (s);
   731 				if (fio)
   732 					saveState(
   733 						(LinkableMapObj*)fio,
   734 						"delete ()",
   735 						bo, 
   736 						QString ("loadImage (%1)").arg(s ),
   737 						QString("Add image %1 to %2").arg(s).arg(getObjectName(bo))
   738 					);
   739 				else
   740 					// TODO loadFIO error handling
   741 					qWarning ("Failed to load "+s);
   742 			}
   743 		}
   744 		delete (p);
   745 		delete (fd);
   746 	}
   747 }
   748 
   749 void VymModel::saveFloatImageInt  (FloatImageObj *fio, const QString &type, const QString &fn)
   750 {
   751 	fio->save (fn,type);
   752 }
   753 
   754 void VymModel::saveFloatImage ()
   755 {
   756 	FloatImageObj *fio=selection.getFloatImage();
   757 	if (fio)
   758 	{
   759 		QFileDialog *fd=new QFileDialog( NULL);
   760 		fd->setFilters (imageIO.getFilters());
   761 		fd->setCaption(vymName+" - " +tr("Save image"));
   762 		fd->setFileMode( QFileDialog::AnyFile );
   763 		fd->setDirectory (lastImageDir);
   764 //		fd->setSelection (fio->getOriginalFilename());
   765 		fd->show();
   766 
   767 		QString fn;
   768 		if ( fd->exec() == QDialog::Accepted && fd->selectedFiles().count()==1)
   769 		{
   770 			fn=fd->selectedFiles().at(0);
   771 			if (QFile (fn).exists() )
   772 			{
   773 				QMessageBox mb( vymName,
   774 					tr("The file %1 exists already.\n"
   775 					"Do you want to overwrite it?").arg(fn),
   776 				QMessageBox::Warning,
   777 				QMessageBox::Yes | QMessageBox::Default,
   778 				QMessageBox::Cancel | QMessageBox::Escape,
   779 				QMessageBox::NoButton );
   780 
   781 				mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
   782 				mb.setButtonText( QMessageBox::No, tr("Cancel"));
   783 				switch( mb.exec() ) 
   784 				{
   785 					case QMessageBox::Yes:
   786 						// save 
   787 						break;
   788 					case QMessageBox::Cancel:
   789 						// do nothing
   790 						delete (fd);
   791 						return;
   792 						break;
   793 				}
   794 			}
   795 			saveFloatImageInt (fio,fd->selectedFilter(),fn );
   796 		}
   797 		delete (fd);
   798 	}
   799 }
   800 
   801 
   802 void VymModel::importDirInt(BranchObj *dst, QDir d)
   803 {
   804 	BranchObj *bo=selection.getBranch();
   805 	if (bo)
   806 	{
   807 		// Traverse directories
   808 		d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
   809 		QFileInfoList list = d.entryInfoList();
   810 		QFileInfo fi;
   811 
   812 		for (int i = 0; i < list.size(); ++i) 
   813 		{
   814 			fi=list.at(i);
   815 			if (fi.fileName() != "." && fi.fileName() != ".." )
   816 			{
   817 				dst->addBranch();
   818 				bo=dst->getLastBranch();
   819 				bo->setHeading (fi.fileName() );
   820 				bo->setColor (QColor("blue"));
   821 				bo->toggleScroll();
   822 				if ( !d.cd(fi.fileName()) ) 
   823 					QMessageBox::critical (0,tr("Critical Import Error"),tr("Cannot find the directory %1").arg(fi.fileName()));
   824 				else 
   825 				{
   826 					// Recursively add subdirs
   827 					importDirInt (bo,d);
   828 					d.cdUp();
   829 				}
   830 			}	
   831 		}		
   832 		// Traverse files
   833 		d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
   834 		list = d.entryInfoList();
   835 
   836 		for (int i = 0; i < list.size(); ++i) 
   837 		{
   838 			fi=list.at(i);
   839 			dst->addBranch();
   840 			bo=dst->getLastBranch();
   841 			bo->setHeading (fi.fileName() );
   842 			bo->setColor (QColor("black"));
   843 			if (fi.fileName().right(4) == ".vym" )
   844 				bo->setVymLink (fi.filePath());
   845 		}	
   846 	}		
   847 }
   848 
   849 void VymModel::importDirInt (const QString &s)
   850 {
   851 	BranchObj *bo=selection.getBranch();
   852 	if (bo)
   853 	{
   854 		saveStateChangingPart (bo,bo,QString ("importDir (\"%1\")").arg(s),QString("Import directory structure from %1").arg(s));
   855 
   856 		QDir d(s);
   857 		importDirInt (bo,d);
   858 	}
   859 }	
   860 
   861 void VymModel::importDir()
   862 {
   863 	BranchObj *bo=selection.getBranch();
   864 	if (bo)
   865 	{
   866 		QStringList filters;
   867 		filters <<"VYM map (*.vym)";
   868 		QFileDialog *fd=new QFileDialog( NULL,vymName+ " - " +tr("Choose directory structure to import"));
   869 		fd->setMode (QFileDialog::DirectoryOnly);
   870 		fd->setFilters (filters);
   871 		fd->setCaption(vymName+" - " +tr("Choose directory structure to import"));
   872 		fd->show();
   873 
   874 		QString fn;
   875 		if ( fd->exec() == QDialog::Accepted )
   876 		{
   877 			importDirInt (fd->selectedFile() );
   878 			reposition();
   879 			//FIXME VM needed? scene()->update();
   880 		}
   881 	}	
   882 }
   883 
   884 
   885 void VymModel::autosave()
   886 {
   887 	QDateTime now=QDateTime().currentDateTime();
   888 
   889 	// Disable autosave, while we have gone back in history
   890 	int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
   891 	if (redosAvail>0) return;
   892 
   893 	// Also disable autosave for new map without filename
   894 	if (filePath.isEmpty()) return;
   895 
   896 
   897 	if (mapUnsaved &&mapChanged && settings.value ("/autosave/use",true).toBool() )
   898 	{
   899 		if (QFileInfo(filePath).lastModified()<=fileChangedTime) 
   900 			mainWindow->fileSave (this);
   901 		else
   902 			if (debug)
   903 				cout <<"  ME::autosave  rejected, file on disk is newer than last save.\n"; 
   904 
   905 	}	
   906 }
   907 
   908 void VymModel::fileChanged()
   909 {
   910 	// Check if file on disk has changed meanwhile
   911 	if (!filePath.isEmpty())
   912 	{
   913 		QDateTime tmod=QFileInfo (filePath).lastModified();
   914 		if (tmod>fileChangedTime)
   915 		{
   916 			// FIXME VM switch to current mapeditor and finish lineedits...
   917 			QMessageBox mb( vymName,
   918 				tr("The file of the map  on disk has changed:\n\n"  
   919 				   "   %1\n\nDo you want to reload that map with the new file?").arg(filePath),
   920 				QMessageBox::Question,
   921 				QMessageBox::Yes ,
   922 				QMessageBox::Cancel | QMessageBox::Default,
   923 				QMessageBox::NoButton );
   924 
   925 			mb.setButtonText( QMessageBox::Yes, tr("Reload"));
   926 			mb.setButtonText( QMessageBox::No, tr("Ignore"));
   927 			switch( mb.exec() ) 
   928 			{
   929 				case QMessageBox::Yes:
   930 					// Reload map
   931 					load (filePath,NewMap,fileType);
   932 		        case QMessageBox::Cancel:
   933 					fileChangedTime=tmod; // allow autosave to overwrite newer file!
   934 			}
   935 		}
   936 	}	
   937 }
   938 
   939 bool VymModel::isDefault()
   940 {
   941     return mapDefault;
   942 }
   943 
   944 void VymModel::makeDefault()
   945 {
   946 	mapChanged=false;
   947 	mapDefault=true;
   948 }
   949 
   950 bool VymModel::hasChanged()
   951 {
   952     return mapChanged;
   953 }
   954 
   955 void VymModel::setChanged()
   956 {
   957 	if (!mapChanged)
   958 		autosaveTimer->start(settings.value("/autosave/ms/",300000).toInt());
   959 	mapChanged=true;
   960 	mapDefault=false;
   961 	mapUnsaved=true;
   962 	findReset();
   963 }
   964 
   965 
   966 QString VymModel::getObjectName (const LinkableMapObj *lmo)
   967 {
   968 	QString s;
   969 	if (!lmo) return QString("Error: NULL has no name!");
   970 
   971 	if ((typeid(*lmo) == typeid(BranchObj) ||
   972 				      typeid(*lmo) == typeid(MapCenterObj))) 
   973 	{
   974 		
   975 		s=(((BranchObj*)lmo)->getHeading());
   976 		if (s=="") s="unnamed";
   977 		return QString("branch (%1)").arg(s);
   978 	}	
   979 	if ((typeid(*lmo) == typeid(FloatImageObj) ))
   980 		return QString ("floatimage [%1]").arg(((FloatImageObj*)lmo)->getOriginalFilename());
   981 	return QString("Unknown type has no name!");
   982 }
   983 
   984 void VymModel::redo()
   985 {
   986 	// Can we undo at all?
   987 	if (redosAvail<1) return;
   988 
   989 	bool blockSaveStateOrg=blockSaveState;
   990 	blockSaveState=true;
   991 	
   992 	redosAvail--;
   993 
   994 	if (undosAvail<stepsTotal) undosAvail++;
   995 	curStep++;
   996 	if (curStep>stepsTotal) curStep=1;
   997 	QString undoCommand=  undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
   998 	QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
   999 	QString redoCommand=  undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
  1000 	QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
  1001 	QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
  1002 	QString version=undoSet.readEntry ("/history/version");
  1003 
  1004 	/* TODO Maybe check for version, if we save the history
  1005 	if (!checkVersion(version))
  1006 		QMessageBox::warning(0,tr("Warning"),
  1007 			tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
  1008 	*/ 
  1009 
  1010 	// Find out current undo directory
  1011 	QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
  1012 
  1013 	if (debug)
  1014 	{
  1015 		cout << "VymModel::redo() begin\n";
  1016 		cout << "    undosAvail="<<undosAvail<<endl;
  1017 		cout << "    redosAvail="<<redosAvail<<endl;
  1018 		cout << "       curStep="<<curStep<<endl;
  1019 		cout << "    ---------------------------"<<endl;
  1020 		cout << "    comment="<<comment.toStdString()<<endl;
  1021 		cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  1022 		cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  1023 		cout << "    redoCom="<<redoCommand.toStdString()<<endl;
  1024 		cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  1025 		cout << "    ---------------------------"<<endl<<endl;
  1026 	}
  1027 
  1028 	// select  object before redo
  1029 	if (!redoSelection.isEmpty())
  1030 		select (redoSelection);
  1031 
  1032 
  1033 	parseAtom (redoCommand);
  1034 	reposition();
  1035 
  1036 	blockSaveState=blockSaveStateOrg;
  1037 
  1038 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1039 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1040 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1041 	undoSet.writeSettings(histPath);
  1042 
  1043 	mainWindow->updateHistory (undoSet);
  1044 	updateActions();
  1045 
  1046 	/* TODO remove testing
  1047 	cout << "ME::redo() end\n";
  1048 	cout << "    undosAvail="<<undosAvail<<endl;
  1049 	cout << "    redosAvail="<<redosAvail<<endl;
  1050 	cout << "       curStep="<<curStep<<endl;
  1051 	cout << "    ---------------------------"<<endl<<endl;
  1052 	*/
  1053 
  1054 
  1055 }
  1056 
  1057 bool VymModel::isRedoAvailable()
  1058 {
  1059 	if (undoSet.readNumEntry("/history/redosAvail",0)>0)
  1060 		return true;
  1061 	else	
  1062 		return false;
  1063 }
  1064 
  1065 void VymModel::undo()
  1066 {
  1067 	// Can we undo at all?
  1068 	if (undosAvail<1) return;
  1069 
  1070 	mainWindow->statusMessage (tr("Autosave disabled during undo."));
  1071 
  1072 	bool blockSaveStateOrg=blockSaveState;
  1073 	blockSaveState=true;
  1074 	
  1075 	QString undoCommand=  undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
  1076 	QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
  1077 	QString redoCommand=  undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
  1078 	QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
  1079 	QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
  1080 	QString version=undoSet.readEntry ("/history/version");
  1081 
  1082 	/* TODO Maybe check for version, if we save the history
  1083 	if (!checkVersion(version))
  1084 		QMessageBox::warning(0,tr("Warning"),
  1085 			tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
  1086 	*/
  1087 
  1088 	// Find out current undo directory
  1089 	QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
  1090 
  1091 	// select  object before undo
  1092 	if (!undoSelection.isEmpty())
  1093 		select (undoSelection);
  1094 
  1095 	if (debug)
  1096 	{
  1097 		cout << "VymModel::undo() begin\n";
  1098 		cout << "    undosAvail="<<undosAvail<<endl;
  1099 		cout << "    redosAvail="<<redosAvail<<endl;
  1100 		cout << "       curStep="<<curStep<<endl;
  1101 		cout << "    ---------------------------"<<endl;
  1102 		cout << "    comment="<<comment.toStdString()<<endl;
  1103 		cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  1104 		cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  1105 		cout << "    redoCom="<<redoCommand.toStdString()<<endl;
  1106 		cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  1107 		cout << "    ---------------------------"<<endl<<endl;
  1108 	}	
  1109 	parseAtom (undoCommand);
  1110 	reposition();
  1111 
  1112 	undosAvail--;
  1113 	curStep--; 
  1114 	if (curStep<1) curStep=stepsTotal;
  1115 
  1116 	redosAvail++;
  1117 
  1118 	blockSaveState=blockSaveStateOrg;
  1119 /* TODO remove testing
  1120 	cout << "VymModel::undo() end\n";
  1121 	cout << "    undosAvail="<<undosAvail<<endl;
  1122 	cout << "    redosAvail="<<redosAvail<<endl;
  1123 	cout << "       curStep="<<curStep<<endl;
  1124 	cout << "    ---------------------------"<<endl<<endl;
  1125 */
  1126 
  1127 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1128 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1129 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1130 	undoSet.writeSettings(histPath);
  1131 
  1132 	mainWindow->updateHistory (undoSet);
  1133 	updateActions();
  1134 	selection.update();
  1135 	ensureSelectionVisible();
  1136 }
  1137 
  1138 bool VymModel::isUndoAvailable()
  1139 {
  1140 	if (undoSet.readNumEntry("/history/undosAvail",0)>0)
  1141 		return true;
  1142 	else	
  1143 		return false;
  1144 }
  1145 
  1146 void VymModel::gotoHistoryStep (int i)
  1147 {
  1148 	// Restore variables
  1149 	int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
  1150 	int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
  1151 
  1152 	if (i<0) i=undosAvail+redosAvail;
  1153 
  1154 	// Clicking above current step makes us undo things
  1155 	if (i<undosAvail) 
  1156 	{	
  1157 		for (int j=0; j<undosAvail-i; j++) undo();
  1158 		return;
  1159 	}	
  1160 	// Clicking below current step makes us redo things
  1161 	if (i>undosAvail) 
  1162 		for (int j=undosAvail; j<i; j++) 
  1163 		{
  1164 			if (debug) cout << "VymModel::gotoHistoryStep redo "<<j<<"/"<<undosAvail<<" i="<<i<<endl;
  1165 			redo();
  1166 		}
  1167 
  1168 	// And ignore clicking the current row ;-)	
  1169 }
  1170 
  1171 
  1172 QString VymModel::getHistoryPath()
  1173 {
  1174 	QString histName(QString("history-%1").arg(curStep));
  1175 	return (tmpMapDir+"/"+histName);
  1176 }
  1177 
  1178 void VymModel::saveState(const SaveMode &savemode, const QString &undoSelection, const QString &undoCom, const QString &redoSelection, const QString &redoCom, const QString &comment, LinkableMapObj *saveSel)
  1179 {
  1180 	sendData(redoCom);	//FIXME testing
  1181 
  1182 	// Main saveState
  1183 
  1184 
  1185 	if (blockSaveState) return;
  1186 
  1187 	if (debug) cout << "ME::saveState() for  "<<qPrintable (mapName)<<endl;
  1188 	
  1189 	// Find out current undo directory
  1190 	if (undosAvail<stepsTotal) undosAvail++;
  1191 	curStep++;
  1192 	if (curStep>stepsTotal) curStep=1;
  1193 	
  1194 	QString backupXML="";
  1195 	QString histDir=getHistoryPath();
  1196 	QString bakMapPath=histDir+"/map.xml";
  1197 
  1198 	// Create histDir if not available
  1199 	QDir d(histDir);
  1200 	if (!d.exists()) 
  1201 		makeSubDirs (histDir);
  1202 
  1203 	// Save depending on how much needs to be saved	
  1204 	if (saveSel)
  1205 		backupXML=saveToDir (histDir,mapName+"-",false, QPointF (),saveSel);
  1206 		
  1207 	QString undoCommand="";
  1208 	if (savemode==UndoCommand)
  1209 	{
  1210 		undoCommand=undoCom;
  1211 	}	
  1212 	else if (savemode==PartOfMap )
  1213 	{
  1214 		undoCommand=undoCom;
  1215 		undoCommand.replace ("PATH",bakMapPath);
  1216 	}
  1217 
  1218 	if (!backupXML.isEmpty())
  1219 		// Write XML Data to disk
  1220 		saveStringToDisk (bakMapPath,backupXML);
  1221 
  1222 	// We would have to save all actions in a tree, to keep track of 
  1223 	// possible redos after a action. Possible, but we are too lazy: forget about redos.
  1224 	redosAvail=0;
  1225 
  1226 	// Write the current state to disk
  1227 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1228 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1229 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1230 	undoSet.setEntry (QString("/history/step-%1/undoCommand").arg(curStep),undoCommand);
  1231 	undoSet.setEntry (QString("/history/step-%1/undoSelection").arg(curStep),undoSelection);
  1232 	undoSet.setEntry (QString("/history/step-%1/redoCommand").arg(curStep),redoCom);
  1233 	undoSet.setEntry (QString("/history/step-%1/redoSelection").arg(curStep),redoSelection);
  1234 	undoSet.setEntry (QString("/history/step-%1/comment").arg(curStep),comment);
  1235 	undoSet.setEntry (QString("/history/version"),vymVersion);
  1236 	undoSet.writeSettings(histPath);
  1237 
  1238 	if (debug)
  1239 	{
  1240 		// TODO remove after testing
  1241 		//cout << "          into="<< histPath.toStdString()<<endl;
  1242 		cout << "    stepsTotal="<<stepsTotal<<
  1243 		", undosAvail="<<undosAvail<<
  1244 		", redosAvail="<<redosAvail<<
  1245 		", curStep="<<curStep<<endl;
  1246 		cout << "    ---------------------------"<<endl;
  1247 		cout << "    comment="<<comment.toStdString()<<endl;
  1248 		cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  1249 		cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  1250 		cout << "    redoCom="<<redoCom.toStdString()<<endl;
  1251 		cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  1252 		if (saveSel) cout << "    saveSel="<<qPrintable (getSelectString(saveSel))<<endl;
  1253 		cout << "    ---------------------------"<<endl;
  1254 	}
  1255 
  1256 	mainWindow->updateHistory (undoSet);
  1257 	setChanged();
  1258 	updateActions();
  1259 }
  1260 
  1261 
  1262 void VymModel::saveStateChangingPart(LinkableMapObj *undoSel, LinkableMapObj* redoSel, const QString &rc, const QString &comment)
  1263 {
  1264 	// save the selected part of the map, Undo will replace part of map 
  1265 	QString undoSelection="";
  1266 	if (undoSel)
  1267 		undoSelection=getSelectString(undoSel);
  1268 	else
  1269 		qWarning ("VymModel::saveStateChangingPart  no undoSel given!");
  1270 	QString redoSelection="";
  1271 	if (redoSel)
  1272 		redoSelection=getSelectString(undoSel);
  1273 	else
  1274 		qWarning ("VymModel::saveStateChangingPart  no redoSel given!");
  1275 		
  1276 
  1277 	saveState (PartOfMap,
  1278 		undoSelection, "addMapReplace (\"PATH\")",
  1279 		redoSelection, rc, 
  1280 		comment, 
  1281 		undoSel);
  1282 }
  1283 
  1284 void VymModel::saveStateRemovingPart(LinkableMapObj *redoSel, const QString &comment)
  1285 {
  1286 	if (!redoSel)
  1287 	{
  1288 		qWarning ("VymModel::saveStateRemovingPart  no redoSel given!");
  1289 		return;
  1290 	}
  1291 	QString undoSelection=getSelectString (redoSel->getParObj());
  1292 	QString redoSelection=getSelectString(redoSel);
  1293 	if (typeid(*redoSel) == typeid(BranchObj)  ) 
  1294 	{
  1295 		// save the selected branch of the map, Undo will insert part of map 
  1296 		saveState (PartOfMap,
  1297 			undoSelection, QString("addMapInsert (\"PATH\",%1)").arg(((BranchObj*)redoSel)->getNum()),
  1298 			redoSelection, "delete ()", 
  1299 			comment, 
  1300 			redoSel);
  1301 	}
  1302 }
  1303 
  1304 
  1305 void VymModel::saveState(LinkableMapObj *undoSel, const QString &uc, LinkableMapObj *redoSel, const QString &rc, const QString &comment) 
  1306 {
  1307 	// "Normal" savestate: save commands, selections and comment
  1308 	// so just save commands for undo and redo
  1309 	// and use current selection
  1310 
  1311 	QString redoSelection="";
  1312 	if (redoSel) redoSelection=getSelectString(redoSel);
  1313 	QString undoSelection="";
  1314 	if (undoSel) undoSelection=getSelectString(undoSel);
  1315 
  1316 	saveState (UndoCommand,
  1317 		undoSelection, uc,
  1318 		redoSelection, rc, 
  1319 		comment, 
  1320 		NULL);
  1321 }
  1322 
  1323 void VymModel::saveState(const QString &undoSel, const QString &uc, const QString &redoSel, const QString &rc, const QString &comment) 
  1324 {
  1325 	// "Normal" savestate: save commands, selections and comment
  1326 	// so just save commands for undo and redo
  1327 	// and use current selection
  1328 	saveState (UndoCommand,
  1329 		undoSel, uc,
  1330 		redoSel, rc, 
  1331 		comment, 
  1332 		NULL);
  1333 }
  1334 
  1335 void VymModel::saveState(const QString &uc, const QString &rc, const QString &comment) 
  1336 {
  1337 	// "Normal" savestate applied to model (no selection needed): 
  1338 	// save commands  and comment
  1339 	saveState (UndoCommand,
  1340 		NULL, uc,
  1341 		NULL, rc, 
  1342 		comment, 
  1343 		NULL);
  1344 }
  1345 
  1346 
  1347 QGraphicsScene* VymModel::getScene ()
  1348 {
  1349 	return mapScene;
  1350 }
  1351 
  1352 BranchObj* VymModel::first()
  1353 {
  1354 	if (mapCenters.count()>0) 
  1355 		return mapCenters.first();
  1356 	else	
  1357 		return NULL;
  1358 }
  1359 	
  1360 BranchObj* VymModel::next(BranchObj *bo_start)
  1361 {
  1362 	BranchObj *rbo;
  1363 	BranchObj *bo=bo_start;
  1364 	if (bo)
  1365 	{
  1366 		// Try to find next branch in current MapCenter
  1367 		rbo=bo->next();
  1368 		if (rbo) return rbo;
  1369 
  1370 		// Try to find MapCenter of bo
  1371 		while (bo->getDepth()>0) bo=(BranchObj*)bo->getParObj();
  1372 
  1373 		// Try to find next MapCenter
  1374 		int i=mapCenters.indexOf ((MapCenterObj*)bo);
  1375 		if (i+2 > mapCenters.count() || i<0) return NULL;
  1376 		if (mapCenters.at(i+1)!=bo_start)
  1377 			return mapCenters.at(i+1);
  1378 	} 
  1379 	return NULL;
  1380 }
  1381 
  1382 LinkableMapObj* VymModel::findMapObj(QPointF p, LinkableMapObj *excludeLMO)
  1383 {
  1384 	LinkableMapObj *lmo;
  1385 
  1386 	for (int i=0;i<mapCenters.count(); i++)
  1387 	{
  1388 		lmo=mapCenters.at(i)->findMapObj (p,excludeLMO);
  1389 		if (lmo) return lmo;
  1390 	}
  1391 	return NULL;
  1392 }
  1393 
  1394 LinkableMapObj* VymModel::findObjBySelect(const QString &s)
  1395 {
  1396 	LinkableMapObj *lmo;
  1397 	if (!s.isEmpty() )
  1398 	{
  1399 		QString part;
  1400 		QString typ;
  1401 		QString num;
  1402 		part=s.section(",",0,0);
  1403 		typ=part.left (2);
  1404 		num=part.right(part.length() - 3);
  1405 		if (typ=="mc" && num.toInt()>=0 && num.toInt() <mapCenters.count() )
  1406 			return mapCenters.at(num.toInt() );
  1407 	}		
  1408 
  1409 	for (int i=0; i<mapCenters.count(); i++)
  1410 	{
  1411 		lmo=mapCenters.at(i)->findObjBySelect(s);
  1412 		if (lmo) return lmo;
  1413 	}	
  1414 	return NULL;
  1415 }
  1416 
  1417 LinkableMapObj* VymModel::findID (const QString &s)
  1418 {
  1419 	LinkableMapObj *lmo;
  1420 	for (int i=0; i<mapCenters.count(); i++)
  1421 	{
  1422 		lmo=mapCenters.at(i)->findID (s);
  1423 		if (lmo) return lmo;
  1424 	}	
  1425 	return NULL;
  1426 }
  1427 
  1428 QString VymModel::saveToDir (const QString &tmpdir,const QString &prefix, int verbose, const QPointF &offset)
  1429 {
  1430     QString s;
  1431 
  1432 	for (int i=0; i<mapCenters.count(); i++)
  1433 		s+=mapCenters.at(i)->saveToDir (tmpdir,prefix,verbose,offset);
  1434     return s;
  1435 }
  1436 
  1437 //////////////////////////////////////////////
  1438 // Interface 
  1439 //////////////////////////////////////////////
  1440 void VymModel::setVersion (const QString &s)
  1441 {
  1442 	version=s;
  1443 }
  1444 
  1445 void VymModel::setAuthor (const QString &s)
  1446 {
  1447 	saveState (
  1448 		QString ("setMapAuthor (\"%1\")").arg(author),
  1449 		QString ("setMapAuthor (\"%1\")").arg(s),
  1450 		QString ("Set author of map to \"%1\"").arg(s)
  1451 	);
  1452 
  1453 	author=s;
  1454 }
  1455 
  1456 QString VymModel::getAuthor()
  1457 {
  1458 	return author;
  1459 }
  1460 
  1461 void VymModel::setComment (const QString &s)
  1462 {
  1463 	saveState (
  1464 		QString ("setMapComment (\"%1\")").arg(comment),
  1465 		QString ("setMapComment (\"%1\")").arg(s),
  1466 		QString ("Set comment of map")
  1467 	);
  1468 
  1469 	comment=s;
  1470 }
  1471 
  1472 QString VymModel::getComment ()
  1473 {
  1474 	return comment;
  1475 }
  1476 
  1477 QString VymModel::getDate ()
  1478 {
  1479 	return QDate::currentDate().toString ("yyyy-MM-dd");
  1480 }
  1481 
  1482 void VymModel::setHeading(const QString &s)
  1483 {
  1484 	BranchObj *sel=selection.getBranch();
  1485 	if (sel)
  1486 	{
  1487 		saveState(
  1488 			sel,
  1489 			"setHeading (\""+sel->getHeading()+"\")", 
  1490 			sel,
  1491 			"setHeading (\""+s+"\")", 
  1492 			QString("Set heading of %1 to \"%2\"").arg(getObjectName(sel)).arg(s) );
  1493 		sel->setHeading(s );
  1494 		TreeItem *ti=selection.getBranchItem();
  1495 		if (ti)
  1496 		{
  1497 			ti->setHeading (s);
  1498 			//FIXME VM ix is wrong ModelIndex below, ix2 is (hopefully) correct:
  1499 			QModelIndex ix=index( ti->row(), ti->column(), index (0,0,QModelIndex()) );
  1500 			//FIXME VM testing only cout <<"VM::setHeading  s="<<s.toStdString()<<"  ti="<<ti<<"  r,c=("<<ti->row()<<","<<ti->column()<<")"<<endl;
  1501 			QModelIndex ix2=index (ti);
  1502 			emit (dataChanged ( ix2,ix2));
  1503 		}
  1504 		else
  1505 		{
  1506 			cout << "Warning: VM::setHeading ti==NULL\n";
  1507 		}
  1508 
  1509 		//cout <<"                (r,c)=("<<ix2.row()<<","<<ix2.column()<<")"<<endl;
  1510 
  1511 		reposition();
  1512 		selection.update();
  1513 		ensureSelectionVisible();
  1514 	}
  1515 }
  1516 
  1517 void VymModel::setHeadingInt(const QString &s)
  1518 {
  1519 	BranchObj *bo=selection.getBranch();
  1520 	if (bo)
  1521 	{
  1522 		bo->setHeading(s);
  1523 		reposition();
  1524 		selection.update();
  1525 		ensureSelectionVisible();
  1526 	}
  1527 }
  1528 
  1529 BranchObj* VymModel::findText (QString s, bool cs)
  1530 {
  1531 	QTextDocument::FindFlags flags=0;
  1532 	if (cs) flags=QTextDocument::FindCaseSensitively;
  1533 
  1534 	if (!itFind) 
  1535 	{	// Nothing found or new find process
  1536 		if (EOFind)
  1537 			// nothing found, start again
  1538 			EOFind=false;
  1539 		itFind=first();
  1540 	}	
  1541 	bool searching=true;
  1542 	bool foundNote=false;
  1543 	while (searching && !EOFind)
  1544 	{
  1545 		if (itFind)
  1546 		{
  1547 			// Searching in Note
  1548 			if (itFind->getNote().contains(s,cs))
  1549 			{
  1550 				if (selection.single()!=itFind) 
  1551 				{
  1552 					selection.select(itFind);
  1553 					ensureSelectionVisible();
  1554 				}
  1555 				if (textEditor->findText(s,flags)) 
  1556 				{
  1557 					searching=false;
  1558 					foundNote=true;
  1559 				}	
  1560 			}
  1561 			// Searching in Heading
  1562 			if (searching && itFind->getHeading().contains (s,cs) ) 
  1563 			{
  1564 				selection.select(itFind);
  1565 				ensureSelectionVisible();
  1566 				searching=false;
  1567 			}
  1568 		}	
  1569 		if (!foundNote)
  1570 		{
  1571 			itFind=next(itFind);
  1572 			if (!itFind) EOFind=true;
  1573 		}
  1574 	//cout <<"still searching...  "<<qPrintable( itFind->getHeading())<<endl;
  1575 	}	
  1576 	if (!searching)
  1577 		return selection.getBranch();
  1578 	else
  1579 		return NULL;
  1580 }
  1581 
  1582 void VymModel::findReset()
  1583 {	// Necessary if text to find changes during a find process
  1584 	itFind=NULL;
  1585 	EOFind=false;
  1586 }
  1587 
  1588 
  1589 
  1590 void VymModel::setScene (QGraphicsScene *s)
  1591 {
  1592 	mapScene=s;
  1593     init();	// Here we have a mapScene set, 
  1594 			// which is (still) needed to create MapCenters
  1595 }
  1596 
  1597 void VymModel::setURL(const QString &url)
  1598 {
  1599 	BranchObj *bo=selection.getBranch();
  1600 	if (bo)
  1601 	{
  1602 		QString oldurl=bo->getURL();
  1603 		bo->setURL (url);
  1604 		saveState (
  1605 			bo,
  1606 			QString ("setURL (\"%1\")").arg(oldurl),
  1607 			bo,
  1608 			QString ("setURL (\"%1\")").arg(url),
  1609 			QString ("set URL of %1 to %2").arg(getObjectName(bo)).arg(url)
  1610 		);
  1611 		updateActions();
  1612 		reposition();
  1613 		selection.update();
  1614 		ensureSelectionVisible();
  1615 	}
  1616 }	
  1617 
  1618 QString VymModel::getURL()
  1619 {
  1620 	BranchObj *bo=selection.getBranch();
  1621 	if (bo)
  1622 		return bo->getURL();
  1623 	else
  1624 		return "";
  1625 }
  1626 
  1627 QStringList VymModel::getURLs()
  1628 {
  1629 	QStringList urls;
  1630 	BranchObj *bo=selection.getBranch();
  1631 	if (bo)
  1632 	{		
  1633 		bo=bo->first();	
  1634 		while (bo) 
  1635 		{
  1636 			if (!bo->getURL().isEmpty()) urls.append( bo->getURL());
  1637 			bo=bo->next();
  1638 		}	
  1639 	}	
  1640 	return urls;
  1641 }
  1642 
  1643 void VymModel::linkFloatImageTo(const QString &dstString)	
  1644 {
  1645 	FloatImageObj *fio=selection.getFloatImage();
  1646 	if (fio)
  1647 	{
  1648 		BranchObj *dst=(BranchObj*)findObjBySelect(dstString);
  1649 		if (dst && (typeid(*dst)==typeid (BranchObj) || 
  1650 					typeid(*dst)==typeid (MapCenterObj)))
  1651 		{			
  1652 			LinkableMapObj *dstPar=dst->getParObj();
  1653 			QString parString=getSelectString(dstPar);
  1654 			QString fioPreSelectString=getSelectString(fio);
  1655 			QString fioPreParentSelectString=getSelectString (fio->getParObj());
  1656 			((BranchObj*)dst)->addFloatImage (fio);
  1657 			selection.unselect();
  1658 			((BranchObj*)(fio->getParObj()))->removeFloatImage (fio);
  1659 			fio=((BranchObj*)dst)->getLastFloatImage();
  1660 			fio->setRelPos();
  1661 			fio->reposition();
  1662 			selection.select(fio);
  1663 			saveState(
  1664 				getSelectString(fio),
  1665 				QString("linkTo (\"%1\")").arg(fioPreParentSelectString), 
  1666 				fioPreSelectString, 
  1667 				QString ("linkTo (\"%1\")").arg(dstString),
  1668 				QString ("Link floatimage to %1").arg(getObjectName(dst)));
  1669 		}
  1670 	}
  1671 }
  1672 
  1673 
  1674 void VymModel::setFrameType(const FrameObj::FrameType &t)
  1675 {
  1676 	BranchObj *bo=selection.getBranch();
  1677 	if (bo)
  1678 	{
  1679 		QString s=bo->getFrameTypeName();
  1680 		bo->setFrameType (t);
  1681 		saveState (bo, QString("setFrameType (\"%1\")").arg(s),
  1682 			bo, QString ("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),QString ("set type of frame to %1").arg(s));
  1683 		reposition();
  1684 		bo->updateLink();
  1685 	}
  1686 }
  1687 
  1688 void VymModel::setFrameType(const QString &s)	
  1689 {
  1690 	BranchObj *bo=selection.getBranch();
  1691 	if (bo)
  1692 	{
  1693 		saveState (bo, QString("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),
  1694 			bo, QString ("setFrameType (\"%1\")").arg(s),QString ("set type of frame to %1").arg(s));
  1695 		bo->setFrameType (s);
  1696 		reposition();
  1697 		bo->updateLink();
  1698 	}
  1699 }
  1700 
  1701 void VymModel::setFramePenColor(const QColor &c)	
  1702 {
  1703 	BranchObj *bo=selection.getBranch();
  1704 	if (bo)
  1705 	{
  1706 		saveState (bo, QString("setFramePenColor (\"%1\")").arg(bo->getFramePenColor().name() ),
  1707 			bo, QString ("setFramePenColor (\"%1\")").arg(c.name() ),QString ("set pen color of frame to %1").arg(c.name() ));
  1708 		bo->setFramePenColor (c);
  1709 	}	
  1710 }
  1711 
  1712 void VymModel::setFrameBrushColor(const QColor &c)	
  1713 {
  1714 	BranchObj *bo=selection.getBranch();
  1715 	if (bo)
  1716 	{
  1717 		saveState (bo, QString("setFrameBrushColor (\"%1\")").arg(bo->getFrameBrushColor().name() ),
  1718 			bo, QString ("setFrameBrushColor (\"%1\")").arg(c.name() ),QString ("set brush color of frame to %1").arg(c.name() ));
  1719 		bo->setFrameBrushColor (c);
  1720 	}	
  1721 }
  1722 
  1723 void VymModel::setFramePadding (const int &i)
  1724 {
  1725 	BranchObj *bo=selection.getBranch();
  1726 	if (bo)
  1727 	{
  1728 		saveState (bo, QString("setFramePadding (\"%1\")").arg(bo->getFramePadding() ),
  1729 			bo, QString ("setFramePadding (\"%1\")").arg(i),QString ("set brush color of frame to %1").arg(i));
  1730 		bo->setFramePadding (i);
  1731 		reposition();
  1732 		bo->updateLink();
  1733 	}	
  1734 }
  1735 
  1736 void VymModel::setFrameBorderWidth(const int &i)
  1737 {
  1738 	BranchObj *bo=selection.getBranch();
  1739 	if (bo)
  1740 	{
  1741 		saveState (bo, QString("setFrameBorderWidth (\"%1\")").arg(bo->getFrameBorderWidth() ),
  1742 			bo, QString ("setFrameBorderWidth (\"%1\")").arg(i),QString ("set border width of frame to %1").arg(i));
  1743 		bo->setFrameBorderWidth (i);
  1744 		reposition();
  1745 		bo->updateLink();
  1746 	}	
  1747 }
  1748 
  1749 void VymModel::setIncludeImagesVer(bool b)	
  1750 {
  1751 	BranchObj *bo=selection.getBranch();
  1752 	if (bo)
  1753 	{
  1754 		QString u= b ? "false" : "true";
  1755 		QString r=!b ? "false" : "true";
  1756 		
  1757 		saveState(
  1758 			bo,
  1759 			QString("setIncludeImagesVertically (%1)").arg(u),
  1760 			bo, 
  1761 			QString("setIncludeImagesVertically (%1)").arg(r),
  1762 			QString("Include images vertically in %1").arg(getObjectName(bo))
  1763 		);	
  1764 		bo->setIncludeImagesVer(b);
  1765 		reposition();
  1766 	}	
  1767 }
  1768 
  1769 void VymModel::setIncludeImagesHor(bool b)	
  1770 {
  1771 	BranchObj *bo=selection.getBranch();
  1772 	if (bo)
  1773 	{
  1774 		QString u= b ? "false" : "true";
  1775 		QString r=!b ? "false" : "true";
  1776 		
  1777 		saveState(
  1778 			bo,
  1779 			QString("setIncludeImagesHorizontally (%1)").arg(u),
  1780 			bo, 
  1781 			QString("setIncludeImagesHorizontally (%1)").arg(r),
  1782 			QString("Include images horizontally in %1").arg(getObjectName(bo))
  1783 		);	
  1784 		bo->setIncludeImagesHor(b);
  1785 		reposition();
  1786 	}	
  1787 }
  1788 
  1789 void VymModel::setHideLinkUnselected (bool b)
  1790 {
  1791 	LinkableMapObj *sel=selection.single();
  1792 	if (sel &&
  1793 		(selection.type() == Selection::Branch || 
  1794 		selection.type() == Selection::MapCenter  ||
  1795 		selection.type() == Selection::FloatImage ))
  1796 	{
  1797 		QString u= b ? "false" : "true";
  1798 		QString r=!b ? "false" : "true";
  1799 		
  1800 		saveState(
  1801 			sel,
  1802 			QString("setHideLinkUnselected (%1)").arg(u),
  1803 			sel, 
  1804 			QString("setHideLinkUnselected (%1)").arg(r),
  1805 			QString("Hide link of %1 if unselected").arg(getObjectName(sel))
  1806 		);	
  1807 		sel->setHideLinkUnselected(b);
  1808 	}
  1809 }
  1810 
  1811 void VymModel::setHideExport(bool b)
  1812 {
  1813 	BranchObj *bo=selection.getBranch();
  1814 	if (bo)
  1815 	{
  1816 		bo->setHideInExport (b);
  1817 		QString u= b ? "false" : "true";
  1818 		QString r=!b ? "false" : "true";
  1819 		
  1820 		saveState(
  1821 			bo,
  1822 			QString ("setHideExport (%1)").arg(u),
  1823 			bo,
  1824 			QString ("setHideExport (%1)").arg(r),
  1825 			QString ("Set HideExport flag of %1 to %2").arg(getObjectName(bo)).arg (r)
  1826 		);	
  1827 		updateActions();
  1828 		reposition();
  1829 		selection.update();
  1830 		// FIXME VM needed? scene()->update();
  1831 	}
  1832 }
  1833 
  1834 void VymModel::toggleHideExport()
  1835 {
  1836 	BranchObj *bo=selection.getBranch();
  1837 	if (bo)
  1838 		setHideExport ( !bo->hideInExport() );
  1839 }
  1840 
  1841 
  1842 void VymModel::copy()
  1843 {
  1844 	LinkableMapObj *sel=selection.single();
  1845 	if (sel)
  1846 	{
  1847 		if (redosAvail == 0)
  1848 		{
  1849 			// Copy to history
  1850 			QString s=getSelectString(sel);
  1851 			saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",sel  );
  1852 			curClipboard=curStep;
  1853 		}
  1854 
  1855 		// Copy also to global clipboard, because we are at last step in history
  1856 		QString bakMapName(QString("history-%1").arg(curStep));
  1857 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1858 		copyDir (bakMapDir,clipboardDir );
  1859 
  1860 		clipboardEmpty=false;
  1861 		updateActions();
  1862 	}	    
  1863 }
  1864 
  1865 
  1866 void VymModel::pasteNoSave(const int &n)
  1867 {
  1868 	bool old=blockSaveState;
  1869 	blockSaveState=true;
  1870 	bool zippedOrg=zipped;
  1871 	if (redosAvail > 0 || n!=0)
  1872 	{
  1873 		// Use the "historical" buffer
  1874 		QString bakMapName(QString("history-%1").arg(n));
  1875 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1876 		load (bakMapDir+"/"+clipboardFile,ImportAdd, VymMap);
  1877 	} else
  1878 		// Use the global buffer
  1879 		load (clipboardDir+"/"+clipboardFile,ImportAdd, VymMap);
  1880 	zipped=zippedOrg;
  1881 	blockSaveState=old;
  1882 }
  1883 
  1884 void VymModel::paste()		
  1885 {   
  1886 	BranchObj *sel=selection.getBranch();
  1887 	if (sel)
  1888 	{
  1889 		saveStateChangingPart(
  1890 			sel,
  1891 			sel,
  1892 			QString ("paste (%1)").arg(curClipboard),
  1893 			QString("Paste to %1").arg( getObjectName(sel))
  1894 		);
  1895 		pasteNoSave(0);
  1896 		reposition();
  1897 	}
  1898 }
  1899 
  1900 void VymModel::cut()
  1901 {
  1902 	LinkableMapObj *sel=selection.single();
  1903 	if ( sel && (selection.type() == Selection::Branch ||
  1904 		selection.type()==Selection::MapCenter ||
  1905 		selection.type()==Selection::FloatImage))
  1906 	{
  1907 	/* No savestate! savestate is called in cutNoSave
  1908 		saveStateChangingPart(
  1909 			sel->getParObj(),
  1910 			sel,
  1911 			"cut ()",
  1912 			QString("Cut %1").arg(getObjectName(sel ))
  1913 		);
  1914 	*/	
  1915 		copy();
  1916 		deleteSelection();
  1917 		reposition();
  1918 	}
  1919 }
  1920 
  1921 void VymModel::moveBranchUp()
  1922 {
  1923 	BranchObj* bo=selection.getBranch();
  1924 	BranchObj* par;
  1925 	if (bo)
  1926 	{
  1927 		if (!bo->canMoveBranchUp()) return;
  1928 		par=(BranchObj*)(bo->getParObj());
  1929 		BranchObj *obo=par->moveBranchUp (bo);	// bo will be the one below selection
  1930 		saveState (getSelectString(bo),"moveBranchDown ()",getSelectString(obo),"moveBranchUp ()",QString("Move up %1").arg(getObjectName(bo)));
  1931 		reposition();
  1932 		//FIXME VM needed? scene()->update();
  1933 		selection.update();
  1934 		ensureSelectionVisible();
  1935 	}
  1936 }
  1937 
  1938 void VymModel::moveBranchDown()
  1939 {
  1940 	BranchObj* bo=selection.getBranch();
  1941 	BranchObj* par;
  1942 	if (bo)
  1943 	{
  1944 		if (!bo->canMoveBranchDown()) return;
  1945 		par=(BranchObj*)(bo->getParObj());
  1946 		BranchObj *obo=par->moveBranchDown(bo);	// bo will be the one above selection
  1947 		saveState(getSelectString(bo),"moveBranchUp ()",getSelectString(obo),"moveBranchDown ()",QString("Move down %1").arg(getObjectName(bo)));
  1948 		reposition();
  1949 		//FIXME VM needed? scene()->update();
  1950 		selection.update();
  1951 		ensureSelectionVisible();
  1952 	}	
  1953 }
  1954 
  1955 void VymModel::sortChildren()
  1956 {
  1957 	BranchObj* bo=selection.getBranch();
  1958 	if (bo)
  1959 	{
  1960 		if(bo->countBranches()>1)
  1961 		{
  1962 			saveStateChangingPart(bo,bo, "sortChildren ()",QString("Sort children of %1").arg(getObjectName(bo)));
  1963 			bo->sortChildren();
  1964 			reposition();
  1965 			ensureSelectionVisible();
  1966 		}
  1967 	}
  1968 }
  1969 
  1970 void VymModel::createMapCenter()
  1971 {
  1972 	MapCenterObj *mco=addMapCenter (QPointF (0,0) );
  1973 	selection.select (mco);
  1974 }
  1975 
  1976 void VymModel::createBranch()
  1977 {
  1978 	BranchObj *bo=selection.getBranch();
  1979 	if (bo)
  1980 	{
  1981 		BranchObj *newbo=addNewBranchInt (-2); // FIXME VM Old model, merge with below
  1982 
  1983 		// Create TreeItem
  1984 		QList<QVariant> cData;
  1985 		cData << "VM:createBranch" << "undef"<<"undef";
  1986 		TreeItem *parti=bo->getTreeItem();
  1987 		TreeItem *ti=new TreeItem (cData,parti);
  1988 		ti->setLMO (newbo);
  1989 		ti->setType (TreeItem::Branch);
  1990 		parti->appendChild (ti);
  1991 
  1992 		if (newbo)
  1993 		{
  1994 			newbo->setTreeItem (ti);
  1995 			selection.select (newbo); // FIXME VM really needed here?
  1996 		}
  1997 	}
  1998 }
  1999 
  2000 MapCenterObj* VymModel::addMapCenter ()
  2001 {
  2002 	MapCenterObj *mco=addMapCenter (contextPos);
  2003 	selection.select (mco);
  2004 	updateActions();
  2005 	ensureSelectionVisible();
  2006 	saveState (
  2007 		mco,
  2008 		"delete()",
  2009 		NULL,
  2010 		QString ("addMapCenter (%1,%2)").arg (contextPos.x()).arg(contextPos.y()),
  2011 		QString ("Adding MapCenter to (%1,%2)").arg (contextPos.x()).arg(contextPos.y())
  2012 	);	
  2013 	return mco;	
  2014 }
  2015 
  2016 MapCenterObj* VymModel::addMapCenter(QPointF absPos)
  2017 {
  2018 	MapCenterObj *mapCenter = new MapCenterObj(mapScene,this);
  2019 	mapCenter->setMapEditor(mapEditor);		//FIXME VM needed to get defLinkStyle, mapLinkColorHint ... for later added objects
  2020 	mapCenter->move (absPos);
  2021     mapCenter->setVisibility (true);
  2022 	mapCenter->setHeading (QApplication::translate("Heading of mapcenter in new map", "New map"));
  2023 	mapCenters.append(mapCenter);
  2024 
  2025 	// Create TreeItem
  2026 	QList<QVariant> cData;
  2027 	cData << "VM:addMapCenter" << "undef"<<"undef";
  2028 	TreeItem *ti=new TreeItem (cData,rootItem);
  2029 	ti->setLMO (mapCenter);
  2030 	ti->setType (TreeItem::MapCenter);
  2031 	mapCenter->setTreeItem (ti);
  2032 	rootItem->appendChild (ti);
  2033 
  2034 	return mapCenter;
  2035 }
  2036 
  2037 MapCenterObj* VymModel::removeMapCenter(MapCenterObj* mco)
  2038 {
  2039 	int i=mapCenters.indexOf (mco);
  2040 	if (i>=0)
  2041 	{
  2042 		mapCenters.removeAt (i);
  2043 		delete (mco);
  2044 		if (i>0) return mapCenters.at(i-1);	// Return previous MCO
  2045 	}
  2046 	return NULL;
  2047 }
  2048 
  2049 MapCenterObj* VymModel::getLastMapCenter()
  2050 {
  2051 	if (mapCenters.size()>0)
  2052 		return mapCenters.last();
  2053 	else
  2054 		return NULL;
  2055 
  2056 }
  2057 
  2058 
  2059 BranchObj* VymModel::addNewBranchInt(int num)
  2060 {
  2061 	// Depending on pos:
  2062 	// -3		insert in children of parent  above selection 
  2063 	// -2		add branch to selection 
  2064 	// -1		insert in children of parent below selection 
  2065 	// 0..n		insert in children of parent at pos
  2066 	BranchObj *newbo=NULL;
  2067 	BranchObj *bo=selection.getBranch();
  2068 	if (bo)
  2069 	{
  2070 		if (num==-2)
  2071 		{
  2072 			// save scroll state. If scrolled, automatically select
  2073 			// new branch in order to tmp unscroll parent...
  2074 			newbo=bo->addBranch();
  2075 			
  2076 		}else if (num==-1)
  2077 		{
  2078 			num=bo->getNum()+1;
  2079 			bo=(BranchObj*)bo->getParObj();
  2080 			if (bo) newbo=bo->insertBranch(num);
  2081 		}else if (num==-3)
  2082 		{
  2083 			num=bo->getNum();
  2084 			bo=(BranchObj*)bo->getParObj();
  2085 			if (bo) newbo=bo->insertBranch(num);
  2086 		}
  2087 		if (!newbo) return NULL;
  2088 	}	
  2089 	return newbo;
  2090 }	
  2091 
  2092 BranchObj* VymModel::addNewBranch(int pos)
  2093 {
  2094 	// Different meaning than num in addNewBranchInt!
  2095 	// -1	add above
  2096 	//  0	add as child
  2097 	// +1	add below
  2098 	BranchObj *bo = selection.getBranch();
  2099 	BranchObj *newbo=NULL;
  2100 
  2101 	if (bo)
  2102 	{
  2103 		// FIXME VM  do we still need this in model? setCursor (Qt::ArrowCursor);
  2104 
  2105 		newbo=addNewBranchInt (pos-2);
  2106 
  2107 		if (newbo)
  2108 		{
  2109 			saveState(
  2110 				newbo,		
  2111 				"delete ()",
  2112 				bo,
  2113 				QString ("addBranch (%1)").arg(pos),
  2114 				QString ("Add new branch to %1").arg(getObjectName(bo)));	
  2115 
  2116 			reposition();
  2117 			selection.update();
  2118 			latestSelectionString=getSelectString(newbo);
  2119 			// In Network mode, the client needs to know where the new branch is,
  2120 			// so we have to pass on this information via saveState.
  2121 			// TODO: Get rid of this positioning workaround
  2122 			QString ps=qpointfToString (newbo->getAbsPos());
  2123 			sendData ("selectLatestAdded ()");
  2124 			sendData (QString("move %1").arg(ps));
  2125 			sendSelection();
  2126 		}
  2127 	}	
  2128 	return newbo;
  2129 }
  2130 
  2131 
  2132 BranchObj* VymModel::addNewBranchBefore()
  2133 {
  2134 	BranchObj *newbo=NULL;
  2135 	BranchObj *bo = selection.getBranch();
  2136 	if (bo && selection.type()==Selection::Branch)
  2137 		 // We accept no MapCenterObj here, so we _have_ a parent
  2138 	{
  2139 		QPointF p=bo->getRelPos();
  2140 
  2141 
  2142 		BranchObj *parbo=(BranchObj*)(bo->getParObj());
  2143 
  2144 		// add below selection
  2145 		newbo=parbo->insertBranch(bo->getNum()+1);
  2146 		if (newbo)
  2147 		{
  2148 			newbo->move2RelPos (p);
  2149 
  2150 			// Move selection to new branch
  2151 			bo->linkTo (newbo,-1);
  2152 
  2153 			saveState (newbo, "deleteKeepChildren ()", newbo, "addBranchBefore ()", 
  2154 				QString ("Add branch before %1").arg(getObjectName(bo)));
  2155 
  2156 			reposition();
  2157 			selection.update();
  2158 		}
  2159 	}	
  2160 	latestSelectionString=selection.getSelectString();
  2161 	return newbo;
  2162 }
  2163 
  2164 void VymModel::deleteSelection()
  2165 {
  2166 	BranchObj *bo = selection.getBranch();
  2167 	if (bo && selection.type()==Selection::MapCenter)
  2168 	{
  2169 	//	BranchObj* par=(BranchObj*)(bo->getParObj());
  2170 		selection.unselect();
  2171 	/* FIXME VM Note:  does saveStateRemovingPart work for MCO? (No parent!)
  2172 		saveStateRemovingPart (bo, QString ("Delete %1").arg(getObjectName(bo)));
  2173 		*/
  2174 		bo=removeMapCenter ((MapCenterObj*)bo);
  2175 		if (bo) 
  2176 		{
  2177 			selection.select (bo);
  2178 			ensureSelectionVisible();
  2179 			selection.update();
  2180 		}	
  2181 		reposition();
  2182 		return;
  2183 	}
  2184 	if (bo && selection.type()==Selection::Branch)
  2185 	{
  2186 		//FIXME need to check if any animObj is part of Branch, remove from animated obj list then
  2187 
  2188 		// missing!!!!
  2189 
  2190 
  2191 		BranchObj* par=(BranchObj*)bo->getParObj();
  2192 		selection.unselect();
  2193 		saveStateRemovingPart (bo, QString ("Delete %1").arg(getObjectName(bo)));
  2194 		par->removeBranch(bo);
  2195 		selection.select (par);
  2196 		ensureSelectionVisible();
  2197 		reposition();
  2198 		selection.update();
  2199 		return;
  2200 	}
  2201 	FloatImageObj *fio=selection.getFloatImage();
  2202 	if (fio)
  2203 	{
  2204 		BranchObj* par=(BranchObj*)fio->getParObj();
  2205 		saveStateChangingPart(
  2206 			par, 
  2207 			fio,
  2208 			"delete ()",
  2209 			QString("Delete %1").arg(getObjectName(fio))
  2210 		);
  2211 		selection.unselect();
  2212 		par->removeFloatImage(fio);
  2213 		selection.select (par);
  2214 		reposition();
  2215 		selection.update();
  2216 		ensureSelectionVisible();
  2217 		return;
  2218 	}
  2219 }
  2220 
  2221 void VymModel::deleteKeepChildren()
  2222 {
  2223 	BranchObj *bo=selection.getBranch();
  2224 	BranchObj *par;
  2225 	if (bo)
  2226 	{
  2227 		par=(BranchObj*)(bo->getParObj());
  2228 
  2229 		// Don't use this on mapcenter
  2230 		if (!par) return;
  2231 
  2232 		// Check if we have childs at all to keep
  2233 		if (bo->countBranches()==0) 
  2234 		{
  2235 			deleteSelection();
  2236 			return;
  2237 		}
  2238 
  2239 		QPointF p=bo->getRelPos();
  2240 		saveStateChangingPart(
  2241 			bo->getParObj(),
  2242 			bo,
  2243 			"deleteKeepChildren ()",
  2244 			QString("Remove %1 and keep its children").arg(getObjectName(bo))
  2245 		);
  2246 
  2247 		QString sel=getSelectString(bo);
  2248 		unselect();
  2249 		par->removeBranchHere(bo);
  2250 		reposition();
  2251 		select (sel);
  2252 		selection.getBranch()->move2RelPos (p);
  2253 		reposition();
  2254 	}	
  2255 }
  2256 
  2257 void VymModel::deleteChildren()
  2258 {
  2259 	BranchObj *bo=selection.getBranch();
  2260 	if (bo)
  2261 	{		
  2262 		saveStateChangingPart(
  2263 			bo, 
  2264 			bo,
  2265 			"deleteChildren ()",
  2266 			QString( "Remove children of branch %1").arg(getObjectName(bo))
  2267 		);
  2268 		bo->removeChildren();
  2269 		reposition();
  2270 	}	
  2271 }
  2272 
  2273 
  2274 bool VymModel::scrollBranch(BranchObj *bo)
  2275 {
  2276 	if (bo)
  2277 	{
  2278 		if (bo->isScrolled()) return false;
  2279 		if (bo->countBranches()==0) return false;
  2280 		if (bo->getDepth()==0) return false;
  2281 		QString u,r;
  2282 		r="scroll";
  2283 		u="unscroll";
  2284 		saveState(
  2285 			bo,
  2286 			QString ("%1 ()").arg(u),
  2287 			bo,
  2288 			QString ("%1 ()").arg(r),
  2289 			QString ("%1 %2").arg(r).arg(getObjectName(bo))
  2290 		);
  2291 		bo->toggleScroll();
  2292 		selection.update();
  2293 		// FIXME VM needed? scene()->update();
  2294 		return true;
  2295 	}	
  2296 	return false;
  2297 }
  2298 
  2299 bool VymModel::unscrollBranch(BranchObj *bo)
  2300 {
  2301 	if (bo)
  2302 	{
  2303 		if (!bo->isScrolled()) return false;
  2304 		if (bo->countBranches()==0) return false;
  2305 		if (bo->getDepth()==0) return false;
  2306 		QString u,r;
  2307 		u="scroll";
  2308 		r="unscroll";
  2309 		saveState(
  2310 			bo,
  2311 			QString ("%1 ()").arg(u),
  2312 			bo,
  2313 			QString ("%1 ()").arg(r),
  2314 			QString ("%1 %2").arg(r).arg(getObjectName(bo))
  2315 		);
  2316 		bo->toggleScroll();
  2317 		selection.update();
  2318 		// FIXME VM needed? scene()->update();
  2319 		return true;
  2320 	}	
  2321 	return false;
  2322 }
  2323 
  2324 void VymModel::toggleScroll()
  2325 {
  2326 	BranchObj *bo=selection.getBranch();
  2327 	if (selection.type()==Selection::Branch )
  2328 	{
  2329 		if (bo->isScrolled())
  2330 			unscrollBranch (bo);
  2331 		else
  2332 			scrollBranch (bo);
  2333 	}
  2334 }
  2335 
  2336 void VymModel::unscrollChildren() 
  2337 {
  2338 	BranchObj *bo=selection.getBranch();
  2339 	if (bo)
  2340 	{
  2341 		bo->first();
  2342 		while (bo) 
  2343 		{
  2344 			if (bo->isScrolled()) unscrollBranch (bo);
  2345 			bo=bo->next();
  2346 		}
  2347 	}	
  2348 }
  2349 void VymModel::addFloatImage (const QPixmap &img) 
  2350 {
  2351 	BranchObj *bo=selection.getBranch();
  2352 	if (bo)
  2353   {
  2354 	FloatImageObj *fio=bo->addFloatImage();
  2355     fio->load(img);
  2356     fio->setOriginalFilename("No original filename (image added by dropevent)");	
  2357 	QString s=getSelectString(bo);
  2358 	saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",fio  );
  2359 	saveState (fio,"delete ()", bo,QString("paste(%1)").arg(curStep),"Pasting dropped image");
  2360     reposition();
  2361     // FIXME VM needed? scene()->update();
  2362   }
  2363 }
  2364 
  2365 
  2366 void VymModel::colorBranch (QColor c)
  2367 {
  2368 	BranchObj *bo=selection.getBranch();
  2369 	if (bo)
  2370 	{
  2371 		saveState(
  2372 			bo, 
  2373 			QString ("colorBranch (\"%1\")").arg(bo->getColor().name()),
  2374 			bo,
  2375 			QString ("colorBranch (\"%1\")").arg(c.name()),
  2376 			QString("Set color of %1 to %2").arg(getObjectName(bo)).arg(c.name())
  2377 		);	
  2378 		bo->setColor(c); // color branch
  2379 	}
  2380 }
  2381 
  2382 void VymModel::colorSubtree (QColor c)
  2383 {
  2384 	BranchObj *bo=selection.getBranch();
  2385 	if (bo) 
  2386 	{
  2387 		saveStateChangingPart(
  2388 			bo, 
  2389 			bo,
  2390 			QString ("colorSubtree (\"%1\")").arg(c.name()),
  2391 			QString ("Set color of %1 and children to %2").arg(getObjectName(bo)).arg(c.name())
  2392 		);	
  2393 		bo->setColorSubtree (c); // color links, color children
  2394 	}
  2395 }
  2396 
  2397 QColor VymModel::getCurrentHeadingColor()
  2398 {
  2399 	BranchObj *bo=selection.getBranch();
  2400 	if (bo) return bo->getColor(); 
  2401 	
  2402 	QMessageBox::warning(0,"Warning","Can't get color of heading,\nthere's no branch selected");
  2403 	return Qt::black;
  2404 }
  2405 
  2406 
  2407 
  2408 void VymModel::editURL()
  2409 {
  2410 	BranchObj *bo=selection.getBranch();
  2411 	if (bo)
  2412 	{		
  2413 		bool ok;
  2414 		QString text = QInputDialog::getText(
  2415 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2416 				bo->getURL(), &ok, NULL);
  2417 		if ( ok) 
  2418 			// user entered something and pressed OK
  2419 			setURL(text);
  2420 	}
  2421 }
  2422 
  2423 void VymModel::editLocalURL()
  2424 {
  2425 	BranchObj *bo=selection.getBranch();
  2426 	if (bo)
  2427 	{		
  2428 		QStringList filters;
  2429 		filters <<"All files (*)";
  2430 		filters << tr("Text","Filedialog") + " (*.txt)";
  2431 		filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
  2432 		filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
  2433 		filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
  2434 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Set URL to a local file"));
  2435 		fd->setFilters (filters);
  2436 		fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
  2437 		fd->setDirectory (lastFileDir);
  2438 		if (! bo->getVymLink().isEmpty() )
  2439 			fd->selectFile( bo->getURL() );
  2440 		fd->show();
  2441 
  2442 		if ( fd->exec() == QDialog::Accepted )
  2443 		{
  2444 			lastFileDir=QDir (fd->directory().path());
  2445 			setURL (fd->selectedFile() );
  2446 		}
  2447 	}
  2448 }
  2449 
  2450 
  2451 void VymModel::editHeading2URL()
  2452 {
  2453 	BranchObj *bo=selection.getBranch();
  2454 	if (bo)
  2455 		setURL (bo->getHeading());
  2456 }	
  2457 
  2458 void VymModel::editBugzilla2URL()
  2459 {
  2460 	BranchObj *bo=selection.getBranch();
  2461 	if (bo)
  2462 	{		
  2463 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
  2464 		setURL (url);
  2465 	}
  2466 }	
  2467 
  2468 void VymModel::editFATE2URL()
  2469 {
  2470 	BranchObj *bo=selection.getBranch();
  2471 	if (bo)
  2472 	{		
  2473 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
  2474 		saveState(
  2475 			bo,
  2476 			"setURL (\""+bo->getURL()+"\")",
  2477 			bo,
  2478 			"setURL (\""+url+"\")",
  2479 			QString("Use heading of %1 as link to FATE").arg(getObjectName(bo))
  2480 		);	
  2481 		bo->setURL (url);
  2482 		updateActions();
  2483 	}
  2484 }	
  2485 
  2486 void VymModel::editVymLink()
  2487 {
  2488 	BranchObj *bo=selection.getBranch();
  2489 	if (bo)
  2490 	{		
  2491 		QStringList filters;
  2492 		filters <<"VYM map (*.vym)";
  2493 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Link to another map"));
  2494 		fd->setFilters (filters);
  2495 		fd->setCaption(vymName+" - " +tr("Link to another map"));
  2496 		fd->setDirectory (lastFileDir);
  2497 		if (! bo->getVymLink().isEmpty() )
  2498 			fd->selectFile( bo->getVymLink() );
  2499 		fd->show();
  2500 
  2501 		QString fn;
  2502 		if ( fd->exec() == QDialog::Accepted )
  2503 		{
  2504 			lastFileDir=QDir (fd->directory().path());
  2505 			saveState(
  2506 				bo,
  2507 				"setVymLink (\""+bo->getVymLink()+"\")",
  2508 				bo,
  2509 				"setVymLink (\""+fd->selectedFile()+"\")",
  2510 				QString("Set vymlink of %1 to %2").arg(getObjectName(bo)).arg(fd->selectedFile())
  2511 			);	
  2512 			setVymLink (fd->selectedFile() );	// FIXME ok?
  2513 		}
  2514 	}
  2515 }
  2516 
  2517 void VymModel::setVymLink (const QString &s)
  2518 {
  2519 	// Internal function, no saveState needed
  2520 	BranchObj *bo=selection.getBranch();
  2521 	if (bo)
  2522 	{
  2523 		bo->setVymLink(s);
  2524 		reposition();
  2525 		updateActions();
  2526 		selection.update();
  2527 		ensureSelectionVisible();
  2528 	}
  2529 }
  2530 
  2531 void VymModel::deleteVymLink()
  2532 {
  2533 	BranchObj *bo=selection.getBranch();
  2534 	if (bo)
  2535 	{		
  2536 		saveState(
  2537 			bo,
  2538 			"setVymLink (\""+bo->getVymLink()+"\")",
  2539 			bo,
  2540 			"setVymLink (\"\")",
  2541 			QString("Unset vymlink of %1").arg(getObjectName(bo))
  2542 		);	
  2543 		bo->setVymLink ("" );
  2544 		updateActions();
  2545 		reposition();
  2546 		// FIXME VM needed? scene()->update();
  2547 	}
  2548 }
  2549 
  2550 QString VymModel::getVymLink()
  2551 {
  2552 	BranchObj *bo=selection.getBranch();
  2553 	if (bo)
  2554 		return bo->getVymLink();
  2555 	else	
  2556 		return "";
  2557 	
  2558 }
  2559 
  2560 QStringList VymModel::getVymLinks()
  2561 {
  2562 	QStringList links;
  2563 	BranchObj *bo=selection.getBranch();
  2564 	if (bo)
  2565 	{		
  2566 		bo=bo->first();	
  2567 		while (bo) 
  2568 		{
  2569 			if (!bo->getVymLink().isEmpty()) links.append( bo->getVymLink());
  2570 			bo=bo->next();
  2571 		}	
  2572 	}	
  2573 	return links;
  2574 }
  2575 
  2576 
  2577 void VymModel::followXLink(int i)
  2578 {
  2579 	BranchObj *bo=selection.getBranch();
  2580 	if (bo)
  2581 	{
  2582 		bo=bo->XLinkTargetAt(i);
  2583 		if (bo) 
  2584 		{
  2585 			selection.select(bo);
  2586 			ensureSelectionVisible();
  2587 		}
  2588 	}
  2589 }
  2590 
  2591 void VymModel::editXLink(int i)	// FIXME VM missing saveState
  2592 {
  2593 	BranchObj *bo=selection.getBranch();
  2594 	if (bo)
  2595 	{
  2596 		XLinkObj *xlo=bo->XLinkAt(i);
  2597 		if (xlo) 
  2598 		{
  2599 			EditXLinkDialog dia;
  2600 			dia.setXLink (xlo);
  2601 			dia.setSelection(bo);
  2602 			if (dia.exec() == QDialog::Accepted)
  2603 			{
  2604 				if (dia.useSettingsGlobal() )
  2605 				{
  2606 					setMapDefXLinkColor (xlo->getColor() );
  2607 					setMapDefXLinkWidth (xlo->getWidth() );
  2608 				}
  2609 				if (dia.deleteXLink())
  2610 					bo->deleteXLinkAt(i);
  2611 			}
  2612 		}	
  2613 	}
  2614 }
  2615 
  2616 
  2617 
  2618 
  2619 
  2620 //////////////////////////////////////////////
  2621 // Scripting
  2622 //////////////////////////////////////////////
  2623 
  2624 void VymModel::parseAtom(const QString &atom)
  2625 {
  2626 	BranchObj *selb=selection.getBranch();
  2627 	QString s,t;
  2628 	double x,y;
  2629 	int n;
  2630 	bool b,ok;
  2631 
  2632 	// Split string s into command and parameters
  2633 	parser.parseAtom (atom);
  2634 	QString com=parser.getCommand();
  2635 	
  2636 	// External commands
  2637 	/////////////////////////////////////////////////////////////////////
  2638 	if (com=="addBranch")
  2639 	{
  2640 		if (selection.isEmpty())
  2641 		{
  2642 			parser.setError (Aborted,"Nothing selected");
  2643 		} else if (! selb )
  2644 		{				  
  2645 			parser.setError (Aborted,"Type of selection is not a branch");
  2646 		} else 
  2647 		{	
  2648 			QList <int> pl;
  2649 			pl << 0 <<1;
  2650 			if (parser.checkParCount(pl))
  2651 			{
  2652 				if (parser.parCount()==0)
  2653 					addNewBranch (0);
  2654 				else
  2655 				{
  2656 					n=parser.parInt (ok,0);
  2657 					if (ok ) addNewBranch (n);
  2658 				}
  2659 			}
  2660 		}
  2661 	/////////////////////////////////////////////////////////////////////
  2662 	} else if (com=="addBranchBefore")
  2663 	{
  2664 		if (selection.isEmpty())
  2665 		{
  2666 			parser.setError (Aborted,"Nothing selected");
  2667 		} else if (! selb )
  2668 		{				  
  2669 			parser.setError (Aborted,"Type of selection is not a branch");
  2670 		} else 
  2671 		{	
  2672 			if (parser.parCount()==0)
  2673 			{
  2674 				addNewBranchBefore ();
  2675 			}	
  2676 		}
  2677 	/////////////////////////////////////////////////////////////////////
  2678 	} else if (com==QString("addMapCenter"))
  2679 	{
  2680 		if (parser.checkParCount(2))
  2681 		{
  2682 			x=parser.parDouble (ok,0);
  2683 			if (ok)
  2684 			{
  2685 				y=parser.parDouble (ok,1);
  2686 				if (ok) addMapCenter (QPointF(x,y));
  2687 			}
  2688 		}	
  2689 	/////////////////////////////////////////////////////////////////////
  2690 	} else if (com==QString("addMapReplace"))
  2691 	{
  2692 		if (selection.isEmpty())
  2693 		{
  2694 			parser.setError (Aborted,"Nothing selected");
  2695 		} else if (! selb )
  2696 		{				  
  2697 			parser.setError (Aborted,"Type of selection is not a branch");
  2698 		} else if (parser.checkParCount(1))
  2699 		{
  2700 			//s=parser.parString (ok,0);	// selection
  2701 			t=parser.parString (ok,0);	// path to map
  2702 			if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2703 			addMapReplaceInt(getSelectString(selb),t);	
  2704 		}
  2705 	/////////////////////////////////////////////////////////////////////
  2706 	} else if (com==QString("addMapInsert"))
  2707 	{
  2708 		if (selection.isEmpty())
  2709 		{
  2710 			parser.setError (Aborted,"Nothing selected");
  2711 		} else if (! selb )
  2712 		{				  
  2713 			parser.setError (Aborted,"Type of selection is not a branch");
  2714 		} else 
  2715 		{	
  2716 			if (parser.checkParCount(2))
  2717 			{
  2718 				t=parser.parString (ok,0);	// path to map
  2719 				n=parser.parInt(ok,1);		// position
  2720 				if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2721 				addMapInsertInt(t,n);	
  2722 			}
  2723 		}
  2724 	/////////////////////////////////////////////////////////////////////
  2725 	} else if (com=="clearFlags")
  2726 	{
  2727 		if (selection.isEmpty() )
  2728 		{
  2729 			parser.setError (Aborted,"Nothing selected");
  2730 		} else if (! selb )
  2731 		{				  
  2732 			parser.setError (Aborted,"Type of selection is not a branch");
  2733 		} else if (parser.checkParCount(0))
  2734 		{
  2735 			selb->clearStandardFlags();	
  2736 			selb->updateFlagsToolbar();
  2737 		}
  2738 	/////////////////////////////////////////////////////////////////////
  2739 	} else if (com=="colorBranch")
  2740 	{
  2741 		if (selection.isEmpty())
  2742 		{
  2743 			parser.setError (Aborted,"Nothing selected");
  2744 		} else if (! selb )
  2745 		{				  
  2746 			parser.setError (Aborted,"Type of selection is not a branch");
  2747 		} else if (parser.checkParCount(1))
  2748 		{	
  2749 			QColor c=parser.parColor (ok,0);
  2750 			if (ok) colorBranch (c);
  2751 		}	
  2752 	/////////////////////////////////////////////////////////////////////
  2753 	} else if (com=="colorSubtree")
  2754 	{
  2755 		if (selection.isEmpty())
  2756 		{
  2757 			parser.setError (Aborted,"Nothing selected");
  2758 		} else if (! selb )
  2759 		{				  
  2760 			parser.setError (Aborted,"Type of selection is not a branch");
  2761 		} else if (parser.checkParCount(1))
  2762 		{	
  2763 			QColor c=parser.parColor (ok,0);
  2764 			if (ok) colorSubtree (c);
  2765 		}	
  2766 	/////////////////////////////////////////////////////////////////////
  2767 	} else if (com=="copy")
  2768 	{
  2769 		if (selection.isEmpty())
  2770 		{
  2771 			parser.setError (Aborted,"Nothing selected");
  2772 		} else if (! selb )
  2773 		{				  
  2774 			parser.setError (Aborted,"Type of selection is not a branch");
  2775 		} else if (parser.checkParCount(0))
  2776 		{	
  2777 			//FIXME missing action for copy
  2778 		}	
  2779 	/////////////////////////////////////////////////////////////////////
  2780 	} else if (com=="cut")
  2781 	{
  2782 		if (selection.isEmpty())
  2783 		{
  2784 			parser.setError (Aborted,"Nothing selected");
  2785 		} else if ( selection.type()!=Selection::Branch  && 
  2786 					selection.type()!=Selection::MapCenter  &&
  2787 					selection.type()!=Selection::FloatImage )
  2788 		{				  
  2789 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  2790 		} else if (parser.checkParCount(0))
  2791 		{	
  2792 			cut();
  2793 		}	
  2794 	/////////////////////////////////////////////////////////////////////
  2795 	} else if (com=="delete")
  2796 	{
  2797 		if (selection.isEmpty())
  2798 		{
  2799 			parser.setError (Aborted,"Nothing selected");
  2800 		} 
  2801 		/*else if (selection.type() != Selection::Branch && selection.type() != Selection::FloatImage )
  2802 		{
  2803 			parser.setError (Aborted,"Type of selection is wrong.");
  2804 		} 
  2805 		*/
  2806 		else if (parser.checkParCount(0))
  2807 		{	
  2808 			deleteSelection();
  2809 		}	
  2810 	/////////////////////////////////////////////////////////////////////
  2811 	} else if (com=="deleteKeepChildren")
  2812 	{
  2813 		if (selection.isEmpty())
  2814 		{
  2815 			parser.setError (Aborted,"Nothing selected");
  2816 		} else if (! selb )
  2817 		{
  2818 			parser.setError (Aborted,"Type of selection is not a branch");
  2819 		} else if (parser.checkParCount(0))
  2820 		{	
  2821 			deleteKeepChildren();
  2822 		}	
  2823 	/////////////////////////////////////////////////////////////////////
  2824 	} else if (com=="deleteChildren")
  2825 	{
  2826 		if (selection.isEmpty())
  2827 		{
  2828 			parser.setError (Aborted,"Nothing selected");
  2829 		} else if (! selb)
  2830 		{
  2831 			parser.setError (Aborted,"Type of selection is not a branch");
  2832 		} else if (parser.checkParCount(0))
  2833 		{	
  2834 			deleteChildren();
  2835 		}	
  2836 	/////////////////////////////////////////////////////////////////////
  2837 	} else if (com=="exportASCII")
  2838 	{
  2839 		QString fname="";
  2840 		ok=true;
  2841 		if (parser.parCount()>=1)
  2842 			// Hey, we even have a filename
  2843 			fname=parser.parString(ok,0); 
  2844 		if (!ok)
  2845 		{
  2846 			parser.setError (Aborted,"Could not read filename");
  2847 		} else
  2848 		{
  2849 				exportASCII (fname,false);
  2850 		}
  2851 	/////////////////////////////////////////////////////////////////////
  2852 	} else if (com=="exportImage")
  2853 	{
  2854 		QString fname="";
  2855 		ok=true;
  2856 		if (parser.parCount()>=2)
  2857 			// Hey, we even have a filename
  2858 			fname=parser.parString(ok,0); 
  2859 		if (!ok)
  2860 		{
  2861 			parser.setError (Aborted,"Could not read filename");
  2862 		} else
  2863 		{
  2864 			QString format="PNG";
  2865 			if (parser.parCount()>=2)
  2866 			{
  2867 				format=parser.parString(ok,1);
  2868 			}
  2869 			exportImage (fname,false,format);
  2870 		}
  2871 	/////////////////////////////////////////////////////////////////////
  2872 	} else if (com=="exportXHTML")
  2873 	{
  2874 		QString fname="";
  2875 		ok=true;
  2876 		if (parser.parCount()>=2)
  2877 			// Hey, we even have a filename
  2878 			fname=parser.parString(ok,1); 
  2879 		if (!ok)
  2880 		{
  2881 			parser.setError (Aborted,"Could not read filename");
  2882 		} else
  2883 		{
  2884 			exportXHTML (fname,false);
  2885 		}
  2886 	/////////////////////////////////////////////////////////////////////
  2887 	} else if (com=="exportXML")
  2888 	{
  2889 		QString fname="";
  2890 		ok=true;
  2891 		if (parser.parCount()>=2)
  2892 			// Hey, we even have a filename
  2893 			fname=parser.parString(ok,1); 
  2894 		if (!ok)
  2895 		{
  2896 			parser.setError (Aborted,"Could not read filename");
  2897 		} else
  2898 		{
  2899 			exportXML (fname,false);
  2900 		}
  2901 	/////////////////////////////////////////////////////////////////////
  2902 	} else if (com=="importDir")
  2903 	{
  2904 		if (selection.isEmpty())
  2905 		{
  2906 			parser.setError (Aborted,"Nothing selected");
  2907 		} else if (! selb )
  2908 		{				  
  2909 			parser.setError (Aborted,"Type of selection is not a branch");
  2910 		} else if (parser.checkParCount(1))
  2911 		{
  2912 			s=parser.parString(ok,0);
  2913 			if (ok) importDirInt(s);
  2914 		}	
  2915 	/////////////////////////////////////////////////////////////////////
  2916 	} else if (com=="linkTo")
  2917 	{
  2918 		if (selection.isEmpty())
  2919 		{
  2920 			parser.setError (Aborted,"Nothing selected");
  2921 		} else if ( selb)
  2922 		{
  2923 			if (parser.checkParCount(4))
  2924 			{
  2925 				// 0	selectstring of parent
  2926 				// 1	num in parent (for branches)
  2927 				// 2,3	x,y of mainbranch or mapcenter
  2928 				s=parser.parString(ok,0);
  2929 				LinkableMapObj *dst=findObjBySelect (s);
  2930 				if (dst)
  2931 				{	
  2932 					if (typeid(*dst) == typeid(BranchObj) ) 
  2933 					{
  2934 						// Get number in parent
  2935 						n=parser.parInt (ok,1);
  2936 						if (ok)
  2937 						{
  2938 							selb->linkTo ((BranchObj*)(dst),n);
  2939 							selection.update();
  2940 						}	
  2941 					} else if (typeid(*dst) == typeid(MapCenterObj) ) 
  2942 					{
  2943 						selb->linkTo ((BranchObj*)(dst),-1);
  2944 						// Get coordinates of mainbranch
  2945 						x=parser.parDouble(ok,2);
  2946 						if (ok)
  2947 						{
  2948 							y=parser.parDouble(ok,3);
  2949 							if (ok) 
  2950 							{
  2951 								selb->move (x,y);
  2952 								selection.update();
  2953 							}
  2954 						}
  2955 					}	
  2956 				}	
  2957 			}	
  2958 		} else if ( selection.type() == Selection::FloatImage) 
  2959 		{
  2960 			if (parser.checkParCount(1))
  2961 			{
  2962 				// 0	selectstring of parent
  2963 				s=parser.parString(ok,0);
  2964 				LinkableMapObj *dst=findObjBySelect (s);
  2965 				if (dst)
  2966 				{	
  2967 					if (typeid(*dst) == typeid(BranchObj) ||
  2968 						typeid(*dst) == typeid(MapCenterObj)) 
  2969 						linkFloatImageTo (getSelectString(dst));
  2970 				} else	
  2971 					parser.setError (Aborted,"Destination is not a branch");
  2972 			}		
  2973 		} else
  2974 			parser.setError (Aborted,"Type of selection is not a floatimage or branch");
  2975 	/////////////////////////////////////////////////////////////////////
  2976 	} else if (com=="loadImage")
  2977 	{
  2978 		if (selection.isEmpty())
  2979 		{
  2980 			parser.setError (Aborted,"Nothing selected");
  2981 		} else if (! selb )
  2982 		{				  
  2983 			parser.setError (Aborted,"Type of selection is not a branch");
  2984 		} else if (parser.checkParCount(1))
  2985 		{
  2986 			s=parser.parString(ok,0);
  2987 			if (ok) loadFloatImageInt (s);
  2988 		}	
  2989 	/////////////////////////////////////////////////////////////////////
  2990 	} else if (com=="moveBranchUp")
  2991 	{
  2992 		if (selection.isEmpty() )
  2993 		{
  2994 			parser.setError (Aborted,"Nothing selected");
  2995 		} else if (! selb )
  2996 		{				  
  2997 			parser.setError (Aborted,"Type of selection is not a branch");
  2998 		} else if (parser.checkParCount(0))
  2999 		{
  3000 			moveBranchUp();
  3001 		}	
  3002 	/////////////////////////////////////////////////////////////////////
  3003 	} else if (com=="moveBranchDown")
  3004 	{
  3005 		if (selection.isEmpty() )
  3006 		{
  3007 			parser.setError (Aborted,"Nothing selected");
  3008 		} else if (! selb )
  3009 		{				  
  3010 			parser.setError (Aborted,"Type of selection is not a branch");
  3011 		} else if (parser.checkParCount(0))
  3012 		{
  3013 			moveBranchDown();
  3014 		}	
  3015 	/////////////////////////////////////////////////////////////////////
  3016 	} else if (com=="move")
  3017 	{
  3018 		if (selection.isEmpty() )
  3019 		{
  3020 			parser.setError (Aborted,"Nothing selected");
  3021 		} else if ( selection.type()!=Selection::Branch  && 
  3022 					selection.type()!=Selection::MapCenter  &&
  3023 					selection.type()!=Selection::FloatImage )
  3024 		{				  
  3025 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3026 		} else if (parser.checkParCount(2))
  3027 		{	
  3028 			x=parser.parDouble (ok,0);
  3029 			if (ok)
  3030 			{
  3031 				y=parser.parDouble (ok,1);
  3032 				if (ok) move (x,y);
  3033 			}
  3034 		}	
  3035 	/////////////////////////////////////////////////////////////////////
  3036 	} else if (com=="moveRel")
  3037 	{
  3038 		if (selection.isEmpty() )
  3039 		{
  3040 			parser.setError (Aborted,"Nothing selected");
  3041 		} else if ( selection.type()!=Selection::Branch  && 
  3042 					selection.type()!=Selection::MapCenter  &&
  3043 					selection.type()!=Selection::FloatImage )
  3044 		{				  
  3045 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3046 		} else if (parser.checkParCount(2))
  3047 		{	
  3048 			x=parser.parDouble (ok,0);
  3049 			if (ok)
  3050 			{
  3051 				y=parser.parDouble (ok,1);
  3052 				if (ok) moveRel (x,y);
  3053 			}
  3054 		}	
  3055 	/////////////////////////////////////////////////////////////////////
  3056 	} else if (com=="nop")
  3057 	{
  3058 	/////////////////////////////////////////////////////////////////////
  3059 	} else if (com=="paste")
  3060 	{
  3061 		if (selection.isEmpty() )
  3062 		{
  3063 			parser.setError (Aborted,"Nothing selected");
  3064 		} else if (! selb )
  3065 		{				  
  3066 			parser.setError (Aborted,"Type of selection is not a branch");
  3067 		} else if (parser.checkParCount(1))
  3068 		{	
  3069 			n=parser.parInt (ok,0);
  3070 			if (ok) pasteNoSave(n);
  3071 		}	
  3072 	/////////////////////////////////////////////////////////////////////
  3073 	} else if (com=="qa")
  3074 	{
  3075 		if (selection.isEmpty() )
  3076 		{
  3077 			parser.setError (Aborted,"Nothing selected");
  3078 		} else if (! selb )
  3079 		{				  
  3080 			parser.setError (Aborted,"Type of selection is not a branch");
  3081 		} else if (parser.checkParCount(4))
  3082 		{	
  3083 			QString c,u;
  3084 			c=parser.parString (ok,0);
  3085 			if (!ok)
  3086 			{
  3087 				parser.setError (Aborted,"No comment given");
  3088 			} else
  3089 			{
  3090 				s=parser.parString (ok,1);
  3091 				if (!ok)
  3092 				{
  3093 					parser.setError (Aborted,"First parameter is not a string");
  3094 				} else
  3095 				{
  3096 					t=parser.parString (ok,2);
  3097 					if (!ok)
  3098 					{
  3099 						parser.setError (Aborted,"Condition is not a string");
  3100 					} else
  3101 					{
  3102 						u=parser.parString (ok,3);
  3103 						if (!ok)
  3104 						{
  3105 							parser.setError (Aborted,"Third parameter is not a string");
  3106 						} else
  3107 						{
  3108 							if (s!="heading")
  3109 							{
  3110 								parser.setError (Aborted,"Unknown type: "+s);
  3111 							} else
  3112 							{
  3113 								if (! (t=="eq") ) 
  3114 								{
  3115 									parser.setError (Aborted,"Unknown operator: "+t);
  3116 								} else
  3117 								{
  3118 									if (! selb    )
  3119 									{
  3120 										parser.setError (Aborted,"Type of selection is not a branch");
  3121 									} else
  3122 									{
  3123 										if (selb->getHeading() == u)
  3124 										{
  3125 											cout << "PASSED: " << qPrintable (c)  << endl;
  3126 										} else
  3127 										{
  3128 											cout << "FAILED: " << qPrintable (c)  << endl;
  3129 										}
  3130 									}
  3131 								}
  3132 							}
  3133 						} 
  3134 					} 
  3135 				} 
  3136 			}
  3137 		}	
  3138 	/////////////////////////////////////////////////////////////////////
  3139 	} else if (com=="saveImage")
  3140 	{
  3141 		FloatImageObj *fio=selection.getFloatImage();
  3142 		if (!fio)
  3143 		{
  3144 			parser.setError (Aborted,"Type of selection is not an image");
  3145 		} else if (parser.checkParCount(2))
  3146 		{
  3147 			s=parser.parString(ok,0);
  3148 			if (ok)
  3149 			{
  3150 				t=parser.parString(ok,1);
  3151 				if (ok) saveFloatImageInt (fio,t,s);
  3152 			}
  3153 		}	
  3154 	/////////////////////////////////////////////////////////////////////
  3155 	} else if (com=="scroll")
  3156 	{
  3157 		if (selection.isEmpty() )
  3158 		{
  3159 			parser.setError (Aborted,"Nothing selected");
  3160 		} else if (! selb )
  3161 		{				  
  3162 			parser.setError (Aborted,"Type of selection is not a branch");
  3163 		} else if (parser.checkParCount(0))
  3164 		{	
  3165 			if (!scrollBranch (selb))	
  3166 				parser.setError (Aborted,"Could not scroll branch");
  3167 		}	
  3168 	/////////////////////////////////////////////////////////////////////
  3169 	} else if (com=="select")
  3170 	{
  3171 		if (parser.checkParCount(1))
  3172 		{
  3173 			s=parser.parString(ok,0);
  3174 			if (ok) select (s);
  3175 		}	
  3176 	/////////////////////////////////////////////////////////////////////
  3177 	} else if (com=="selectLastBranch")
  3178 	{
  3179 		if (selection.isEmpty() )
  3180 		{
  3181 			parser.setError (Aborted,"Nothing selected");
  3182 		} else if (! selb )
  3183 		{				  
  3184 			parser.setError (Aborted,"Type of selection is not a branch");
  3185 		} else if (parser.checkParCount(0))
  3186 		{	
  3187 			BranchObj *bo=selb->getLastBranch();
  3188 			if (!bo)
  3189 				parser.setError (Aborted,"Could not select last branch");
  3190 			selectInt (bo);	
  3191 				
  3192 		}	
  3193 	/////////////////////////////////////////////////////////////////////
  3194 	} else if (com=="selectLastImage")
  3195 	{
  3196 		if (selection.isEmpty() )
  3197 		{
  3198 			parser.setError (Aborted,"Nothing selected");
  3199 		} else if (! selb )
  3200 		{				  
  3201 			parser.setError (Aborted,"Type of selection is not a branch");
  3202 		} else if (parser.checkParCount(0))
  3203 		{	
  3204 			FloatImageObj *fio=selb->getLastFloatImage();
  3205 			if (!fio)
  3206 				parser.setError (Aborted,"Could not select last image");
  3207 			selectInt (fio);	
  3208 				
  3209 		}	
  3210 	/////////////////////////////////////////////////////////////////////
  3211 	} else if (com=="selectLatestAdded")
  3212 	{
  3213 		if (latestSelectionString.isEmpty() )
  3214 		{
  3215 			parser.setError (Aborted,"No latest added object");
  3216 		} else
  3217 		{	
  3218 			if (!select (latestSelectionString))
  3219 				parser.setError (Aborted,"Could not select latest added object "+latestSelectionString);
  3220 		}	
  3221 	/////////////////////////////////////////////////////////////////////
  3222 	} else if (com=="setFrameType")
  3223 	{
  3224 		if ( selection.type()!=Selection::Branch && selection.type()!= Selection::MapCenter && selection.type()!=Selection::FloatImage)
  3225 		{
  3226 			parser.setError (Aborted,"Type of selection does not allow setting frame type");
  3227 		}
  3228 		else if (parser.checkParCount(1))
  3229 		{
  3230 			s=parser.parString(ok,0);
  3231 			if (ok) setFrameType (s);
  3232 		}	
  3233 	/////////////////////////////////////////////////////////////////////
  3234 	} else if (com=="setFramePenColor")
  3235 	{
  3236 		if ( selection.type()!=Selection::Branch && selection.type()!= Selection::MapCenter && selection.type()!=Selection::FloatImage)
  3237 		{
  3238 			parser.setError (Aborted,"Type of selection does not allow setting of pen color");
  3239 		}
  3240 		else if (parser.checkParCount(1))
  3241 		{
  3242 			QColor c=parser.parColor(ok,0);
  3243 			if (ok) setFramePenColor (c);
  3244 		}	
  3245 	/////////////////////////////////////////////////////////////////////
  3246 	} else if (com=="setFrameBrushColor")
  3247 	{
  3248 		if ( selection.type()!=Selection::Branch && selection.type()!= Selection::MapCenter && selection.type()!=Selection::FloatImage)
  3249 		{
  3250 			parser.setError (Aborted,"Type of selection does not allow setting brush color");
  3251 		}
  3252 		else if (parser.checkParCount(1))
  3253 		{
  3254 			QColor c=parser.parColor(ok,0);
  3255 			if (ok) setFrameBrushColor (c);
  3256 		}	
  3257 	/////////////////////////////////////////////////////////////////////
  3258 	} else if (com=="setFramePadding")
  3259 	{
  3260 		if ( selection.type()!=Selection::Branch && selection.type()!= Selection::MapCenter && selection.type()!=Selection::FloatImage)
  3261 		{
  3262 			parser.setError (Aborted,"Type of selection does not allow setting frame padding");
  3263 		}
  3264 		else if (parser.checkParCount(1))
  3265 		{
  3266 			n=parser.parInt(ok,0);
  3267 			if (ok) setFramePadding(n);
  3268 		}	
  3269 	/////////////////////////////////////////////////////////////////////
  3270 	} else if (com=="setFrameBorderWidth")
  3271 	{
  3272 		if ( selection.type()!=Selection::Branch && selection.type()!= Selection::MapCenter && selection.type()!=Selection::FloatImage)
  3273 		{
  3274 			parser.setError (Aborted,"Type of selection does not allow setting frame border width");
  3275 		}
  3276 		else if (parser.checkParCount(1))
  3277 		{
  3278 			n=parser.parInt(ok,0);
  3279 			if (ok) setFrameBorderWidth (n);
  3280 		}	
  3281 	/////////////////////////////////////////////////////////////////////
  3282 	} else if (com=="setMapAuthor")
  3283 	{
  3284 		if (parser.checkParCount(1))
  3285 		{
  3286 			s=parser.parString(ok,0);
  3287 			if (ok) setAuthor (s);
  3288 		}	
  3289 	/////////////////////////////////////////////////////////////////////
  3290 	} else if (com=="setMapComment")
  3291 	{
  3292 		if (parser.checkParCount(1))
  3293 		{
  3294 			s=parser.parString(ok,0);
  3295 			if (ok) setComment(s);
  3296 		}	
  3297 	/////////////////////////////////////////////////////////////////////
  3298 	} else if (com=="setMapBackgroundColor")
  3299 	{
  3300 		if (selection.isEmpty() )
  3301 		{
  3302 			parser.setError (Aborted,"Nothing selected");
  3303 		} else if (! selection.getBranch() )
  3304 		{				  
  3305 			parser.setError (Aborted,"Type of selection is not a branch");
  3306 		} else if (parser.checkParCount(1))
  3307 		{
  3308 			QColor c=parser.parColor (ok,0);
  3309 			if (ok) setMapBackgroundColor (c);
  3310 		}	
  3311 	/////////////////////////////////////////////////////////////////////
  3312 	} else if (com=="setMapDefLinkColor")
  3313 	{
  3314 		if (selection.isEmpty() )
  3315 		{
  3316 			parser.setError (Aborted,"Nothing selected");
  3317 		} else if (! selb )
  3318 		{				  
  3319 			parser.setError (Aborted,"Type of selection is not a branch");
  3320 		} else if (parser.checkParCount(1))
  3321 		{
  3322 			QColor c=parser.parColor (ok,0);
  3323 			if (ok) setMapDefLinkColor (c);
  3324 		}	
  3325 	/////////////////////////////////////////////////////////////////////
  3326 	} else if (com=="setMapLinkStyle")
  3327 	{
  3328 		if (parser.checkParCount(1))
  3329 		{
  3330 			s=parser.parString (ok,0);
  3331 			if (ok) setMapLinkStyle(s);
  3332 		}	
  3333 	/////////////////////////////////////////////////////////////////////
  3334 	} else if (com=="setHeading")
  3335 	{
  3336 		if (selection.isEmpty() )
  3337 		{
  3338 			parser.setError (Aborted,"Nothing selected");
  3339 		} else if (! selb )
  3340 		{				  
  3341 			parser.setError (Aborted,"Type of selection is not a branch");
  3342 		} else if (parser.checkParCount(1))
  3343 		{
  3344 			s=parser.parString (ok,0);
  3345 			if (ok) 
  3346 				setHeading (s);
  3347 		}	
  3348 	/////////////////////////////////////////////////////////////////////
  3349 	} else if (com=="setHideExport")
  3350 	{
  3351 		if (selection.isEmpty() )
  3352 		{
  3353 			parser.setError (Aborted,"Nothing selected");
  3354 		} else if (selection.type()!=Selection::Branch && selection.type() != Selection::MapCenter &&selection.type()!=Selection::FloatImage)
  3355 		{				  
  3356 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3357 		} else if (parser.checkParCount(1))
  3358 		{
  3359 			b=parser.parBool(ok,0);
  3360 			if (ok) setHideExport (b);
  3361 		}
  3362 	/////////////////////////////////////////////////////////////////////
  3363 	} else if (com=="setIncludeImagesHorizontally")
  3364 	{ 
  3365 		if (selection.isEmpty() )
  3366 		{
  3367 			parser.setError (Aborted,"Nothing selected");
  3368 		} else if (! selb)
  3369 		{				  
  3370 			parser.setError (Aborted,"Type of selection is not a branch");
  3371 		} else if (parser.checkParCount(1))
  3372 		{
  3373 			b=parser.parBool(ok,0);
  3374 			if (ok) setIncludeImagesHor(b);
  3375 		}
  3376 	/////////////////////////////////////////////////////////////////////
  3377 	} else if (com=="setIncludeImagesVertically")
  3378 	{
  3379 		if (selection.isEmpty() )
  3380 		{
  3381 			parser.setError (Aborted,"Nothing selected");
  3382 		} else if (! selb)
  3383 		{				  
  3384 			parser.setError (Aborted,"Type of selection is not a branch");
  3385 		} else if (parser.checkParCount(1))
  3386 		{
  3387 			b=parser.parBool(ok,0);
  3388 			if (ok) setIncludeImagesVer(b);
  3389 		}
  3390 	/////////////////////////////////////////////////////////////////////
  3391 	} else if (com=="setHideLinkUnselected")
  3392 	{
  3393 		if (selection.isEmpty() )
  3394 		{
  3395 			parser.setError (Aborted,"Nothing selected");
  3396 		} else if ( selection.type()!=Selection::Branch && selection.type()!= Selection::MapCenter && selection.type()!=Selection::FloatImage)
  3397 		{				  
  3398 			parser.setError (Aborted,"Type of selection does not allow hiding the link");
  3399 		} else if (parser.checkParCount(1))
  3400 		{
  3401 			b=parser.parBool(ok,0);
  3402 			if (ok) setHideLinkUnselected(b);
  3403 		}
  3404 	/////////////////////////////////////////////////////////////////////
  3405 	} else if (com=="setSelectionColor")
  3406 	{
  3407 		if (parser.checkParCount(1))
  3408 		{
  3409 			QColor c=parser.parColor (ok,0);
  3410 			if (ok) setSelectionColorInt (c);
  3411 		}	
  3412 	/////////////////////////////////////////////////////////////////////
  3413 	} else if (com=="setURL")
  3414 	{
  3415 		if (selection.isEmpty() )
  3416 		{
  3417 			parser.setError (Aborted,"Nothing selected");
  3418 		} else if (! selb )
  3419 		{				  
  3420 			parser.setError (Aborted,"Type of selection is not a branch");
  3421 		} else if (parser.checkParCount(1))
  3422 		{
  3423 			s=parser.parString (ok,0);
  3424 			if (ok) setURL(s);
  3425 		}	
  3426 	/////////////////////////////////////////////////////////////////////
  3427 	} else if (com=="setVymLink")
  3428 	{
  3429 		if (selection.isEmpty() )
  3430 		{
  3431 			parser.setError (Aborted,"Nothing selected");
  3432 		} else if (! selb )
  3433 		{				  
  3434 			parser.setError (Aborted,"Type of selection is not a branch");
  3435 		} else if (parser.checkParCount(1))
  3436 		{
  3437 			s=parser.parString (ok,0);
  3438 			if (ok) setVymLink(s);
  3439 		}	
  3440 	}
  3441 	/////////////////////////////////////////////////////////////////////
  3442 	else if (com=="setFlag")
  3443 	{
  3444 		if (selection.isEmpty() )
  3445 		{
  3446 			parser.setError (Aborted,"Nothing selected");
  3447 		} else if (! selb )
  3448 		{				  
  3449 			parser.setError (Aborted,"Type of selection is not a branch");
  3450 		} else if (parser.checkParCount(1))
  3451 		{
  3452 			s=parser.parString(ok,0);
  3453 			if (ok) 
  3454 			{
  3455 				selb->activateStandardFlag(s);
  3456 				selb->updateFlagsToolbar();
  3457 			}	
  3458 		}
  3459 	/////////////////////////////////////////////////////////////////////
  3460 	} else if (com=="setFrameType")
  3461 	{
  3462 		if (selection.isEmpty() )
  3463 		{
  3464 			parser.setError (Aborted,"Nothing selected");
  3465 		} else if (! selb )
  3466 		{				  
  3467 			parser.setError (Aborted,"Type of selection is not a branch");
  3468 		} else if (parser.checkParCount(1))
  3469 		{
  3470 			s=parser.parString(ok,0);
  3471 			if (ok) 
  3472 				setFrameType (s);
  3473 		}
  3474 	/////////////////////////////////////////////////////////////////////
  3475 	} else if (com=="sortChildren")
  3476 	{
  3477 		if (selection.isEmpty() )
  3478 		{
  3479 			parser.setError (Aborted,"Nothing selected");
  3480 		} else if (! selb )
  3481 		{				  
  3482 			parser.setError (Aborted,"Type of selection is not a branch");
  3483 		} else if (parser.checkParCount(0))
  3484 		{
  3485 			sortChildren();
  3486 		}
  3487 	/////////////////////////////////////////////////////////////////////
  3488 	} else if (com=="toggleFlag")
  3489 	{
  3490 		if (selection.isEmpty() )
  3491 		{
  3492 			parser.setError (Aborted,"Nothing selected");
  3493 		} else if (! selb )
  3494 		{				  
  3495 			parser.setError (Aborted,"Type of selection is not a branch");
  3496 		} else if (parser.checkParCount(1))
  3497 		{
  3498 			s=parser.parString(ok,0);
  3499 			if (ok) 
  3500 			{
  3501 				selb->toggleStandardFlag(s);	
  3502 				selb->updateFlagsToolbar();
  3503 			}	
  3504 		}
  3505 	/////////////////////////////////////////////////////////////////////
  3506 	} else if (com=="unscroll")
  3507 	{
  3508 		if (selection.isEmpty() )
  3509 		{
  3510 			parser.setError (Aborted,"Nothing selected");
  3511 		} else if (! selb )
  3512 		{				  
  3513 			parser.setError (Aborted,"Type of selection is not a branch");
  3514 		} else if (parser.checkParCount(0))
  3515 		{	
  3516 			if (!unscrollBranch (selb))	
  3517 				parser.setError (Aborted,"Could not unscroll branch");
  3518 		}	
  3519 	/////////////////////////////////////////////////////////////////////
  3520 	} else if (com=="unscrollChildren")
  3521 	{
  3522 		if (selection.isEmpty() )
  3523 		{
  3524 			parser.setError (Aborted,"Nothing selected");
  3525 		} else if (! selb )
  3526 		{				  
  3527 			parser.setError (Aborted,"Type of selection is not a branch");
  3528 		} else if (parser.checkParCount(0))
  3529 		{	
  3530 			unscrollChildren ();
  3531 		}	
  3532 	/////////////////////////////////////////////////////////////////////
  3533 	} else if (com=="unsetFlag")
  3534 	{
  3535 		if (selection.isEmpty() )
  3536 		{
  3537 			parser.setError (Aborted,"Nothing selected");
  3538 		} else if (! selb )
  3539 		{				  
  3540 			parser.setError (Aborted,"Type of selection is not a branch");
  3541 		} else if (parser.checkParCount(1))
  3542 		{
  3543 			s=parser.parString(ok,0);
  3544 			if (ok) 
  3545 			{
  3546 				selb->deactivateStandardFlag(s);
  3547 				selb->updateFlagsToolbar();
  3548 			}	
  3549 		}
  3550 	} else
  3551 		parser.setError (Aborted,"Unknown command");
  3552 
  3553 	// Any errors?
  3554 	if (parser.errorLevel()==NoError)
  3555 	{
  3556 		// setChanged();  FIXME should not be called e.g. for export?!
  3557 		reposition();
  3558 	}	
  3559 	else	
  3560 	{
  3561 		// TODO Error handling
  3562 		qWarning("VymModel::parseAtom: Error!");
  3563 		qWarning(parser.errorMessage());
  3564 	} 
  3565 }
  3566 
  3567 void VymModel::runScript (QString script)
  3568 {
  3569 	parser.setScript (script);
  3570 	parser.runScript();
  3571 	while (parser.next() ) 
  3572 		parseAtom(parser.getAtom());
  3573 }
  3574 
  3575 void VymModel::setExportMode (bool b)
  3576 {
  3577 	// should be called before and after exports
  3578 	// depending on the settings
  3579 	if (b && settings.value("/export/useHideExport","true")=="true")
  3580 		setHideTmpMode (HideExport);
  3581 	else	
  3582 		setHideTmpMode (HideNone);
  3583 }
  3584 
  3585 void VymModel::exportImage(QString fname, bool askName, QString format)
  3586 {
  3587 	if (fname=="")
  3588 	{
  3589 		fname=getMapName()+".png";
  3590 		format="PNG";
  3591 	} 	
  3592 
  3593 	if (askName)
  3594 	{
  3595 		QStringList fl;
  3596 		QFileDialog *fd=new QFileDialog (NULL);
  3597 		fd->setCaption (tr("Export map as image"));
  3598 		fd->setDirectory (lastImageDir);
  3599 		fd->setFileMode(QFileDialog::AnyFile);
  3600 		fd->setFilters  (imageIO.getFilters() );
  3601 		if (fd->exec())
  3602 		{
  3603 			fl=fd->selectedFiles();
  3604 			fname=fl.first();
  3605 			format=imageIO.getType(fd->selectedFilter());
  3606 		} 
  3607 	}
  3608 
  3609 	setExportMode (true);
  3610 	QPixmap pix (getPixmap());
  3611 	pix.save(fname, format);
  3612 	setExportMode (false);
  3613 }
  3614 
  3615 
  3616 void VymModel::exportXML(QString dir, bool askForName)
  3617 {
  3618 	if (askForName)
  3619 	{
  3620 		dir=browseDirectory(NULL,tr("Export XML to directory"));
  3621 		if (dir =="" && !reallyWriteDirectory(dir) )
  3622 		return;
  3623 	}
  3624 
  3625 	// Hide stuff during export, if settings want this
  3626 	setExportMode (true);
  3627 
  3628 	// Create subdirectories
  3629 	makeSubDirs (dir);
  3630 
  3631 	// write to directory
  3632 	QString saveFile=saveToDir (dir,mapName+"-",true,getTotalBBox().topLeft() ,NULL);
  3633 	QFile file;
  3634 
  3635 	file.setName ( dir + "/"+mapName+".xml");
  3636 	if ( !file.open( QIODevice::WriteOnly ) )
  3637 	{
  3638 		// This should neverever happen
  3639 		QMessageBox::critical (0,tr("Critical Export Error"),tr("VymModel::exportXML couldn't open %1").arg(file.name()));
  3640 		return;
  3641 	}	
  3642 
  3643 	// Write it finally, and write in UTF8, no matter what 
  3644 	QTextStream ts( &file );
  3645 	ts.setEncoding (QTextStream::UnicodeUTF8);
  3646 	ts << saveFile;
  3647 	file.close();
  3648 
  3649 	// Now write image, too
  3650 	exportImage (dir+"/images/"+mapName+".png",false,"PNG");
  3651 
  3652 	setExportMode (false);
  3653 }
  3654 
  3655 void VymModel::exportASCII(QString fname,bool askName)
  3656 {
  3657 	ExportASCII ex;
  3658 	ex.setModel (this);
  3659 	if (fname=="") 
  3660 		ex.setFile (mapName+".txt");	
  3661 	else
  3662 		ex.setFile (fname);
  3663 
  3664 	if (askName)
  3665 	{
  3666 		//ex.addFilter ("TXT (*.txt)");
  3667 		ex.setDir(lastImageDir);
  3668 		//ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
  3669 		ex.execDialog() ; 
  3670 	} 
  3671 	if (!ex.canceled())
  3672 	{
  3673 		setExportMode(true);
  3674 		ex.doExport();
  3675 		setExportMode(false);
  3676 	}
  3677 }
  3678 
  3679 void VymModel::exportXHTML (const QString &dir, bool askForName)
  3680 {
  3681 			ExportXHTMLDialog dia(NULL);
  3682 			dia.setFilePath (filePath );
  3683 			dia.setMapName (mapName );
  3684 			dia.readSettings();
  3685 			if (dir!="") dia.setDir (dir);
  3686 
  3687 			bool ok=true;
  3688 			
  3689 			if (askForName)
  3690 			{
  3691 				if (dia.exec()!=QDialog::Accepted) 
  3692 					ok=false;
  3693 				else	
  3694 				{
  3695 					QDir d (dia.getDir());
  3696 					// Check, if warnings should be used before overwriting
  3697 					// the output directory
  3698 					if (d.exists() && d.count()>0)
  3699 					{
  3700 						WarningDialog warn;
  3701 						warn.showCancelButton (true);
  3702 						warn.setText(QString(
  3703 							"The directory %1 is not empty.\n"
  3704 							"Do you risk to overwrite some of its contents?").arg(d.path() ));
  3705 						warn.setCaption("Warning: Directory not empty");
  3706 						warn.setShowAgainName("mainwindow/overwrite-dir-xhtml");
  3707 
  3708 						if (warn.exec()!=QDialog::Accepted) ok=false;
  3709 					}
  3710 				}	
  3711 			}
  3712 
  3713 			if (ok)
  3714 			{
  3715 				exportXML (dia.getDir(),false );
  3716 				dia.doExport(mapName );
  3717 				//if (dia.hasChanged()) setChanged();
  3718 			}
  3719 }
  3720 
  3721 void VymModel::exportOOPresentation(const QString &fn, const QString &cf)
  3722 {
  3723 	ExportOO ex;
  3724 	ex.setFile (fn);
  3725 	ex.setModel (this);
  3726 	if (ex.setConfigFile(cf)) 
  3727 	{
  3728 		setExportMode (true);
  3729 		ex.exportPresentation();
  3730 		setExportMode (false);
  3731 	}
  3732 }
  3733 
  3734 
  3735 
  3736 
  3737 //////////////////////////////////////////////
  3738 // View related
  3739 //////////////////////////////////////////////
  3740 
  3741 void VymModel::registerEditor(QWidget *me)
  3742 {
  3743 	mapEditor=(MapEditor*)me;
  3744 	for (int i=0; i<mapCenters.count(); i++)
  3745 		mapCenters.at(i)->setMapEditor(mapEditor);
  3746 }
  3747 
  3748 void VymModel::unregisterEditor(QWidget *)
  3749 {
  3750 	mapEditor=NULL;
  3751 }
  3752 
  3753 void VymModel::setContextPos(QPointF p)
  3754 {
  3755 	contextPos=p;
  3756 }
  3757 
  3758 void VymModel::unsetContextPos()
  3759 {
  3760 	contextPos=QPointF();
  3761 }
  3762 
  3763 void VymModel::updateNoteFlag()
  3764 {
  3765 	setChanged();
  3766 	BranchObj *bo=selection.getBranch();
  3767 	if (bo) 
  3768 	{
  3769 		bo->updateNoteFlag();
  3770 		mainWindow->updateActions();
  3771 	}	
  3772 }
  3773 
  3774 void VymModel::updateRelPositions()
  3775 {
  3776 	for (int i=0; i<mapCenters.count(); i++)
  3777 		mapCenters.at(i)->updateRelPositions();
  3778 }
  3779 
  3780 void VymModel::reposition()
  3781 {
  3782 	for (int i=0;i<mapCenters.count(); i++)
  3783 		mapCenters.at(i)->reposition();	//	for positioning heading
  3784 }
  3785 
  3786 QPolygonF VymModel::shape(BranchObj *bo)
  3787 {
  3788 	// Creating (arbitrary) shapes
  3789 
  3790 	QPolygonF p;
  3791 	QRectF rb=bo->getBBox();
  3792 	if (bo->getDepth()==0)
  3793 	{
  3794 		// Just take BBox of this mapCenter
  3795 		p<<rb.topLeft()<<rb.topRight()<<rb.bottomRight()<<rb.bottomLeft();
  3796 		return p;
  3797 	}
  3798 
  3799 	// Take union of BBox and TotalBBox 
  3800 
  3801 	QRectF ra=bo->getTotalBBox();
  3802 	if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
  3803 		p   <<ra.bottomLeft()
  3804 			<<ra.topLeft()
  3805 			<<QPointF (rb.topLeft().x(), ra.topLeft().y() )
  3806 			<<rb.topRight()
  3807 			<<rb.bottomRight()
  3808 			<<QPointF (rb.bottomLeft().x(), ra.bottomLeft().y() ) ;
  3809 	else		
  3810 		p   <<ra.bottomRight()
  3811 			<<ra.topRight()
  3812 			<<QPointF (rb.topRight().x(), ra.topRight().y() )
  3813 			<<rb.topLeft()
  3814 			<<rb.bottomLeft()
  3815 			<<QPointF (rb.bottomRight().x(), ra.bottomRight().y() ) ;
  3816 	return p;		
  3817 
  3818 }
  3819 
  3820 void VymModel::moveAway(LinkableMapObj *lmo)
  3821 {
  3822 	// Autolayout:
  3823 	//
  3824 	// Move all branches and MapCenters away from lmo 
  3825 	// to avoid collisions 
  3826 
  3827 	QPolygonF pA;
  3828 	QPolygonF pB;
  3829 
  3830 	BranchObj *boA=(BranchObj*)lmo;
  3831 	BranchObj *boB;
  3832 	for (int i=0; i<mapCenters.count(); i++)
  3833 	{
  3834 		boB=mapCenters.at(i);
  3835 		pA=shape (boA);
  3836 		pB=shape (boB);
  3837 		PolygonCollisionResult r = PolygonCollision(pA, pB, QPoint(0,0));
  3838 		cout <<"------->"
  3839 			<<"="<<r.intersect
  3840 			<<"  ("<<qPrintable(boA->getHeading() )<<")"
  3841 			<<"  with ("<< qPrintable (boB->getHeading() )
  3842 			<<")  willIntersect"
  3843 			<<r.willIntersect 
  3844 			<<"  minT="<<r.minTranslation<<endl<<endl;
  3845 	}
  3846 }
  3847 
  3848 QPixmap VymModel::getPixmap()
  3849 {
  3850 	QRectF mapRect=getTotalBBox();
  3851 	QPixmap pix((int)mapRect.width()+2,(int)mapRect.height()+1);
  3852 	QPainter pp (&pix);
  3853 	
  3854 	pp.setRenderHints(mapEditor->renderHints());
  3855 
  3856 	// Don't print the visualisation of selection
  3857 	selection.unselect();
  3858 
  3859 	mapScene->render (	&pp, 
  3860 		QRectF(0,0,mapRect.width()+2,mapRect.height()+2),
  3861 		QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
  3862 
  3863 	// Restore selection
  3864 	selection.reselect();
  3865 	
  3866 	return pix;
  3867 }
  3868 
  3869 
  3870 void VymModel::setMapLinkStyle (const QString & s)
  3871 {
  3872 	QString snow;
  3873 	switch (linkstyle)
  3874 	{
  3875 		case LinkableMapObj::Line :
  3876 			snow="StyleLine";
  3877 			break;
  3878 		case LinkableMapObj::Parabel:
  3879 			snow="StyleParabel";
  3880 			break;
  3881 		case LinkableMapObj::PolyLine:
  3882 			snow="StylePolyLine";
  3883 			break;
  3884 		case LinkableMapObj::PolyParabel:
  3885 			snow="StylePolyParabel";
  3886 			break;
  3887 		default:	
  3888 			snow="UndefinedStyle";
  3889 			break;
  3890 	}
  3891 
  3892 	saveState (
  3893 		QString("setMapLinkStyle (\"%1\")").arg(s),
  3894 		QString("setMapLinkStyle (\"%1\")").arg(snow),
  3895 		QString("Set map link style (\"%1\")").arg(s)
  3896 	);	
  3897 
  3898 	if (s=="StyleLine")
  3899 		linkstyle=LinkableMapObj::Line;
  3900 	else if (s=="StyleParabel")
  3901 		linkstyle=LinkableMapObj::Parabel;
  3902 	else if (s=="StylePolyLine")
  3903 		linkstyle=LinkableMapObj::PolyLine;
  3904 	else if (s=="StylePolyParabel")	
  3905 		linkstyle=LinkableMapObj::PolyParabel;
  3906 	else
  3907 		linkstyle=LinkableMapObj::UndefinedStyle;
  3908 
  3909 	BranchObj *bo;
  3910 	bo=first();
  3911 	bo=next(bo);
  3912 	while (bo) 
  3913 	{
  3914 		bo->setLinkStyle(bo->getDefLinkStyle());
  3915 		bo=next(bo);
  3916 	}
  3917 	reposition();
  3918 }
  3919 
  3920 LinkableMapObj::Style VymModel::getMapLinkStyle ()
  3921 {
  3922 	return linkstyle;
  3923 }	
  3924 
  3925 void VymModel::setMapDefLinkColor(QColor col)
  3926 {
  3927 	if ( !col.isValid() ) return;
  3928 	saveState (
  3929 		QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
  3930 		QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
  3931 		QString("Set map link color to %1").arg(col.name())
  3932 	);
  3933 
  3934 	defLinkColor=col;
  3935 	BranchObj *bo;
  3936 	bo=first();
  3937 	while (bo) 
  3938 	{
  3939 		bo->setLinkColor();
  3940 		bo=next(bo);
  3941 	}
  3942 	updateActions();
  3943 }
  3944 
  3945 void VymModel::setMapLinkColorHintInt()
  3946 {
  3947 	// called from setMapLinkColorHint(lch) or at end of parse
  3948 	BranchObj *bo;
  3949 	bo=first();
  3950 	while (bo) 
  3951 	{
  3952 		bo->setLinkColor();
  3953 		bo=next(bo);
  3954 	}
  3955 }
  3956 
  3957 void VymModel::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
  3958 {
  3959 	linkcolorhint=lch;
  3960 	setMapLinkColorHintInt();
  3961 }
  3962 
  3963 void VymModel::toggleMapLinkColorHint()
  3964 {
  3965 	if (linkcolorhint==LinkableMapObj::HeadingColor)
  3966 		linkcolorhint=LinkableMapObj::DefaultColor;
  3967 	else	
  3968 		linkcolorhint=LinkableMapObj::HeadingColor;
  3969 	BranchObj *bo;
  3970 	bo=first();
  3971 	while (bo) 
  3972 	{
  3973 		bo->setLinkColor();
  3974 		bo=next(bo);
  3975 	}
  3976 }
  3977 
  3978 void VymModel::selectMapBackgroundImage ()
  3979 {
  3980 	Q3FileDialog *fd=new Q3FileDialog( NULL);
  3981 	fd->setMode (Q3FileDialog::ExistingFile);
  3982 	fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  3983 	ImagePreview *p =new ImagePreview (fd);
  3984 	fd->setContentsPreviewEnabled( TRUE );
  3985 	fd->setContentsPreview( p, p );
  3986 	fd->setPreviewMode( Q3FileDialog::Contents );
  3987 	fd->setCaption(vymName+" - " +tr("Load background image"));
  3988 	fd->setDir (lastImageDir);
  3989 	fd->show();
  3990 
  3991 	if ( fd->exec() == QDialog::Accepted )
  3992 	{
  3993 		// TODO selectMapBackgroundImg in QT4 use:	lastImageDir=fd->directory();
  3994 		lastImageDir=QDir (fd->dirPath());
  3995 		setMapBackgroundImage (fd->selectedFile());
  3996 	}
  3997 }	
  3998 
  3999 void VymModel::setMapBackgroundImage (const QString &fn)	//FIXME missing savestate
  4000 {
  4001 	QColor oldcol=mapScene->backgroundBrush().color();
  4002 	/*
  4003 	saveState(
  4004 		selection,
  4005 		QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
  4006 		selection,
  4007 		QString ("setMapBackgroundImage (%1)").arg(col.name()),
  4008 		QString("Set background color of map to %1").arg(col.name()));
  4009 	*/	
  4010 	QBrush brush;
  4011 	brush.setTextureImage (QPixmap (fn));
  4012 	mapScene->setBackgroundBrush(brush);
  4013 }
  4014 
  4015 void VymModel::selectMapBackgroundColor()
  4016 {
  4017 	QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), NULL);
  4018 	if ( !col.isValid() ) return;
  4019 	setMapBackgroundColor( col );
  4020 }
  4021 
  4022 
  4023 void VymModel::setMapBackgroundColor(QColor col)
  4024 {
  4025 	QColor oldcol=mapScene->backgroundBrush().color();
  4026 	saveState(
  4027 		QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
  4028 		QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
  4029 		QString("Set background color of map to %1").arg(col.name()));
  4030 	mapScene->setBackgroundBrush(col);
  4031 }
  4032 
  4033 QColor VymModel::getMapBackgroundColor()
  4034 {
  4035     return mapScene->backgroundBrush().color();
  4036 }
  4037 
  4038 
  4039 LinkableMapObj::ColorHint VymModel::getMapLinkColorHint()
  4040 {
  4041 	return linkcolorhint;
  4042 }
  4043 
  4044 QColor VymModel::getMapDefLinkColor()
  4045 {
  4046 	return defLinkColor;
  4047 }
  4048 
  4049 void VymModel::setMapDefXLinkColor(QColor col)
  4050 {
  4051 	defXLinkColor=col;
  4052 }
  4053 
  4054 QColor VymModel::getMapDefXLinkColor()
  4055 {
  4056 	return defXLinkColor;
  4057 }
  4058 
  4059 void VymModel::setMapDefXLinkWidth (int w)
  4060 {
  4061 	defXLinkWidth=w;
  4062 }
  4063 
  4064 int VymModel::getMapDefXLinkWidth()
  4065 {
  4066 	return defXLinkWidth;
  4067 }
  4068 
  4069 void VymModel::move(const double &x, const double &y)
  4070 {
  4071 	LinkableMapObj *sel=selection.single();
  4072 	if (sel)
  4073 	{
  4074         QPointF ap(sel->getAbsPos());
  4075         QPointF to(x, y);
  4076         if (ap != to)
  4077         {
  4078             QString ps=qpointfToString(ap);
  4079             QString s=selection.getSelectString();
  4080             saveState(
  4081                 s, "move "+ps, 
  4082                 s, "move "+qpointfToString(to), 
  4083                 QString("Move %1 to %2").arg(getObjectName(sel)).arg(ps));
  4084             sel->move(x,y);
  4085             reposition();
  4086             selection.update();
  4087         }
  4088 	}
  4089 }
  4090 
  4091 void VymModel::moveRel (const double &x, const double &y)
  4092 {
  4093 	LinkableMapObj *sel=selection.single();
  4094 	if (sel)
  4095 	{
  4096         QPointF rp(sel->getRelPos());
  4097         QPointF to(x, y);
  4098         if (rp != to)
  4099         {
  4100             QString ps=qpointfToString (sel->getRelPos());
  4101             QString s=getSelectString(sel);
  4102             saveState(
  4103                 s, "moveRel "+ps, 
  4104                 s, "moveRel "+qpointfToString(to), 
  4105                 QString("Move %1 to relative position %2").arg(getObjectName(sel)).arg(ps));
  4106             ((OrnamentedObj*)sel)->move2RelPos (x,y);
  4107             reposition();
  4108             sel->updateLink();
  4109             selection.update();
  4110         }
  4111 	}
  4112 }
  4113 
  4114 
  4115 void VymModel::animate()
  4116 {
  4117 	animationTimer->stop();
  4118 	BranchObj *bo;
  4119 	int i=0;
  4120 	while (i<animObjList.size() )
  4121 	{
  4122 		bo=(BranchObj*)animObjList.at(i);
  4123 		if (!bo->animate())
  4124 		{
  4125 			if (i>=0) 
  4126 			{	
  4127 				animObjList.removeAt(i);
  4128 				i--;
  4129 			}
  4130 		}
  4131 		bo->reposition();
  4132 		i++;
  4133 	} 
  4134 	mapEditor->updateSelection();
  4135 	mapScene->update();
  4136 	if (!animObjList.isEmpty()) animationTimer->start();
  4137 }
  4138 
  4139 
  4140 void VymModel::startAnimation(BranchObj *bo, const QPointF &start, const QPointF &dest)
  4141 {
  4142 	if (bo && bo->getDepth()>0) 
  4143 	{
  4144 		AnimPoint ap;
  4145 		ap.setStart (start);
  4146 		ap.setDest  (dest);
  4147 		ap.setTicks (animationTicks);
  4148 		ap.setAnimated (true);
  4149 		bo->setAnimation (ap);
  4150 		animObjList.append( bo );
  4151 		animationTimer->setSingleShot (true);
  4152 		animationTimer->start(animationInterval);
  4153 	}
  4154 }
  4155 
  4156 void VymModel::stopAnimation (MapObj *mo)
  4157 {
  4158 	int i=animObjList.indexOf(mo);
  4159     if (i>=0)
  4160 		animObjList.removeAt (i);
  4161 }
  4162 
  4163 void VymModel::sendSelection()
  4164 {
  4165 	if (netstate!=Server) return;
  4166 	sendData (QString("select (\"%1\")").arg(selection.getSelectString()) );
  4167 }
  4168 
  4169 void VymModel::newServer()
  4170 {
  4171 	port=54321;
  4172 	sendCounter=0;
  4173     tcpServer = new QTcpServer(this);
  4174     if (!tcpServer->listen(QHostAddress::Any,port)) {
  4175         QMessageBox::critical(NULL, "vym server",
  4176                               QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
  4177         //FIXME needed? we are no widget any longer... close();
  4178         return;
  4179     }
  4180 	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
  4181 	netstate=Server;
  4182 	cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
  4183 }
  4184 
  4185 void VymModel::connectToServer()
  4186 {
  4187 	port=54321;
  4188 	server="salam.suse.de";
  4189 	server="localhost";
  4190 	clientSocket = new QTcpSocket (this);
  4191 	clientSocket->abort();
  4192     clientSocket->connectToHost(server ,port);
  4193 	connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
  4194     connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
  4195             this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
  4196 	netstate=Client;		
  4197 	cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
  4198 
  4199 	
  4200 }
  4201 
  4202 void VymModel::newClient()
  4203 {
  4204     QTcpSocket *newClient = tcpServer->nextPendingConnection();
  4205     connect(newClient, SIGNAL(disconnected()),
  4206             newClient, SLOT(deleteLater()));
  4207 
  4208 	cout <<"ME::newClient  at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
  4209 
  4210 	clientList.append (newClient);
  4211 }
  4212 
  4213 
  4214 void VymModel::sendData(const QString &s)
  4215 {
  4216 	if (clientList.size()==0) return;
  4217 
  4218 	// Create bytearray to send
  4219 	QByteArray block;
  4220     QDataStream out(&block, QIODevice::WriteOnly);
  4221     out.setVersion(QDataStream::Qt_4_0);
  4222 
  4223 	// Reserve some space for blocksize
  4224     out << (quint16)0;
  4225 
  4226 	// Write sendCounter
  4227     out << sendCounter++;
  4228 
  4229 	// Write data
  4230     out << s;
  4231 
  4232 	// Go back and write blocksize so far
  4233     out.device()->seek(0);
  4234     quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
  4235 	out << bs;
  4236 
  4237 	if (debug)
  4238 		cout << "ME::sendData  bs="<<bs<<"  counter="<<sendCounter<<"  s="<<qPrintable(s)<<endl;
  4239 
  4240 	for (int i=0; i<clientList.size(); ++i)
  4241 	{
  4242 		//cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
  4243 		clientList.at(i)->write (block);
  4244 	}
  4245 }
  4246 
  4247 void VymModel::readData ()
  4248 {
  4249 	while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
  4250 	{
  4251 		if (debug)
  4252 			cout <<"readData  bytesAvail="<<clientSocket->bytesAvailable();
  4253 		quint16 recCounter;
  4254 		quint16 blockSize;
  4255 
  4256 		QDataStream in(clientSocket);
  4257 		in.setVersion(QDataStream::Qt_4_0);
  4258 
  4259 		in >> blockSize;
  4260 		in >> recCounter;
  4261 		
  4262 		QString t;
  4263 		in >>t;
  4264 		if (debug)
  4265 			cout << "  t="<<qPrintable (t)<<endl;
  4266 		parseAtom (t);
  4267 	}
  4268 	return;
  4269 }
  4270 
  4271 void VymModel::displayNetworkError(QAbstractSocket::SocketError socketError)
  4272 {
  4273     switch (socketError) {
  4274     case QAbstractSocket::RemoteHostClosedError:
  4275         break;
  4276     case QAbstractSocket::HostNotFoundError:
  4277         QMessageBox::information(NULL, vymName +" Network client",
  4278                                  "The host was not found. Please check the "
  4279                                     "host name and port settings.");
  4280         break;
  4281     case QAbstractSocket::ConnectionRefusedError:
  4282         QMessageBox::information(NULL, vymName + " Network client",
  4283                                  "The connection was refused by the peer. "
  4284                                     "Make sure the fortune server is running, "
  4285                                     "and check that the host name and port "
  4286                                     "settings are correct.");
  4287         break;
  4288     default:
  4289         QMessageBox::information(NULL, vymName + " Network client",
  4290                                  QString("The following error occurred: %1.")
  4291                                  .arg(clientSocket->errorString()));
  4292     }
  4293 }
  4294 
  4295 
  4296 
  4297 
  4298 void VymModel::selectMapSelectionColor()
  4299 {
  4300 	QColor col = QColorDialog::getColor( defLinkColor, NULL);
  4301 	setSelectionColor (col);
  4302 }
  4303 
  4304 void VymModel::setSelectionColorInt (QColor col)
  4305 {
  4306 	if ( !col.isValid() ) return;
  4307 	saveState (
  4308 		QString("setSelectionColor (%1)").arg(selection.getColor().name()),
  4309 		QString("setSelectionColor (%1)").arg(col.name()),
  4310 		QString("Set color of selection box to %1").arg(col.name())
  4311 	);
  4312 
  4313 	selection.setColor (col);
  4314 }
  4315 
  4316 void VymModel::updateSelection()
  4317 {
  4318 	selection.update();
  4319 }
  4320 
  4321 void VymModel::setSelectionColor(QColor col)
  4322 {
  4323 	if ( !col.isValid() ) return;
  4324 	saveState (
  4325 		QString("setSelectionColor (%1)").arg(selection.getColor().name()),
  4326 		QString("setSelectionColor (%1)").arg(col.name()),
  4327 		QString("Set color of selection box to %1").arg(col.name())
  4328 	);
  4329 	setSelectionColorInt (col);
  4330 }
  4331 
  4332 QColor VymModel::getSelectionColor()
  4333 {
  4334 	return selection.getColor();
  4335 }
  4336 
  4337 void VymModel::setHideTmpMode (HideTmpMode mode)
  4338 {
  4339 	hidemode=mode;
  4340 	for (int i=0;i<mapCenters.count(); i++)
  4341 		mapCenters.at(i)->setHideTmp (mode);	
  4342 	reposition();
  4343 	// FIXME needed? scene()->update();
  4344 }
  4345 
  4346 
  4347 QRectF VymModel::getTotalBBox()
  4348 {
  4349 	QRectF r;
  4350 	for (int i=0;i<mapCenters.count(); i++)
  4351 		r=addBBox (mapCenters.at(i)->getTotalBBox(), r);
  4352 	return r;	
  4353 }
  4354 
  4355 //////////////////////////////////////////////
  4356 // Selection related
  4357 //////////////////////////////////////////////
  4358 
  4359 void VymModel::setSelectionModel (QItemSelectionModel *sm)
  4360 {
  4361 	selModel=sm;
  4362 }
  4363 
  4364 void VymModel::setSelectionBlocked (bool b)
  4365 {
  4366 	if (b)
  4367 		selection.block();
  4368 	else	
  4369 		selection.unblock();
  4370 }
  4371 
  4372 bool VymModel::isSelectionBlocked()
  4373 {
  4374 	return selection.isBlocked();
  4375 }
  4376 
  4377 bool VymModel::select ()
  4378 {
  4379 	QModelIndex index=selModel->selectedIndexes().first();	// TODO no multiselections yet
  4380 
  4381 	TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
  4382 	return select (item->getLMO() );
  4383 }
  4384 
  4385 bool VymModel::select (const QString &s)
  4386 {
  4387 	if (selection.select(s))
  4388 	{
  4389 		selection.update();
  4390 		ensureSelectionVisible();
  4391 		sendSelection ();
  4392 		return true;
  4393 	}
  4394 	return false;
  4395 
  4396 }
  4397 
  4398 bool VymModel::select (LinkableMapObj *lmo)
  4399 {
  4400 	if (selection.select(lmo))
  4401 	{
  4402 		selection.update();
  4403 		ensureSelectionVisible();
  4404 		sendSelection ();
  4405 		return true;
  4406 	}
  4407 	return false;
  4408 }
  4409 
  4410 void VymModel::unselect()
  4411 {
  4412 	selection.unselect();
  4413 }	
  4414 
  4415 void VymModel::reselect()
  4416 {
  4417 	selection.reselect();
  4418 }	
  4419 
  4420 void VymModel::ensureSelectionVisible()
  4421 {
  4422 	LinkableMapObj *lmo=selection.single();
  4423 	if (lmo &&mapEditor) mapEditor->ensureVisible (lmo->getBBox() );
  4424 	
  4425 }
  4426 
  4427 void VymModel::selectInt (LinkableMapObj *lmo)
  4428 {
  4429 	if (selection.select(lmo))
  4430 	{
  4431 		selection.update();
  4432 		sendSelection ();
  4433 	}
  4434 }
  4435 
  4436 
  4437 void VymModel::selectNextBranchInt()
  4438 {
  4439 	// Increase number of branch
  4440 	LinkableMapObj *sel=selection.single();
  4441 	if (sel)
  4442 	{
  4443 		QString s=selection.getSelectString();
  4444 		QString part;
  4445 		QString typ;
  4446 		QString num;
  4447 
  4448 		// Where am I? 
  4449 		part=s.section(",",-1);
  4450 		typ=part.left (3);
  4451 		num=part.right(part.length() - 3);
  4452 
  4453 		s=s.left (s.length() -num.length());
  4454 
  4455 		// Go to next lmo
  4456 		num=QString ("%1").arg(num.toUInt()+1);
  4457 
  4458 		s=s+num;
  4459 		
  4460 		// Try to select this one
  4461 		if (select (s)) return;
  4462 
  4463 		// We have no direct successor, 
  4464 		// try to increase the parental number in order to
  4465 		// find a successor with same depth
  4466 
  4467 		int d=selection.single()->getDepth();
  4468 		int oldDepth=d;
  4469 		int i;
  4470 		bool found=false;
  4471 		bool b;
  4472 		while (!found && d>0)
  4473 		{
  4474 			s=s.section (",",0,d-1);
  4475 			// replace substring of current depth in s with "1"
  4476 			part=s.section(",",-1);
  4477 			typ=part.left (3);
  4478 			num=part.right(part.length() - 3);
  4479 
  4480 			if (d>1)
  4481 			{	
  4482 				// increase number of parent
  4483 				num=QString ("%1").arg(num.toUInt()+1);
  4484 				s=s.section (",",0,d-2) + ","+ typ+num;
  4485 			} else
  4486 			{
  4487 				// Special case, look at orientation
  4488 				if (selection.single()->getOrientation()==LinkableMapObj::RightOfCenter)
  4489 					num=QString ("%1").arg(num.toUInt()+1);
  4490 				else	
  4491 					num=QString ("%1").arg(num.toUInt()-1);
  4492 				s=typ+num;
  4493 			}	
  4494 
  4495 			if (select (s))
  4496 				// pad to oldDepth, select the first branch for each depth
  4497 				for (i=d;i<oldDepth;i++)
  4498 				{
  4499 					b=select (s);
  4500 					if (b)
  4501 					{	
  4502 						if ( selection.getBranch()->countBranches()>0)
  4503 							s+=",bo:0";
  4504 						else	
  4505 							break;
  4506 					} else
  4507 						break;
  4508 				}	
  4509 
  4510 			// try to select the freshly built string
  4511 			found=select(s);
  4512 			d--;
  4513 		}
  4514 		return;
  4515 	}	
  4516 }
  4517 
  4518 void VymModel::selectPrevBranchInt()
  4519 {
  4520 	// Decrease number of branch
  4521 	BranchObj *bo=selection.getBranch();
  4522 	if (bo)
  4523 	{
  4524 		QString s=selection.getSelectString();
  4525 		QString part;
  4526 		QString typ;
  4527 		QString num;
  4528 
  4529 		// Where am I? 
  4530 		part=s.section(",",-1);
  4531 		typ=part.left (3);
  4532 		num=part.right(part.length() - 3);
  4533 
  4534 		s=s.left (s.length() -num.length());
  4535 
  4536 		int n=num.toInt()-1;
  4537 		
  4538 		// Go to next lmo
  4539 		num=QString ("%1").arg(n);
  4540 		s=s+num;
  4541 		
  4542 		// Try to select this one
  4543 		if (n>=0 && select (s)) return;
  4544 
  4545 		// We have no direct precessor, 
  4546 		// try to decrease the parental number in order to
  4547 		// find a precessor with same depth
  4548 
  4549 		int d=selection.single()->getDepth();
  4550 		int oldDepth=d;
  4551 		int i;
  4552 		bool found=false;
  4553 		bool b;
  4554 		while (!found && d>0)
  4555 		{
  4556 			s=s.section (",",0,d-1);
  4557 			// replace substring of current depth in s with "1"
  4558 			part=s.section(",",-1);
  4559 			typ=part.left (3);
  4560 			num=part.right(part.length() - 3);
  4561 
  4562 			if (d>1)
  4563 			{
  4564 				// decrease number of parent
  4565 				num=QString ("%1").arg(num.toInt()-1);
  4566 				s=s.section (",",0,d-2) + ","+ typ+num;
  4567 			} else
  4568 			{
  4569 				// Special case, look at orientation
  4570 				if (selection.single()->getOrientation()==LinkableMapObj::RightOfCenter)
  4571 					num=QString ("%1").arg(num.toInt()-1);
  4572 				else	
  4573 					num=QString ("%1").arg(num.toInt()+1);
  4574 				s=typ+num;
  4575 			}	
  4576 
  4577 			if (select(s))
  4578 				// pad to oldDepth, select the last branch for each depth
  4579 				for (i=d;i<oldDepth;i++)
  4580 				{
  4581 					b=select (s);
  4582 					if (b)
  4583 						if ( selection.getBranch()->countBranches()>0)
  4584 							s+=",bo:"+ QString ("%1").arg( selection.getBranch()->countBranches()-1 );
  4585 						else	
  4586 							break;
  4587 					else
  4588 						break;
  4589 				}	
  4590 			
  4591 			// try to select the freshly built string
  4592 			found=select(s);
  4593 			d--;
  4594 		}
  4595 		return;
  4596 	}	
  4597 }
  4598 
  4599 void VymModel::selectUpperBranch()
  4600 {
  4601 	if (selection.isBlocked() ) return;
  4602 
  4603 	BranchObj *bo=selection.getBranch();
  4604 	if (bo && selection.type()==Selection::Branch)
  4605 	{
  4606 		if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  4607 			selectPrevBranchInt();
  4608 		else
  4609 			if (bo->getDepth()==1)
  4610 				selectNextBranchInt();
  4611 			else
  4612 				selectPrevBranchInt();
  4613 	}
  4614 }
  4615 
  4616 void VymModel::selectLowerBranch()
  4617 {
  4618 	if (selection.isBlocked() ) return;
  4619 
  4620 	BranchObj *bo=selection.getBranch();
  4621 	if (bo && selection.type()==Selection::Branch)
  4622 	{
  4623 		if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  4624 			selectNextBranchInt();
  4625 		else
  4626 			if (bo->getDepth()==1)
  4627 				selectPrevBranchInt();
  4628 			else
  4629 				selectNextBranchInt();
  4630 	}			
  4631 }
  4632 
  4633 
  4634 void VymModel::selectLeftBranch()
  4635 {
  4636 	if (selection.isBlocked() ) return;
  4637 
  4638 	BranchObj* bo;
  4639 	BranchObj* par;
  4640 	LinkableMapObj *sel=selection.single();
  4641 	if (sel)
  4642 	{
  4643 		if (selection.type()== Selection::MapCenter)
  4644 		{
  4645 			par=selection.getBranch();
  4646 			bo=par->getLastSelectedBranch();
  4647 			if (bo)
  4648 			{
  4649 				// Workaround for reselecting on left and right side
  4650 				if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  4651 					bo=par->getLastBranch();
  4652 				if (bo)
  4653 				{
  4654 					bo=par->getLastBranch();
  4655 					selection.select(bo);
  4656 					selection.update();
  4657 					ensureSelectionVisible();
  4658 					sendSelection();
  4659 				}
  4660 			}	
  4661 		} else
  4662 		{
  4663 			par=(BranchObj*)(sel->getParObj());
  4664 			if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
  4665 			{
  4666 				if (selection.type() == Selection::Branch ||
  4667 					selection.type() == Selection::FloatImage)
  4668 				{
  4669 					selection.select(par);
  4670 					selection.update();
  4671 					ensureSelectionVisible();
  4672 					sendSelection();
  4673 				}
  4674 			} else
  4675 			{
  4676 				if (selection.type() == Selection::Branch )
  4677 				{
  4678 					bo=selection.getBranch()->getLastSelectedBranch();
  4679 					if (bo) 
  4680 					{
  4681 						selection.select(bo);
  4682 						selection.update();
  4683 						ensureSelectionVisible();
  4684 					sendSelection();
  4685 					}
  4686 				}
  4687 			}
  4688 		}	
  4689 	}
  4690 }
  4691 
  4692 void VymModel::selectRightBranch()
  4693 {
  4694 	if (selection.isBlocked() ) return;
  4695 
  4696 	BranchObj* bo;
  4697 	BranchObj* par;
  4698 	LinkableMapObj *sel=selection.single();
  4699 	if (sel)
  4700 	{
  4701 		if (selection.type()==Selection::MapCenter) 
  4702 		{
  4703 			par=selection.getBranch();
  4704 			bo=par->getLastSelectedBranch();
  4705 			if (bo)
  4706 			{
  4707 				// Workaround for reselecting on left and right side
  4708 				if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
  4709 					bo=par->getFirstBranch();
  4710 				if (bo)
  4711 				{
  4712 					selection.select(bo);
  4713 					selection.update();
  4714 					ensureSelectionVisible();
  4715 					sendSelection();
  4716 				}
  4717 			}
  4718 		} else
  4719 		{
  4720 			par=(BranchObj*)(selection.single()->getParObj());
  4721 			if (selection.single()->getOrientation()==LinkableMapObj::LeftOfCenter)
  4722 			{
  4723 				if (selection.type() == Selection::Branch ||
  4724 					selection.type() == Selection::FloatImage)
  4725 				{
  4726 					selection.select(par);
  4727 					selection.update();
  4728 					ensureSelectionVisible();
  4729 					sendSelection();
  4730 				}
  4731 			} else
  4732 			{
  4733 				if (selection.type()  == Selection::Branch) 
  4734 				{
  4735 					bo=selection.getBranch()->getLastSelectedBranch();
  4736 					if (bo) 
  4737 					{
  4738 						selection.select(bo);
  4739 						selection.update();
  4740 						ensureSelectionVisible();
  4741 					sendSelection();
  4742 					}
  4743 				}
  4744 			}
  4745 		}
  4746 	}
  4747 }
  4748 
  4749 void VymModel::selectFirstBranch()
  4750 {
  4751 	BranchObj *bo1=selection.getBranch();
  4752 	BranchObj *bo2;
  4753 	BranchObj* par;
  4754 	if (bo1)
  4755 	{
  4756 		par=(BranchObj*)(bo1->getParObj());
  4757 		if (!par) return;
  4758 		bo2=par->getFirstBranch();
  4759 		if (bo2) {
  4760 			selection.select(bo2);
  4761 			selection.update();
  4762 			ensureSelectionVisible();
  4763 			sendSelection();
  4764 		}
  4765 	}		
  4766 }
  4767 
  4768 void VymModel::selectLastBranch()
  4769 {
  4770 	BranchObj *bo1=selection.getBranch();
  4771 	BranchObj *bo2;
  4772 	BranchObj* par;
  4773 	if (bo1)
  4774 	{
  4775 		par=(BranchObj*)(bo1->getParObj());
  4776 		if (!par) return;
  4777 		bo2=par->getLastBranch();
  4778 		if (bo2) 
  4779 		{
  4780 			selection.select(bo2);
  4781 			selection.update();
  4782 			ensureSelectionVisible();
  4783 			sendSelection();
  4784 		}
  4785 	}		
  4786 }
  4787 
  4788 void VymModel::selectParent()
  4789 {
  4790 	LinkableMapObj *lmo=selection.first();
  4791 	BranchObj* par;
  4792 	if (lmo)
  4793 	{
  4794 		par=(BranchObj*)(lmo->getParObj());
  4795 		if (!par) return;
  4796 		selection.select(par);
  4797 		selection.update();
  4798 		ensureSelectionVisible();
  4799 		sendSelection();
  4800 	}		
  4801 }
  4802 
  4803 Selection::Type VymModel::selectionType()
  4804 {
  4805 	return selection.type();
  4806 }
  4807 
  4808 LinkableMapObj* VymModel::getSelection()
  4809 {
  4810 	return selection.single();	
  4811 }
  4812 BranchObj* VymModel::getSelectedBranch()
  4813 {
  4814 	return selection.getBranch();	
  4815 }
  4816 
  4817 FloatImageObj* VymModel::getSelectedFloatImage()
  4818 {
  4819 	return selection.getFloatImage();	
  4820 }
  4821 
  4822 QString VymModel::getSelectString ()
  4823 {
  4824 	return selection.getSelectString();
  4825 }
  4826 
  4827 QString VymModel::getSelectString (LinkableMapObj *lmo)
  4828 {
  4829 	QString s;
  4830 	if (!lmo) return s;
  4831 	if (typeid(*lmo)==typeid(BranchObj) ||
  4832 		typeid(*lmo)==typeid(MapCenterObj) )
  4833 	{	
  4834 		LinkableMapObj *par=lmo->getParObj();
  4835 		if (par)
  4836 		{
  4837 			if (lmo->getDepth() ==1)
  4838 				// Mainbranch, return 
  4839 				s= "bo:" + QString("%1").arg(((BranchObj*)lmo)->getNum());
  4840 			else	
  4841 				// Branch, call myself recursively
  4842 				s= getSelectString(par) + ",bo:" + QString("%1").arg(((BranchObj*)lmo)->getNum());
  4843 		} else
  4844 		{
  4845 			// MapCenter
  4846 			int i=mapCenters.indexOf ((MapCenterObj*)lmo);
  4847 			if (i>=0) s=QString("mc:%1").arg(i);
  4848 		}	
  4849 	}	
  4850 	return s;
  4851 }
  4852