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