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