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