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