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