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