vymmodel.cpp
author insilmaril
Tue Mar 31 15:36:10 2009 +0000 (2009-03-31)
changeset 748 edb78a44240b
parent 746 ee6b0f3a4c2f
child 749 9ff332964015
permissions -rw-r--r--
Removing branches and mapcenters works
     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 /*
  2231 	if (!parentIndex.isValid()) 
  2232 	{
  2233 	cout << "VM::delete no valid parent ix\n";
  2234 	return;
  2235 	}
  2236 */	
  2237 	TreeItem *ti=bo->getTreeItem();
  2238 	
  2239 	if (selectionType()==TreeItem::MapCenter)	
  2240 	{
  2241 	//	BranchObj* par=(BranchObj*)(bo->getParObj());
  2242 		//selection.unselect();
  2243 		/* FIXME-1 VM Note:  does saveStateRemovingPart work for MCO? (No parent!)
  2244 		saveStateRemovingPart (bo, QString ("Delete %1").arg(getObjectName(bo)));
  2245 		*/	
  2246 		emit (layoutAboutToBeChanged() );
  2247 
  2248 		parentIndex=parent(index(ti));
  2249 		cout << "VM::delete  ti="<<ti<<"  row="<<ix.row()<<"  parIndex.valid="<<parentIndex.isValid()<<endl;
  2250 		int n=ix.row();
  2251 		beginRemoveRows (parentIndex,n,n);
  2252 		removeRows (n,1,parentIndex);
  2253 		bo=removeMapCenter ((MapCenterObj*)bo);
  2254 		endRemoveRows();
  2255 		if (bo) 
  2256 		{
  2257 			select (bo);
  2258 			ensureSelectionVisible();
  2259 			ensureSelectionVisible();
  2260 			reposition();
  2261 		}	
  2262 
  2263 		emit (layoutChanged() );
  2264 	}
  2265 	if (selectionType()==TreeItem::Branch)
  2266 	{
  2267 
  2268 		BranchObj* par=(BranchObj*)bo->getParObj();
  2269 		unselect();
  2270 		saveStateRemovingPart (bo, QString ("Delete %1").arg(getObjectName(bo)));
  2271 
  2272 		emit (layoutAboutToBeChanged() );
  2273 
  2274 		cout << "VM::delete  ti="<<ti<<"  row="<<ix.row()<<endl;
  2275 		parentIndex=parent(index(ti));
  2276 		int n=ix.row();
  2277 		beginRemoveRows (parentIndex,n,n);
  2278 		removeRows (n,1,parentIndex);
  2279 		par->removeBranch(bo);	// remove from BranchObj lists...
  2280 		endRemoveRows();
  2281 		select (par);
  2282 		ensureSelectionVisible();
  2283 		reposition();
  2284 
  2285 		emit (layoutChanged() );
  2286 		return;
  2287 	}
  2288 	FloatImageObj *fio=selection.getFloatImage(); 	//FIXME-1 VM still missing
  2289 
  2290 /*
  2291 	if (fio)
  2292 	{
  2293 		BranchObj* par=(BranchObj*)fio->getParObj();
  2294 		saveStateChangingPart(
  2295 			par, 
  2296 			fio,
  2297 			"delete ()",
  2298 			QString("Delete %1").arg(getObjectName(fio))
  2299 		);
  2300 		unselect();
  2301 		par->removeFloatImage(fio);
  2302 		select (par);
  2303 		reposition();
  2304 		ensureSelectionVisible();
  2305 		return;
  2306 	}
  2307 	*/
  2308 }
  2309 
  2310 void VymModel::deleteKeepChildren()		//FIXME-1 VM still missing
  2311 
  2312 {
  2313 	BranchObj *bo=getSelectedBranch();
  2314 	BranchObj *par;
  2315 	if (bo)
  2316 	{
  2317 		par=(BranchObj*)(bo->getParObj());
  2318 
  2319 		// Don't use this on mapcenter
  2320 		if (!par) return;
  2321 
  2322 		// Check if we have childs at all to keep
  2323 		if (bo->countBranches()==0) 
  2324 		{
  2325 			deleteSelection();
  2326 			return;
  2327 		}
  2328 
  2329 		QPointF p=bo->getRelPos();
  2330 		saveStateChangingPart(
  2331 			bo->getParObj(),
  2332 			bo,
  2333 			"deleteKeepChildren ()",
  2334 			QString("Remove %1 and keep its children").arg(getObjectName(bo))
  2335 		);
  2336 
  2337 		QString sel=getSelectString(bo);
  2338 		unselect();
  2339 		par->removeBranchHere(bo);
  2340 		reposition();
  2341 		select (sel);
  2342 		getSelectedBranch()->move2RelPos (p);
  2343 		reposition();
  2344 	}	
  2345 }
  2346 
  2347 void VymModel::deleteChildren()		//FIXME-1 VM still missing
  2348 
  2349 {
  2350 	BranchObj *bo=getSelectedBranch();
  2351 	if (bo)
  2352 	{		
  2353 		saveStateChangingPart(
  2354 			bo, 
  2355 			bo,
  2356 			"deleteChildren ()",
  2357 			QString( "Remove children of branch %1").arg(getObjectName(bo))
  2358 		);
  2359 		bo->removeChildren();
  2360 		reposition();
  2361 	}	
  2362 }
  2363 
  2364 
  2365 bool VymModel::scrollBranch(BranchObj *bo)
  2366 {
  2367 	if (bo)
  2368 	{
  2369 		if (bo->isScrolled()) return false;
  2370 		if (bo->countBranches()==0) return false;
  2371 		if (bo->getDepth()==0) return false;
  2372 		QString u,r;
  2373 		r="scroll";
  2374 		u="unscroll";
  2375 		saveState(
  2376 			bo,
  2377 			QString ("%1 ()").arg(u),
  2378 			bo,
  2379 			QString ("%1 ()").arg(r),
  2380 			QString ("%1 %2").arg(r).arg(getObjectName(bo))
  2381 		);
  2382 		bo->toggleScroll();
  2383 		selection.update();
  2384 		// FIXME-3 VM needed? scene()->update();
  2385 		return true;
  2386 	}	
  2387 	return false;
  2388 }
  2389 
  2390 bool VymModel::unscrollBranch(BranchObj *bo)
  2391 {
  2392 	if (bo)
  2393 	{
  2394 		if (!bo->isScrolled()) return false;
  2395 		if (bo->countBranches()==0) return false;
  2396 		if (bo->getDepth()==0) return false;
  2397 		QString u,r;
  2398 		u="scroll";
  2399 		r="unscroll";
  2400 		saveState(
  2401 			bo,
  2402 			QString ("%1 ()").arg(u),
  2403 			bo,
  2404 			QString ("%1 ()").arg(r),
  2405 			QString ("%1 %2").arg(r).arg(getObjectName(bo))
  2406 		);
  2407 		bo->toggleScroll();
  2408 		selection.update();
  2409 		// FIXME-3 VM needed? scene()->update();
  2410 		return true;
  2411 	}	
  2412 	return false;
  2413 }
  2414 
  2415 void VymModel::toggleScroll()
  2416 {
  2417 	BranchObj *bo=getSelectedBranch();
  2418 	if (selectionType()==TreeItem::Branch )
  2419 	{
  2420 		if (bo->isScrolled())
  2421 			unscrollBranch (bo);
  2422 		else
  2423 			scrollBranch (bo);
  2424 	}
  2425 }
  2426 
  2427 void VymModel::unscrollChildren() 	// FIXME-1	first, next moved to vymmodel
  2428 
  2429 {
  2430 /*
  2431 	BranchObj *bo=getSelectedBranch();
  2432 	if (bo)
  2433 	{
  2434 		bo->first();
  2435 		while (bo) 
  2436 		{
  2437 			if (bo->isScrolled()) unscrollBranch (bo);
  2438 			bo=bo->next();
  2439 		}
  2440 	}	
  2441 */	
  2442 }
  2443 
  2444 void VymModel::addFloatImage (const QPixmap &img) 
  2445 {
  2446 	BranchObj *bo=getSelectedBranch();
  2447 	if (bo)
  2448   {
  2449 	FloatImageObj *fio=bo->addFloatImage();
  2450     fio->load(img);
  2451     fio->setOriginalFilename("No original filename (image added by dropevent)");	
  2452 	QString s=getSelectString(bo);
  2453 	saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",fio  );
  2454 	saveState (fio,"delete ()", bo,QString("paste(%1)").arg(curStep),"Pasting dropped image");
  2455     reposition();
  2456     // FIXME-3 VM needed? scene()->update();
  2457   }
  2458 }
  2459 
  2460 
  2461 void VymModel::colorBranch (QColor c)
  2462 {
  2463 	BranchObj *bo=getSelectedBranch();
  2464 	if (bo)
  2465 	{
  2466 		saveState(
  2467 			bo, 
  2468 			QString ("colorBranch (\"%1\")").arg(bo->getColor().name()),
  2469 			bo,
  2470 			QString ("colorBranch (\"%1\")").arg(c.name()),
  2471 			QString("Set color of %1 to %2").arg(getObjectName(bo)).arg(c.name())
  2472 		);	
  2473 		bo->setColor(c); // color branch
  2474 	}
  2475 }
  2476 
  2477 void VymModel::colorSubtree (QColor c)
  2478 {
  2479 	BranchObj *bo=getSelectedBranch();
  2480 	if (bo) 
  2481 	{
  2482 		saveStateChangingPart(
  2483 			bo, 
  2484 			bo,
  2485 			QString ("colorSubtree (\"%1\")").arg(c.name()),
  2486 			QString ("Set color of %1 and children to %2").arg(getObjectName(bo)).arg(c.name())
  2487 		);	
  2488 		bo->setColorSubtree (c); // color links, color children
  2489 	}
  2490 }
  2491 
  2492 QColor VymModel::getCurrentHeadingColor()
  2493 {
  2494 	BranchObj *bo=getSelectedBranch();
  2495 	if (bo) return bo->getColor(); 
  2496 	
  2497 	QMessageBox::warning(0,"Warning","Can't get color of heading,\nthere's no branch selected");
  2498 	return Qt::black;
  2499 }
  2500 
  2501 
  2502 
  2503 void VymModel::editURL()
  2504 {
  2505 	BranchObj *bo=getSelectedBranch();
  2506 	if (bo)
  2507 	{		
  2508 		bool ok;
  2509 		QString text = QInputDialog::getText(
  2510 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2511 				bo->getURL(), &ok, NULL);
  2512 		if ( ok) 
  2513 			// user entered something and pressed OK
  2514 			setURL(text);
  2515 	}
  2516 }
  2517 
  2518 void VymModel::editLocalURL()
  2519 {
  2520 	BranchObj *bo=getSelectedBranch();
  2521 	if (bo)
  2522 	{		
  2523 		QStringList filters;
  2524 		filters <<"All files (*)";
  2525 		filters << tr("Text","Filedialog") + " (*.txt)";
  2526 		filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
  2527 		filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
  2528 		filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
  2529 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Set URL to a local file"));
  2530 		fd->setFilters (filters);
  2531 		fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
  2532 		fd->setDirectory (lastFileDir);
  2533 		if (! bo->getVymLink().isEmpty() )
  2534 			fd->selectFile( bo->getURL() );
  2535 		fd->show();
  2536 
  2537 		if ( fd->exec() == QDialog::Accepted )
  2538 		{
  2539 			lastFileDir=QDir (fd->directory().path());
  2540 			setURL (fd->selectedFile() );
  2541 		}
  2542 	}
  2543 }
  2544 
  2545 
  2546 void VymModel::editHeading2URL()
  2547 {
  2548 	BranchObj *bo=getSelectedBranch();
  2549 	if (bo)
  2550 		setURL (bo->getHeading());
  2551 }	
  2552 
  2553 void VymModel::editBugzilla2URL()
  2554 {
  2555 	BranchObj *bo=getSelectedBranch();
  2556 	if (bo)
  2557 	{		
  2558 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
  2559 		setURL (url);
  2560 	}
  2561 }	
  2562 
  2563 void VymModel::editFATE2URL()
  2564 {
  2565 	BranchObj *bo=getSelectedBranch();
  2566 	if (bo)
  2567 	{		
  2568 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
  2569 		saveState(
  2570 			bo,
  2571 			"setURL (\""+bo->getURL()+"\")",
  2572 			bo,
  2573 			"setURL (\""+url+"\")",
  2574 			QString("Use heading of %1 as link to FATE").arg(getObjectName(bo))
  2575 		);	
  2576 		bo->setURL (url);
  2577 		updateActions();
  2578 	}
  2579 }	
  2580 
  2581 void VymModel::editVymLink()
  2582 {
  2583 	BranchObj *bo=getSelectedBranch();
  2584 	if (bo)
  2585 	{		
  2586 		QStringList filters;
  2587 		filters <<"VYM map (*.vym)";
  2588 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Link to another map"));
  2589 		fd->setFilters (filters);
  2590 		fd->setCaption(vymName+" - " +tr("Link to another map"));
  2591 		fd->setDirectory (lastFileDir);
  2592 		if (! bo->getVymLink().isEmpty() )
  2593 			fd->selectFile( bo->getVymLink() );
  2594 		fd->show();
  2595 
  2596 		QString fn;
  2597 		if ( fd->exec() == QDialog::Accepted )
  2598 		{
  2599 			lastFileDir=QDir (fd->directory().path());
  2600 			saveState(
  2601 				bo,
  2602 				"setVymLink (\""+bo->getVymLink()+"\")",
  2603 				bo,
  2604 				"setVymLink (\""+fd->selectedFile()+"\")",
  2605 				QString("Set vymlink of %1 to %2").arg(getObjectName(bo)).arg(fd->selectedFile())
  2606 			);	
  2607 			setVymLink (fd->selectedFile() );	// FIXME-2 ok?
  2608 		}
  2609 	}
  2610 }
  2611 
  2612 void VymModel::setVymLink (const QString &s)
  2613 {
  2614 	// Internal function, no saveState needed
  2615 	BranchObj *bo=getSelectedBranch();
  2616 	if (bo)
  2617 	{
  2618 		bo->setVymLink(s);
  2619 		reposition();
  2620 		updateActions();
  2621 		selection.update();
  2622 		ensureSelectionVisible();
  2623 	}
  2624 }
  2625 
  2626 void VymModel::deleteVymLink()
  2627 {
  2628 	BranchObj *bo=getSelectedBranch();
  2629 	if (bo)
  2630 	{		
  2631 		saveState(
  2632 			bo,
  2633 			"setVymLink (\""+bo->getVymLink()+"\")",
  2634 			bo,
  2635 			"setVymLink (\"\")",
  2636 			QString("Unset vymlink of %1").arg(getObjectName(bo))
  2637 		);	
  2638 		bo->setVymLink ("" );
  2639 		updateActions();
  2640 		reposition();
  2641 		// FIXME-3 VM needed? scene()->update();
  2642 	}
  2643 }
  2644 
  2645 QString VymModel::getVymLink()
  2646 {
  2647 	BranchObj *bo=getSelectedBranch();
  2648 	if (bo)
  2649 		return bo->getVymLink();
  2650 	else	
  2651 		return "";
  2652 	
  2653 }
  2654 
  2655 QStringList VymModel::getVymLinks()	// FIXME-1	first, next moved to vymmodel
  2656 {
  2657 	return QStringList();
  2658 /*
  2659 	QStringList links;
  2660 	BranchObj *bo=getSelectedBranch();
  2661 	if (bo)
  2662 	{		
  2663 		bo=bo->first();	
  2664 		while (bo) 
  2665 		{
  2666 			if (!bo->getVymLink().isEmpty()) links.append( bo->getVymLink());
  2667 			bo=bo->next();
  2668 		}	
  2669 	}	
  2670 	return links;
  2671 */	
  2672 }
  2673 
  2674 
  2675 void VymModel::followXLink(int i)
  2676 {
  2677 	BranchObj *bo=getSelectedBranch();
  2678 	if (bo)
  2679 	{
  2680 		bo=bo->XLinkTargetAt(i);
  2681 		if (bo) 
  2682 		{
  2683 			selection.select(bo);
  2684 			ensureSelectionVisible();
  2685 		}
  2686 	}
  2687 }
  2688 
  2689 void VymModel::editXLink(int i)	// FIXME-1 VM missing saveState
  2690 {
  2691 	BranchObj *bo=getSelectedBranch();
  2692 	if (bo)
  2693 	{
  2694 		XLinkObj *xlo=bo->XLinkAt(i);
  2695 		if (xlo) 
  2696 		{
  2697 			EditXLinkDialog dia;
  2698 			dia.setXLink (xlo);
  2699 			dia.setSelection(bo);
  2700 			if (dia.exec() == QDialog::Accepted)
  2701 			{
  2702 				if (dia.useSettingsGlobal() )
  2703 				{
  2704 					setMapDefXLinkColor (xlo->getColor() );
  2705 					setMapDefXLinkWidth (xlo->getWidth() );
  2706 				}
  2707 				if (dia.deleteXLink())
  2708 					bo->deleteXLinkAt(i);
  2709 			}
  2710 		}	
  2711 	}
  2712 }
  2713 
  2714 
  2715 
  2716 
  2717 
  2718 //////////////////////////////////////////////
  2719 // Scripting
  2720 //////////////////////////////////////////////
  2721 
  2722 void VymModel::parseAtom(const QString &atom)
  2723 {
  2724 	BranchObj *selb=getSelectedBranch();
  2725 	QString s,t;
  2726 	double x,y;
  2727 	int n;
  2728 	bool b,ok;
  2729 
  2730 	// Split string s into command and parameters
  2731 	parser.parseAtom (atom);
  2732 	QString com=parser.getCommand();
  2733 	
  2734 	// External commands
  2735 	/////////////////////////////////////////////////////////////////////
  2736 	if (com=="addBranch")
  2737 	{
  2738 		if (selection.isEmpty())
  2739 		{
  2740 			parser.setError (Aborted,"Nothing selected");
  2741 		} else if (! selb )
  2742 		{				  
  2743 			parser.setError (Aborted,"Type of selection is not a branch");
  2744 		} else 
  2745 		{	
  2746 			QList <int> pl;
  2747 			pl << 0 <<1;
  2748 			if (parser.checkParCount(pl))
  2749 			{
  2750 				if (parser.parCount()==0)
  2751 					addNewBranch (0);
  2752 				else
  2753 				{
  2754 					n=parser.parInt (ok,0);
  2755 					if (ok ) addNewBranch (n);
  2756 				}
  2757 			}
  2758 		}
  2759 	/////////////////////////////////////////////////////////////////////
  2760 	} else if (com=="addBranchBefore")
  2761 	{
  2762 		if (selection.isEmpty())
  2763 		{
  2764 			parser.setError (Aborted,"Nothing selected");
  2765 		} else if (! selb )
  2766 		{				  
  2767 			parser.setError (Aborted,"Type of selection is not a branch");
  2768 		} else 
  2769 		{	
  2770 			if (parser.parCount()==0)
  2771 			{
  2772 				addNewBranchBefore ();
  2773 			}	
  2774 		}
  2775 	/////////////////////////////////////////////////////////////////////
  2776 	} else if (com==QString("addMapCenter"))
  2777 	{
  2778 		if (parser.checkParCount(2))
  2779 		{
  2780 			x=parser.parDouble (ok,0);
  2781 			if (ok)
  2782 			{
  2783 				y=parser.parDouble (ok,1);
  2784 				if (ok) addMapCenter (QPointF(x,y));
  2785 			}
  2786 		}	
  2787 	/////////////////////////////////////////////////////////////////////
  2788 	} else if (com==QString("addMapReplace"))
  2789 	{
  2790 		if (selection.isEmpty())
  2791 		{
  2792 			parser.setError (Aborted,"Nothing selected");
  2793 		} else if (! selb )
  2794 		{				  
  2795 			parser.setError (Aborted,"Type of selection is not a branch");
  2796 		} else if (parser.checkParCount(1))
  2797 		{
  2798 			//s=parser.parString (ok,0);	// selection
  2799 			t=parser.parString (ok,0);	// path to map
  2800 			if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2801 			addMapReplaceInt(getSelectString(selb),t);	
  2802 		}
  2803 	/////////////////////////////////////////////////////////////////////
  2804 	} else if (com==QString("addMapInsert"))
  2805 	{
  2806 		if (selection.isEmpty())
  2807 		{
  2808 			parser.setError (Aborted,"Nothing selected");
  2809 		} else if (! selb )
  2810 		{				  
  2811 			parser.setError (Aborted,"Type of selection is not a branch");
  2812 		} else 
  2813 		{	
  2814 			if (parser.checkParCount(2))
  2815 			{
  2816 				t=parser.parString (ok,0);	// path to map
  2817 				n=parser.parInt(ok,1);		// position
  2818 				if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2819 				addMapInsertInt(t,n);	
  2820 			}
  2821 		}
  2822 	/////////////////////////////////////////////////////////////////////
  2823 	} else if (com=="clearFlags")
  2824 	{
  2825 		if (selection.isEmpty() )
  2826 		{
  2827 			parser.setError (Aborted,"Nothing selected");
  2828 		} else if (! selb )
  2829 		{				  
  2830 			parser.setError (Aborted,"Type of selection is not a branch");
  2831 		} else if (parser.checkParCount(0))
  2832 		{
  2833 			selb->clearStandardFlags();	
  2834 			selb->updateFlagsToolbar();
  2835 		}
  2836 	/////////////////////////////////////////////////////////////////////
  2837 	} else if (com=="colorBranch")
  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) colorBranch (c);
  2849 		}	
  2850 	/////////////////////////////////////////////////////////////////////
  2851 	} else if (com=="colorSubtree")
  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(1))
  2860 		{	
  2861 			QColor c=parser.parColor (ok,0);
  2862 			if (ok) colorSubtree (c);
  2863 		}	
  2864 	/////////////////////////////////////////////////////////////////////
  2865 	} else if (com=="copy")
  2866 	{
  2867 		if (selection.isEmpty())
  2868 		{
  2869 			parser.setError (Aborted,"Nothing selected");
  2870 		} else if (! selb )
  2871 		{				  
  2872 			parser.setError (Aborted,"Type of selection is not a branch");
  2873 		} else if (parser.checkParCount(0))
  2874 		{	
  2875 			//FIXME-1 missing action for copy
  2876 		}	
  2877 	/////////////////////////////////////////////////////////////////////
  2878 	} else if (com=="cut")
  2879 	{
  2880 		if (selection.isEmpty())
  2881 		{
  2882 			parser.setError (Aborted,"Nothing selected");
  2883 		} else if ( selectionType()!=TreeItem::Branch  && 
  2884 					selectionType()!=TreeItem::MapCenter  &&
  2885 					selectionType()!=TreeItem::Image )
  2886 		{				  
  2887 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  2888 		} else if (parser.checkParCount(0))
  2889 		{	
  2890 			cut();
  2891 		}	
  2892 	/////////////////////////////////////////////////////////////////////
  2893 	} else if (com=="delete")
  2894 	{
  2895 		if (selection.isEmpty())
  2896 		{
  2897 			parser.setError (Aborted,"Nothing selected");
  2898 		} 
  2899 		/*else if (selectionType() != TreeItem::Branch && selectionType() != TreeItem::Image )
  2900 		{
  2901 			parser.setError (Aborted,"Type of selection is wrong.");
  2902 		} 
  2903 		*/
  2904 		else if (parser.checkParCount(0))
  2905 		{	
  2906 			deleteSelection();
  2907 		}	
  2908 	/////////////////////////////////////////////////////////////////////
  2909 	} else if (com=="deleteKeepChildren")
  2910 	{
  2911 		if (selection.isEmpty())
  2912 		{
  2913 			parser.setError (Aborted,"Nothing selected");
  2914 		} else if (! selb )
  2915 		{
  2916 			parser.setError (Aborted,"Type of selection is not a branch");
  2917 		} else if (parser.checkParCount(0))
  2918 		{	
  2919 			deleteKeepChildren();
  2920 		}	
  2921 	/////////////////////////////////////////////////////////////////////
  2922 	} else if (com=="deleteChildren")
  2923 	{
  2924 		if (selection.isEmpty())
  2925 		{
  2926 			parser.setError (Aborted,"Nothing selected");
  2927 		} else if (! selb)
  2928 		{
  2929 			parser.setError (Aborted,"Type of selection is not a branch");
  2930 		} else if (parser.checkParCount(0))
  2931 		{	
  2932 			deleteChildren();
  2933 		}	
  2934 	/////////////////////////////////////////////////////////////////////
  2935 	} else if (com=="exportASCII")
  2936 	{
  2937 		QString fname="";
  2938 		ok=true;
  2939 		if (parser.parCount()>=1)
  2940 			// Hey, we even have a filename
  2941 			fname=parser.parString(ok,0); 
  2942 		if (!ok)
  2943 		{
  2944 			parser.setError (Aborted,"Could not read filename");
  2945 		} else
  2946 		{
  2947 				exportASCII (fname,false);
  2948 		}
  2949 	/////////////////////////////////////////////////////////////////////
  2950 	} else if (com=="exportImage")
  2951 	{
  2952 		QString fname="";
  2953 		ok=true;
  2954 		if (parser.parCount()>=2)
  2955 			// Hey, we even have a filename
  2956 			fname=parser.parString(ok,0); 
  2957 		if (!ok)
  2958 		{
  2959 			parser.setError (Aborted,"Could not read filename");
  2960 		} else
  2961 		{
  2962 			QString format="PNG";
  2963 			if (parser.parCount()>=2)
  2964 			{
  2965 				format=parser.parString(ok,1);
  2966 			}
  2967 			exportImage (fname,false,format);
  2968 		}
  2969 	/////////////////////////////////////////////////////////////////////
  2970 	} else if (com=="exportXHTML")
  2971 	{
  2972 		QString fname="";
  2973 		ok=true;
  2974 		if (parser.parCount()>=2)
  2975 			// Hey, we even have a filename
  2976 			fname=parser.parString(ok,1); 
  2977 		if (!ok)
  2978 		{
  2979 			parser.setError (Aborted,"Could not read filename");
  2980 		} else
  2981 		{
  2982 			exportXHTML (fname,false);
  2983 		}
  2984 	/////////////////////////////////////////////////////////////////////
  2985 	} else if (com=="exportXML")
  2986 	{
  2987 		QString fname="";
  2988 		ok=true;
  2989 		if (parser.parCount()>=2)
  2990 			// Hey, we even have a filename
  2991 			fname=parser.parString(ok,1); 
  2992 		if (!ok)
  2993 		{
  2994 			parser.setError (Aborted,"Could not read filename");
  2995 		} else
  2996 		{
  2997 			exportXML (fname,false);
  2998 		}
  2999 	/////////////////////////////////////////////////////////////////////
  3000 	} else if (com=="importDir")
  3001 	{
  3002 		if (selection.isEmpty())
  3003 		{
  3004 			parser.setError (Aborted,"Nothing selected");
  3005 		} else if (! selb )
  3006 		{				  
  3007 			parser.setError (Aborted,"Type of selection is not a branch");
  3008 		} else if (parser.checkParCount(1))
  3009 		{
  3010 			s=parser.parString(ok,0);
  3011 			if (ok) importDirInt(s);
  3012 		}	
  3013 	/////////////////////////////////////////////////////////////////////
  3014 	} else if (com=="linkTo")
  3015 	{
  3016 		if (selection.isEmpty())
  3017 		{
  3018 			parser.setError (Aborted,"Nothing selected");
  3019 		} else if ( selb)
  3020 		{
  3021 			if (parser.checkParCount(4))
  3022 			{
  3023 				// 0	selectstring of parent
  3024 				// 1	num in parent (for branches)
  3025 				// 2,3	x,y of mainbranch or mapcenter
  3026 				s=parser.parString(ok,0);
  3027 				LinkableMapObj *dst=findObjBySelect (s);
  3028 				if (dst)
  3029 				{	
  3030 					if (typeid(*dst) == typeid(BranchObj) ) 
  3031 					{
  3032 						// Get number in parent
  3033 						n=parser.parInt (ok,1);
  3034 						if (ok)
  3035 						{
  3036 							selb->linkTo ((BranchObj*)(dst),n);
  3037 							selection.update();
  3038 						}	
  3039 					} else if (typeid(*dst) == typeid(MapCenterObj) ) 
  3040 					{
  3041 						selb->linkTo ((BranchObj*)(dst),-1);
  3042 						// Get coordinates of mainbranch
  3043 						x=parser.parDouble(ok,2);
  3044 						if (ok)
  3045 						{
  3046 							y=parser.parDouble(ok,3);
  3047 							if (ok) 
  3048 							{
  3049 								selb->move (x,y);
  3050 								selection.update();
  3051 							}
  3052 						}
  3053 					}	
  3054 				}	
  3055 			}	
  3056 		} else if ( selectionType() == TreeItem::Image) 
  3057 		{
  3058 			if (parser.checkParCount(1))
  3059 			{
  3060 				// 0	selectstring of parent
  3061 				s=parser.parString(ok,0);
  3062 				LinkableMapObj *dst=findObjBySelect (s);
  3063 				if (dst)
  3064 				{	
  3065 					if (typeid(*dst) == typeid(BranchObj) ||
  3066 						typeid(*dst) == typeid(MapCenterObj)) 
  3067 						linkFloatImageTo (getSelectString(dst));
  3068 				} else	
  3069 					parser.setError (Aborted,"Destination is not a branch");
  3070 			}		
  3071 		} else
  3072 			parser.setError (Aborted,"Type of selection is not a floatimage or branch");
  3073 	/////////////////////////////////////////////////////////////////////
  3074 	} else if (com=="loadImage")
  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(1))
  3083 		{
  3084 			s=parser.parString(ok,0);
  3085 			if (ok) loadFloatImageInt (s);
  3086 		}	
  3087 	/////////////////////////////////////////////////////////////////////
  3088 	} else if (com=="moveBranchUp")
  3089 	{
  3090 		if (selection.isEmpty() )
  3091 		{
  3092 			parser.setError (Aborted,"Nothing selected");
  3093 		} else if (! selb )
  3094 		{				  
  3095 			parser.setError (Aborted,"Type of selection is not a branch");
  3096 		} else if (parser.checkParCount(0))
  3097 		{
  3098 			moveBranchUp();
  3099 		}	
  3100 	/////////////////////////////////////////////////////////////////////
  3101 	} else if (com=="moveBranchDown")
  3102 	{
  3103 		if (selection.isEmpty() )
  3104 		{
  3105 			parser.setError (Aborted,"Nothing selected");
  3106 		} else if (! selb )
  3107 		{				  
  3108 			parser.setError (Aborted,"Type of selection is not a branch");
  3109 		} else if (parser.checkParCount(0))
  3110 		{
  3111 			moveBranchDown();
  3112 		}	
  3113 	/////////////////////////////////////////////////////////////////////
  3114 	} else if (com=="move")
  3115 	{
  3116 		if (selection.isEmpty() )
  3117 		{
  3118 			parser.setError (Aborted,"Nothing selected");
  3119 		} else if ( selectionType()!=TreeItem::Branch  && 
  3120 					selectionType()!=TreeItem::MapCenter  &&
  3121 					selectionType()!=TreeItem::Image )
  3122 		{				  
  3123 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3124 		} else if (parser.checkParCount(2))
  3125 		{	
  3126 			x=parser.parDouble (ok,0);
  3127 			if (ok)
  3128 			{
  3129 				y=parser.parDouble (ok,1);
  3130 				if (ok) move (x,y);
  3131 			}
  3132 		}	
  3133 	/////////////////////////////////////////////////////////////////////
  3134 	} else if (com=="moveRel")
  3135 	{
  3136 		if (selection.isEmpty() )
  3137 		{
  3138 			parser.setError (Aborted,"Nothing selected");
  3139 		} else if ( selectionType()!=TreeItem::Branch  && 
  3140 					selectionType()!=TreeItem::MapCenter  &&
  3141 					selectionType()!=TreeItem::Image )
  3142 		{				  
  3143 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3144 		} else if (parser.checkParCount(2))
  3145 		{	
  3146 			x=parser.parDouble (ok,0);
  3147 			if (ok)
  3148 			{
  3149 				y=parser.parDouble (ok,1);
  3150 				if (ok) moveRel (x,y);
  3151 			}
  3152 		}	
  3153 	/////////////////////////////////////////////////////////////////////
  3154 	} else if (com=="nop")
  3155 	{
  3156 	/////////////////////////////////////////////////////////////////////
  3157 	} else if (com=="paste")
  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(1))
  3166 		{	
  3167 			n=parser.parInt (ok,0);
  3168 			if (ok) pasteNoSave(n);
  3169 		}	
  3170 	/////////////////////////////////////////////////////////////////////
  3171 	} else if (com=="qa")
  3172 	{
  3173 		if (selection.isEmpty() )
  3174 		{
  3175 			parser.setError (Aborted,"Nothing selected");
  3176 		} else if (! selb )
  3177 		{				  
  3178 			parser.setError (Aborted,"Type of selection is not a branch");
  3179 		} else if (parser.checkParCount(4))
  3180 		{	
  3181 			QString c,u;
  3182 			c=parser.parString (ok,0);
  3183 			if (!ok)
  3184 			{
  3185 				parser.setError (Aborted,"No comment given");
  3186 			} else
  3187 			{
  3188 				s=parser.parString (ok,1);
  3189 				if (!ok)
  3190 				{
  3191 					parser.setError (Aborted,"First parameter is not a string");
  3192 				} else
  3193 				{
  3194 					t=parser.parString (ok,2);
  3195 					if (!ok)
  3196 					{
  3197 						parser.setError (Aborted,"Condition is not a string");
  3198 					} else
  3199 					{
  3200 						u=parser.parString (ok,3);
  3201 						if (!ok)
  3202 						{
  3203 							parser.setError (Aborted,"Third parameter is not a string");
  3204 						} else
  3205 						{
  3206 							if (s!="heading")
  3207 							{
  3208 								parser.setError (Aborted,"Unknown type: "+s);
  3209 							} else
  3210 							{
  3211 								if (! (t=="eq") ) 
  3212 								{
  3213 									parser.setError (Aborted,"Unknown operator: "+t);
  3214 								} else
  3215 								{
  3216 									if (! selb    )
  3217 									{
  3218 										parser.setError (Aborted,"Type of selection is not a branch");
  3219 									} else
  3220 									{
  3221 										if (selb->getHeading() == u)
  3222 										{
  3223 											cout << "PASSED: " << qPrintable (c)  << endl;
  3224 										} else
  3225 										{
  3226 											cout << "FAILED: " << qPrintable (c)  << endl;
  3227 										}
  3228 									}
  3229 								}
  3230 							}
  3231 						} 
  3232 					} 
  3233 				} 
  3234 			}
  3235 		}	
  3236 	/////////////////////////////////////////////////////////////////////
  3237 	} else if (com=="saveImage")
  3238 	{
  3239 		FloatImageObj *fio=selection.getFloatImage();
  3240 		if (!fio)
  3241 		{
  3242 			parser.setError (Aborted,"Type of selection is not an image");
  3243 		} else if (parser.checkParCount(2))
  3244 		{
  3245 			s=parser.parString(ok,0);
  3246 			if (ok)
  3247 			{
  3248 				t=parser.parString(ok,1);
  3249 				if (ok) saveFloatImageInt (fio,t,s);
  3250 			}
  3251 		}	
  3252 	/////////////////////////////////////////////////////////////////////
  3253 	} else if (com=="scroll")
  3254 	{
  3255 		if (selection.isEmpty() )
  3256 		{
  3257 			parser.setError (Aborted,"Nothing selected");
  3258 		} else if (! selb )
  3259 		{				  
  3260 			parser.setError (Aborted,"Type of selection is not a branch");
  3261 		} else if (parser.checkParCount(0))
  3262 		{	
  3263 			if (!scrollBranch (selb))	
  3264 				parser.setError (Aborted,"Could not scroll branch");
  3265 		}	
  3266 	/////////////////////////////////////////////////////////////////////
  3267 	} else if (com=="select")
  3268 	{
  3269 		if (parser.checkParCount(1))
  3270 		{
  3271 			s=parser.parString(ok,0);
  3272 			if (ok) select (s);
  3273 		}	
  3274 	/////////////////////////////////////////////////////////////////////
  3275 	} else if (com=="selectLastBranch")
  3276 	{
  3277 		if (selection.isEmpty() )
  3278 		{
  3279 			parser.setError (Aborted,"Nothing selected");
  3280 		} else if (! selb )
  3281 		{				  
  3282 			parser.setError (Aborted,"Type of selection is not a branch");
  3283 		} else if (parser.checkParCount(0))
  3284 		{	
  3285 			BranchObj *bo=selb->getLastBranch();
  3286 			if (!bo)
  3287 				parser.setError (Aborted,"Could not select last branch");
  3288 			selectInt (bo);	
  3289 				
  3290 		}	
  3291 	/////////////////////////////////////////////////////////////////////
  3292 	} else if (com=="selectLastImage")
  3293 	{
  3294 		if (selection.isEmpty() )
  3295 		{
  3296 			parser.setError (Aborted,"Nothing selected");
  3297 		} else if (! selb )
  3298 		{				  
  3299 			parser.setError (Aborted,"Type of selection is not a branch");
  3300 		} else if (parser.checkParCount(0))
  3301 		{	
  3302 			FloatImageObj *fio=selb->getLastFloatImage();
  3303 			if (!fio)
  3304 				parser.setError (Aborted,"Could not select last image");
  3305 			selectInt (fio);	
  3306 				
  3307 		}	
  3308 	/////////////////////////////////////////////////////////////////////
  3309 	} else if (com=="selectLatestAdded")
  3310 	{
  3311 		if (latestSelectionString.isEmpty() )
  3312 		{
  3313 			parser.setError (Aborted,"No latest added object");
  3314 		} else
  3315 		{	
  3316 			if (!select (latestSelectionString))
  3317 				parser.setError (Aborted,"Could not select latest added object "+latestSelectionString);
  3318 		}	
  3319 	/////////////////////////////////////////////////////////////////////
  3320 	} else if (com=="setFrameType")
  3321 	{
  3322 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3323 		{
  3324 			parser.setError (Aborted,"Type of selection does not allow setting frame type");
  3325 		}
  3326 		else if (parser.checkParCount(1))
  3327 		{
  3328 			s=parser.parString(ok,0);
  3329 			if (ok) setFrameType (s);
  3330 		}	
  3331 	/////////////////////////////////////////////////////////////////////
  3332 	} else if (com=="setFramePenColor")
  3333 	{
  3334 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3335 		{
  3336 			parser.setError (Aborted,"Type of selection does not allow setting of pen color");
  3337 		}
  3338 		else if (parser.checkParCount(1))
  3339 		{
  3340 			QColor c=parser.parColor(ok,0);
  3341 			if (ok) setFramePenColor (c);
  3342 		}	
  3343 	/////////////////////////////////////////////////////////////////////
  3344 	} else if (com=="setFrameBrushColor")
  3345 	{
  3346 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3347 		{
  3348 			parser.setError (Aborted,"Type of selection does not allow setting brush color");
  3349 		}
  3350 		else if (parser.checkParCount(1))
  3351 		{
  3352 			QColor c=parser.parColor(ok,0);
  3353 			if (ok) setFrameBrushColor (c);
  3354 		}	
  3355 	/////////////////////////////////////////////////////////////////////
  3356 	} else if (com=="setFramePadding")
  3357 	{
  3358 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3359 		{
  3360 			parser.setError (Aborted,"Type of selection does not allow setting frame padding");
  3361 		}
  3362 		else if (parser.checkParCount(1))
  3363 		{
  3364 			n=parser.parInt(ok,0);
  3365 			if (ok) setFramePadding(n);
  3366 		}	
  3367 	/////////////////////////////////////////////////////////////////////
  3368 	} else if (com=="setFrameBorderWidth")
  3369 	{
  3370 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3371 		{
  3372 			parser.setError (Aborted,"Type of selection does not allow setting frame border width");
  3373 		}
  3374 		else if (parser.checkParCount(1))
  3375 		{
  3376 			n=parser.parInt(ok,0);
  3377 			if (ok) setFrameBorderWidth (n);
  3378 		}	
  3379 	/////////////////////////////////////////////////////////////////////
  3380 	} else if (com=="setMapAuthor")
  3381 	{
  3382 		if (parser.checkParCount(1))
  3383 		{
  3384 			s=parser.parString(ok,0);
  3385 			if (ok) setAuthor (s);
  3386 		}	
  3387 	/////////////////////////////////////////////////////////////////////
  3388 	} else if (com=="setMapComment")
  3389 	{
  3390 		if (parser.checkParCount(1))
  3391 		{
  3392 			s=parser.parString(ok,0);
  3393 			if (ok) setComment(s);
  3394 		}	
  3395 	/////////////////////////////////////////////////////////////////////
  3396 	} else if (com=="setMapBackgroundColor")
  3397 	{
  3398 		if (selection.isEmpty() )
  3399 		{
  3400 			parser.setError (Aborted,"Nothing selected");
  3401 		} else if (! getSelectedBranch() )
  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) setMapBackgroundColor (c);
  3408 		}	
  3409 	/////////////////////////////////////////////////////////////////////
  3410 	} else if (com=="setMapDefLinkColor")
  3411 	{
  3412 		if (selection.isEmpty() )
  3413 		{
  3414 			parser.setError (Aborted,"Nothing selected");
  3415 		} else if (! selb )
  3416 		{				  
  3417 			parser.setError (Aborted,"Type of selection is not a branch");
  3418 		} else if (parser.checkParCount(1))
  3419 		{
  3420 			QColor c=parser.parColor (ok,0);
  3421 			if (ok) setMapDefLinkColor (c);
  3422 		}	
  3423 	/////////////////////////////////////////////////////////////////////
  3424 	} else if (com=="setMapLinkStyle")
  3425 	{
  3426 		if (parser.checkParCount(1))
  3427 		{
  3428 			s=parser.parString (ok,0);
  3429 			if (ok) setMapLinkStyle(s);
  3430 		}	
  3431 	/////////////////////////////////////////////////////////////////////
  3432 	} else if (com=="setHeading")
  3433 	{
  3434 		if (selection.isEmpty() )
  3435 		{
  3436 			parser.setError (Aborted,"Nothing selected");
  3437 		} else if (! selb )
  3438 		{				  
  3439 			parser.setError (Aborted,"Type of selection is not a branch");
  3440 		} else if (parser.checkParCount(1))
  3441 		{
  3442 			s=parser.parString (ok,0);
  3443 			if (ok) 
  3444 				setHeading (s);
  3445 		}	
  3446 	/////////////////////////////////////////////////////////////////////
  3447 	} else if (com=="setHideExport")
  3448 	{
  3449 		if (selection.isEmpty() )
  3450 		{
  3451 			parser.setError (Aborted,"Nothing selected");
  3452 		} else if (selectionType()!=TreeItem::Branch && selectionType() != TreeItem::MapCenter &&selectionType()!=TreeItem::Image)
  3453 		{				  
  3454 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3455 		} else if (parser.checkParCount(1))
  3456 		{
  3457 			b=parser.parBool(ok,0);
  3458 			if (ok) setHideExport (b);
  3459 		}
  3460 	/////////////////////////////////////////////////////////////////////
  3461 	} else if (com=="setIncludeImagesHorizontally")
  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) setIncludeImagesHor(b);
  3473 		}
  3474 	/////////////////////////////////////////////////////////////////////
  3475 	} else if (com=="setIncludeImagesVertically")
  3476 	{
  3477 		if (selection.isEmpty() )
  3478 		{
  3479 			parser.setError (Aborted,"Nothing selected");
  3480 		} else if (! selb)
  3481 		{				  
  3482 			parser.setError (Aborted,"Type of selection is not a branch");
  3483 		} else if (parser.checkParCount(1))
  3484 		{
  3485 			b=parser.parBool(ok,0);
  3486 			if (ok) setIncludeImagesVer(b);
  3487 		}
  3488 	/////////////////////////////////////////////////////////////////////
  3489 	} else if (com=="setHideLinkUnselected")
  3490 	{
  3491 		if (selection.isEmpty() )
  3492 		{
  3493 			parser.setError (Aborted,"Nothing selected");
  3494 		} else if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3495 		{				  
  3496 			parser.setError (Aborted,"Type of selection does not allow hiding the link");
  3497 		} else if (parser.checkParCount(1))
  3498 		{
  3499 			b=parser.parBool(ok,0);
  3500 			if (ok) setHideLinkUnselected(b);
  3501 		}
  3502 	/////////////////////////////////////////////////////////////////////
  3503 	} else if (com=="setSelectionColor")
  3504 	{
  3505 		if (parser.checkParCount(1))
  3506 		{
  3507 			QColor c=parser.parColor (ok,0);
  3508 			if (ok) setSelectionColorInt (c);
  3509 		}	
  3510 	/////////////////////////////////////////////////////////////////////
  3511 	} else if (com=="setURL")
  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) setURL(s);
  3523 		}	
  3524 	/////////////////////////////////////////////////////////////////////
  3525 	} else if (com=="setVymLink")
  3526 	{
  3527 		if (selection.isEmpty() )
  3528 		{
  3529 			parser.setError (Aborted,"Nothing selected");
  3530 		} else if (! selb )
  3531 		{				  
  3532 			parser.setError (Aborted,"Type of selection is not a branch");
  3533 		} else if (parser.checkParCount(1))
  3534 		{
  3535 			s=parser.parString (ok,0);
  3536 			if (ok) setVymLink(s);
  3537 		}	
  3538 	}
  3539 	/////////////////////////////////////////////////////////////////////
  3540 	else if (com=="setFlag")
  3541 	{
  3542 		if (selection.isEmpty() )
  3543 		{
  3544 			parser.setError (Aborted,"Nothing selected");
  3545 		} else if (! selb )
  3546 		{				  
  3547 			parser.setError (Aborted,"Type of selection is not a branch");
  3548 		} else if (parser.checkParCount(1))
  3549 		{
  3550 			s=parser.parString(ok,0);
  3551 			if (ok) 
  3552 			{
  3553 				selb->activateStandardFlag(s);
  3554 				selb->updateFlagsToolbar();
  3555 			}	
  3556 		}
  3557 	/////////////////////////////////////////////////////////////////////
  3558 	} else if (com=="setFrameType")
  3559 	{
  3560 		if (selection.isEmpty() )
  3561 		{
  3562 			parser.setError (Aborted,"Nothing selected");
  3563 		} else if (! selb )
  3564 		{				  
  3565 			parser.setError (Aborted,"Type of selection is not a branch");
  3566 		} else if (parser.checkParCount(1))
  3567 		{
  3568 			s=parser.parString(ok,0);
  3569 			if (ok) 
  3570 				setFrameType (s);
  3571 		}
  3572 	/////////////////////////////////////////////////////////////////////
  3573 	} else if (com=="sortChildren")
  3574 	{
  3575 		if (selection.isEmpty() )
  3576 		{
  3577 			parser.setError (Aborted,"Nothing selected");
  3578 		} else if (! selb )
  3579 		{				  
  3580 			parser.setError (Aborted,"Type of selection is not a branch");
  3581 		} else if (parser.checkParCount(0))
  3582 		{
  3583 			sortChildren();
  3584 		}
  3585 	/////////////////////////////////////////////////////////////////////
  3586 	} else if (com=="toggleFlag")
  3587 	{
  3588 		if (selection.isEmpty() )
  3589 		{
  3590 			parser.setError (Aborted,"Nothing selected");
  3591 		} else if (! selb )
  3592 		{				  
  3593 			parser.setError (Aborted,"Type of selection is not a branch");
  3594 		} else if (parser.checkParCount(1))
  3595 		{
  3596 			s=parser.parString(ok,0);
  3597 			if (ok) 
  3598 			{
  3599 				selb->toggleStandardFlag(s);	
  3600 				selb->updateFlagsToolbar();
  3601 			}	
  3602 		}
  3603 	/////////////////////////////////////////////////////////////////////
  3604 	} else if (com=="unscroll")
  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 			if (!unscrollBranch (selb))	
  3615 				parser.setError (Aborted,"Could not unscroll branch");
  3616 		}	
  3617 	/////////////////////////////////////////////////////////////////////
  3618 	} else if (com=="unscrollChildren")
  3619 	{
  3620 		if (selection.isEmpty() )
  3621 		{
  3622 			parser.setError (Aborted,"Nothing selected");
  3623 		} else if (! selb )
  3624 		{				  
  3625 			parser.setError (Aborted,"Type of selection is not a branch");
  3626 		} else if (parser.checkParCount(0))
  3627 		{	
  3628 			unscrollChildren ();
  3629 		}	
  3630 	/////////////////////////////////////////////////////////////////////
  3631 	} else if (com=="unsetFlag")
  3632 	{
  3633 		if (selection.isEmpty() )
  3634 		{
  3635 			parser.setError (Aborted,"Nothing selected");
  3636 		} else if (! selb )
  3637 		{				  
  3638 			parser.setError (Aborted,"Type of selection is not a branch");
  3639 		} else if (parser.checkParCount(1))
  3640 		{
  3641 			s=parser.parString(ok,0);
  3642 			if (ok) 
  3643 			{
  3644 				selb->deactivateStandardFlag(s);
  3645 				selb->updateFlagsToolbar();
  3646 			}	
  3647 		}
  3648 	} else
  3649 		parser.setError (Aborted,"Unknown command");
  3650 
  3651 	// Any errors?
  3652 	if (parser.errorLevel()==NoError)
  3653 	{
  3654 		// setChanged();  FIXME-2 should not be called e.g. for export?!
  3655 		reposition();
  3656 	}	
  3657 	else	
  3658 	{
  3659 		// TODO Error handling
  3660 		qWarning("VymModel::parseAtom: Error!");
  3661 		qWarning(parser.errorMessage());
  3662 	} 
  3663 }
  3664 
  3665 void VymModel::runScript (QString script)
  3666 {
  3667 	parser.setScript (script);
  3668 	parser.runScript();
  3669 	while (parser.next() ) 
  3670 		parseAtom(parser.getAtom());
  3671 }
  3672 
  3673 void VymModel::setExportMode (bool b)
  3674 {
  3675 	// should be called before and after exports
  3676 	// depending on the settings
  3677 	if (b && settings.value("/export/useHideExport","true")=="true")
  3678 		setHideTmpMode (HideExport);
  3679 	else	
  3680 		setHideTmpMode (HideNone);
  3681 }
  3682 
  3683 void VymModel::exportImage(QString fname, bool askName, QString format)
  3684 {
  3685 	if (fname=="")
  3686 	{
  3687 		fname=getMapName()+".png";
  3688 		format="PNG";
  3689 	} 	
  3690 
  3691 	if (askName)
  3692 	{
  3693 		QStringList fl;
  3694 		QFileDialog *fd=new QFileDialog (NULL);
  3695 		fd->setCaption (tr("Export map as image"));
  3696 		fd->setDirectory (lastImageDir);
  3697 		fd->setFileMode(QFileDialog::AnyFile);
  3698 		fd->setFilters  (imageIO.getFilters() );
  3699 		if (fd->exec())
  3700 		{
  3701 			fl=fd->selectedFiles();
  3702 			fname=fl.first();
  3703 			format=imageIO.getType(fd->selectedFilter());
  3704 		} 
  3705 	}
  3706 
  3707 	setExportMode (true);
  3708 	QPixmap pix (getPixmap());
  3709 	pix.save(fname, format);
  3710 	setExportMode (false);
  3711 }
  3712 
  3713 
  3714 void VymModel::exportXML(QString dir, bool askForName)
  3715 {
  3716 	if (askForName)
  3717 	{
  3718 		dir=browseDirectory(NULL,tr("Export XML to directory"));
  3719 		if (dir =="" && !reallyWriteDirectory(dir) )
  3720 		return;
  3721 	}
  3722 
  3723 	// Hide stuff during export, if settings want this
  3724 	setExportMode (true);
  3725 
  3726 	// Create subdirectories
  3727 	makeSubDirs (dir);
  3728 
  3729 	// write to directory
  3730 	QString saveFile=saveToDir (dir,mapName+"-",true,getTotalBBox().topLeft() ,NULL);
  3731 	QFile file;
  3732 
  3733 	file.setName ( dir + "/"+mapName+".xml");
  3734 	if ( !file.open( QIODevice::WriteOnly ) )
  3735 	{
  3736 		// This should neverever happen
  3737 		QMessageBox::critical (0,tr("Critical Export Error"),tr("VymModel::exportXML couldn't open %1").arg(file.name()));
  3738 		return;
  3739 	}	
  3740 
  3741 	// Write it finally, and write in UTF8, no matter what 
  3742 	QTextStream ts( &file );
  3743 	ts.setEncoding (QTextStream::UnicodeUTF8);
  3744 	ts << saveFile;
  3745 	file.close();
  3746 
  3747 	// Now write image, too
  3748 	exportImage (dir+"/images/"+mapName+".png",false,"PNG");
  3749 
  3750 	setExportMode (false);
  3751 }
  3752 
  3753 void VymModel::exportASCII(QString fname,bool askName)
  3754 {
  3755 	ExportASCII ex;
  3756 	ex.setModel (this);
  3757 	if (fname=="") 
  3758 		ex.setFile (mapName+".txt");	
  3759 	else
  3760 		ex.setFile (fname);
  3761 
  3762 	if (askName)
  3763 	{
  3764 		//ex.addFilter ("TXT (*.txt)");
  3765 		ex.setDir(lastImageDir);
  3766 		//ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
  3767 		ex.execDialog() ; 
  3768 	} 
  3769 	if (!ex.canceled())
  3770 	{
  3771 		setExportMode(true);
  3772 		ex.doExport();
  3773 		setExportMode(false);
  3774 	}
  3775 }
  3776 
  3777 void VymModel::exportXHTML (const QString &dir, bool askForName)
  3778 {
  3779 			ExportXHTMLDialog dia(NULL);
  3780 			dia.setFilePath (filePath );
  3781 			dia.setMapName (mapName );
  3782 			dia.readSettings();
  3783 			if (dir!="") dia.setDir (dir);
  3784 
  3785 			bool ok=true;
  3786 			
  3787 			if (askForName)
  3788 			{
  3789 				if (dia.exec()!=QDialog::Accepted) 
  3790 					ok=false;
  3791 				else	
  3792 				{
  3793 					QDir d (dia.getDir());
  3794 					// Check, if warnings should be used before overwriting
  3795 					// the output directory
  3796 					if (d.exists() && d.count()>0)
  3797 					{
  3798 						WarningDialog warn;
  3799 						warn.showCancelButton (true);
  3800 						warn.setText(QString(
  3801 							"The directory %1 is not empty.\n"
  3802 							"Do you risk to overwrite some of its contents?").arg(d.path() ));
  3803 						warn.setCaption("Warning: Directory not empty");
  3804 						warn.setShowAgainName("mainwindow/overwrite-dir-xhtml");
  3805 
  3806 						if (warn.exec()!=QDialog::Accepted) ok=false;
  3807 					}
  3808 				}	
  3809 			}
  3810 
  3811 			if (ok)
  3812 			{
  3813 				exportXML (dia.getDir(),false );
  3814 				dia.doExport(mapName );
  3815 				//if (dia.hasChanged()) setChanged();
  3816 			}
  3817 }
  3818 
  3819 void VymModel::exportOOPresentation(const QString &fn, const QString &cf)
  3820 {
  3821 	ExportOO ex;
  3822 	ex.setFile (fn);
  3823 	ex.setModel (this);
  3824 	if (ex.setConfigFile(cf)) 
  3825 	{
  3826 		setExportMode (true);
  3827 		ex.exportPresentation();
  3828 		setExportMode (false);
  3829 	}
  3830 }
  3831 
  3832 
  3833 
  3834 
  3835 //////////////////////////////////////////////
  3836 // View related
  3837 //////////////////////////////////////////////
  3838 
  3839 void VymModel::registerEditor(QWidget *me)
  3840 {
  3841 	mapEditor=(MapEditor*)me;
  3842 	for (int i=0; i<mapCenters.count(); i++)
  3843 		mapCenters.at(i)->setMapEditor(mapEditor);
  3844 }
  3845 
  3846 void VymModel::unregisterEditor(QWidget *)
  3847 {
  3848 	mapEditor=NULL;
  3849 }
  3850 
  3851 void VymModel::setContextPos(QPointF p)
  3852 {
  3853 	contextPos=p;
  3854 }
  3855 
  3856 void VymModel::unsetContextPos()
  3857 {
  3858 	contextPos=QPointF();
  3859 }
  3860 
  3861 void VymModel::updateNoteFlag()
  3862 {
  3863 	setChanged();
  3864 	cout << "VM::updateNoteFlag()\n";
  3865 	/* FIXME-1 modify note flag
  3866 	BranchObj *bo=getSelectedBranch();
  3867 	if (bo) 
  3868 	{
  3869 		bo->updateNoteFlag();
  3870 		mainWindow->updateActions();
  3871 	}	
  3872 	*/
  3873 }
  3874 
  3875 void VymModel::updateRelPositions()
  3876 {
  3877 	for (int i=0; i<mapCenters.count(); i++)
  3878 		mapCenters.at(i)->updateRelPositions();
  3879 }
  3880 
  3881 void VymModel::reposition()
  3882 {
  3883 	for (int i=0;i<mapCenters.count(); i++)
  3884 		mapCenters.at(i)->reposition();	//	for positioning heading
  3885 }
  3886 
  3887 QPolygonF VymModel::shape(BranchObj *bo)
  3888 {
  3889 	// Creating (arbitrary) shapes
  3890 
  3891 	QPolygonF p;
  3892 	QRectF rb=bo->getBBox();
  3893 	if (bo->getDepth()==0)
  3894 	{
  3895 		// Just take BBox of this mapCenter
  3896 		p<<rb.topLeft()<<rb.topRight()<<rb.bottomRight()<<rb.bottomLeft();
  3897 		return p;
  3898 	}
  3899 
  3900 	// Take union of BBox and TotalBBox 
  3901 
  3902 	QRectF ra=bo->getTotalBBox();
  3903 	if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
  3904 		p   <<ra.bottomLeft()
  3905 			<<ra.topLeft()
  3906 			<<QPointF (rb.topLeft().x(), ra.topLeft().y() )
  3907 			<<rb.topRight()
  3908 			<<rb.bottomRight()
  3909 			<<QPointF (rb.bottomLeft().x(), ra.bottomLeft().y() ) ;
  3910 	else		
  3911 		p   <<ra.bottomRight()
  3912 			<<ra.topRight()
  3913 			<<QPointF (rb.topRight().x(), ra.topRight().y() )
  3914 			<<rb.topLeft()
  3915 			<<rb.bottomLeft()
  3916 			<<QPointF (rb.bottomRight().x(), ra.bottomRight().y() ) ;
  3917 	return p;		
  3918 
  3919 }
  3920 
  3921 void VymModel::moveAway(LinkableMapObj *lmo)
  3922 {
  3923 	// Autolayout:
  3924 	//
  3925 	// Move all branches and MapCenters away from lmo 
  3926 	// to avoid collisions 
  3927 
  3928 	QPolygonF pA;
  3929 	QPolygonF pB;
  3930 
  3931 	BranchObj *boA=(BranchObj*)lmo;
  3932 	BranchObj *boB;
  3933 	for (int i=0; i<mapCenters.count(); i++)
  3934 	{
  3935 		boB=mapCenters.at(i);
  3936 		pA=shape (boA);
  3937 		pB=shape (boB);
  3938 		PolygonCollisionResult r = PolygonCollision(pA, pB, QPoint(0,0));
  3939 		cout <<"------->"
  3940 			<<"="<<r.intersect
  3941 			<<"  ("<<qPrintable(boA->getHeading() )<<")"
  3942 			<<"  with ("<< qPrintable (boB->getHeading() )
  3943 			<<")  willIntersect"
  3944 			<<r.willIntersect 
  3945 			<<"  minT="<<r.minTranslation<<endl<<endl;
  3946 	}
  3947 }
  3948 
  3949 QPixmap VymModel::getPixmap()
  3950 {
  3951 	QRectF mapRect=getTotalBBox();
  3952 	QPixmap pix((int)mapRect.width()+2,(int)mapRect.height()+1);
  3953 	QPainter pp (&pix);
  3954 	
  3955 	pp.setRenderHints(mapEditor->renderHints());
  3956 
  3957 	// Don't print the visualisation of selection
  3958 	selection.unselect();
  3959 
  3960 	mapScene->render (	&pp, 
  3961 		QRectF(0,0,mapRect.width()+2,mapRect.height()+2),
  3962 		QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
  3963 
  3964 	// Restore selection
  3965 	selection.reselect();
  3966 	
  3967 	return pix;
  3968 }
  3969 
  3970 
  3971 void VymModel::setMapLinkStyle (const QString & s)
  3972 {
  3973 	QString snow;
  3974 	switch (linkstyle)
  3975 	{
  3976 		case LinkableMapObj::Line :
  3977 			snow="StyleLine";
  3978 			break;
  3979 		case LinkableMapObj::Parabel:
  3980 			snow="StyleParabel";
  3981 			break;
  3982 		case LinkableMapObj::PolyLine:
  3983 			snow="StylePolyLine";
  3984 			break;
  3985 		case LinkableMapObj::PolyParabel:
  3986 			snow="StylePolyParabel";
  3987 			break;
  3988 		default:	
  3989 			snow="UndefinedStyle";
  3990 			break;
  3991 	}
  3992 
  3993 	saveState (
  3994 		QString("setMapLinkStyle (\"%1\")").arg(s),
  3995 		QString("setMapLinkStyle (\"%1\")").arg(snow),
  3996 		QString("Set map link style (\"%1\")").arg(s)
  3997 	);	
  3998 
  3999 	if (s=="StyleLine")
  4000 		linkstyle=LinkableMapObj::Line;
  4001 	else if (s=="StyleParabel")
  4002 		linkstyle=LinkableMapObj::Parabel;
  4003 	else if (s=="StylePolyLine")
  4004 		linkstyle=LinkableMapObj::PolyLine;
  4005 	else if (s=="StylePolyParabel")	
  4006 		linkstyle=LinkableMapObj::PolyParabel;
  4007 	else
  4008 		linkstyle=LinkableMapObj::UndefinedStyle;
  4009 
  4010 	TreeItem *cur=NULL;
  4011 	TreeItem *prev=NULL;
  4012 	int d=0;
  4013 	BranchObj *bo;
  4014 	next (cur,prev,d);
  4015 	while (cur) 
  4016 	{
  4017 		bo=(BranchObj*)(cur->getLMO() );
  4018 		bo->setLinkStyle(bo->getDefLinkStyle());
  4019 		cur=next(cur,prev,d);
  4020 	}
  4021 	reposition();
  4022 }
  4023 
  4024 LinkableMapObj::Style VymModel::getMapLinkStyle ()
  4025 {
  4026 	return linkstyle;
  4027 }	
  4028 
  4029 void VymModel::setMapDefLinkColor(QColor col)
  4030 {
  4031 	if ( !col.isValid() ) return;
  4032 	saveState (
  4033 		QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
  4034 		QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
  4035 		QString("Set map link color to %1").arg(col.name())
  4036 	);
  4037 
  4038 	defLinkColor=col;
  4039 	TreeItem *cur=NULL;
  4040 	TreeItem *prev=NULL;
  4041 	int d=0;
  4042 	BranchObj *bo;
  4043 	cur=next(cur,prev,d);
  4044 	while (cur) 
  4045 	{
  4046 		bo=(BranchObj*)(cur->getLMO() );
  4047 		bo->setLinkColor();
  4048 		next(cur,prev,d);
  4049 	}
  4050 	updateActions();
  4051 }
  4052 
  4053 void VymModel::setMapLinkColorHintInt()
  4054 {
  4055 	// called from setMapLinkColorHint(lch) or at end of parse
  4056 	TreeItem *cur=NULL;
  4057 	TreeItem *prev=NULL;
  4058 	int d=0;
  4059 	BranchObj *bo;
  4060 	cur=next(cur,prev,d);
  4061 	while (cur) 
  4062 	{
  4063 		bo=(BranchObj*)(cur->getLMO() );
  4064 		bo->setLinkColor();
  4065 		cur=next(cur,prev,d);
  4066 	}
  4067 }
  4068 
  4069 void VymModel::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
  4070 {
  4071 	linkcolorhint=lch;
  4072 	setMapLinkColorHintInt();
  4073 }
  4074 
  4075 void VymModel::toggleMapLinkColorHint()
  4076 {
  4077 	if (linkcolorhint==LinkableMapObj::HeadingColor)
  4078 		linkcolorhint=LinkableMapObj::DefaultColor;
  4079 	else	
  4080 		linkcolorhint=LinkableMapObj::HeadingColor;
  4081 	TreeItem *cur=NULL;
  4082 	TreeItem *prev=NULL;
  4083 	int d=0;
  4084 	BranchObj *bo;
  4085 	cur=next(cur,prev,d);
  4086 	while (cur) 
  4087 	{
  4088 		bo=(BranchObj*)(cur->getLMO() );
  4089 		bo->setLinkColor();
  4090 		next(cur,prev,d);
  4091 	}
  4092 }
  4093 
  4094 void VymModel::selectMapBackgroundImage ()	// FIXME-2 move to ME
  4095 {
  4096 	Q3FileDialog *fd=new Q3FileDialog( NULL);
  4097 	fd->setMode (Q3FileDialog::ExistingFile);
  4098 	fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  4099 	ImagePreview *p =new ImagePreview (fd);
  4100 	fd->setContentsPreviewEnabled( TRUE );
  4101 	fd->setContentsPreview( p, p );
  4102 	fd->setPreviewMode( Q3FileDialog::Contents );
  4103 	fd->setCaption(vymName+" - " +tr("Load background image"));
  4104 	fd->setDir (lastImageDir);
  4105 	fd->show();
  4106 
  4107 	if ( fd->exec() == QDialog::Accepted )
  4108 	{
  4109 		// TODO selectMapBackgroundImg in QT4 use:	lastImageDir=fd->directory();
  4110 		lastImageDir=QDir (fd->dirPath());
  4111 		setMapBackgroundImage (fd->selectedFile());
  4112 	}
  4113 }	
  4114 
  4115 void VymModel::setMapBackgroundImage (const QString &fn)	//FIXME-2 missing savestate
  4116 {
  4117 	QColor oldcol=mapScene->backgroundBrush().color();
  4118 	/*
  4119 	saveState(
  4120 		selection,
  4121 		QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
  4122 		selection,
  4123 		QString ("setMapBackgroundImage (%1)").arg(col.name()),
  4124 		QString("Set background color of map to %1").arg(col.name()));
  4125 	*/	
  4126 	QBrush brush;
  4127 	brush.setTextureImage (QPixmap (fn));
  4128 	mapScene->setBackgroundBrush(brush);
  4129 }
  4130 
  4131 void VymModel::selectMapBackgroundColor()	// FIXME-1 move to ME
  4132 {
  4133 	QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), NULL);
  4134 	if ( !col.isValid() ) return;
  4135 	setMapBackgroundColor( col );
  4136 }
  4137 
  4138 
  4139 void VymModel::setMapBackgroundColor(QColor col)	// FIXME-1 move to ME
  4140 {
  4141 	QColor oldcol=mapScene->backgroundBrush().color();
  4142 	saveState(
  4143 		QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
  4144 		QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
  4145 		QString("Set background color of map to %1").arg(col.name()));
  4146 	mapScene->setBackgroundBrush(col);
  4147 }
  4148 
  4149 QColor VymModel::getMapBackgroundColor()	// FIXME-1 move to ME
  4150 {
  4151     return mapScene->backgroundBrush().color();
  4152 }
  4153 
  4154 
  4155 LinkableMapObj::ColorHint VymModel::getMapLinkColorHint()	// FIXME-1 move to ME
  4156 {
  4157 	return linkcolorhint;
  4158 }
  4159 
  4160 QColor VymModel::getMapDefLinkColor()	// FIXME-1 move to ME
  4161 {
  4162 	return defLinkColor;
  4163 }
  4164 
  4165 void VymModel::setMapDefXLinkColor(QColor col)	// FIXME-1 move to ME
  4166 {
  4167 	defXLinkColor=col;
  4168 }
  4169 
  4170 QColor VymModel::getMapDefXLinkColor()	// FIXME-1 move to ME
  4171 {
  4172 	return defXLinkColor;
  4173 }
  4174 
  4175 void VymModel::setMapDefXLinkWidth (int w)	// FIXME-1 move to ME
  4176 {
  4177 	defXLinkWidth=w;
  4178 }
  4179 
  4180 int VymModel::getMapDefXLinkWidth()	// FIXME-1 move to ME
  4181 {
  4182 	return defXLinkWidth;
  4183 }
  4184 
  4185 void VymModel::move(const double &x, const double &y)
  4186 {
  4187 	BranchObj *bo = getSelectedBranch();
  4188 	if (bo && 
  4189 		(selectionType()==TreeItem::Branch ||
  4190 		 selectionType()==TreeItem::MapCenter ||
  4191 		 selectionType()==TreeItem::Image
  4192 		))
  4193 	{
  4194         QPointF ap(bo->getAbsPos());
  4195         QPointF to(x, y);
  4196         if (ap != to)
  4197         {
  4198             QString ps=qpointfToString(ap);
  4199             QString s=getSelectString();
  4200             saveState(
  4201                 s, "move "+ps, 
  4202                 s, "move "+qpointfToString(to), 
  4203                 QString("Move %1 to %2").arg(getObjectName(bo)).arg(ps));
  4204             bo->move(x,y);
  4205             reposition();
  4206             selection.update();
  4207         }
  4208 	}
  4209 }
  4210 
  4211 void VymModel::moveRel (const double &x, const double &y)
  4212 {
  4213 	BranchObj *bo = getSelectedBranch();
  4214 	if (bo && 
  4215 		(selectionType()==TreeItem::Branch ||
  4216 		 selectionType()==TreeItem::MapCenter ||
  4217 		 selectionType()==TreeItem::Image
  4218 		))
  4219 	if (bo)
  4220 	{
  4221         QPointF rp(bo->getRelPos());
  4222         QPointF to(x, y);
  4223         if (rp != to)
  4224         {
  4225             QString ps=qpointfToString (bo->getRelPos());
  4226             QString s=getSelectString(bo);
  4227             saveState(
  4228                 s, "moveRel "+ps, 
  4229                 s, "moveRel "+qpointfToString(to), 
  4230                 QString("Move %1 to relative position %2").arg(getObjectName(bo)).arg(ps));
  4231             ((OrnamentedObj*)bo)->move2RelPos (x,y);
  4232             reposition();
  4233             bo->updateLink();
  4234             selection.update();
  4235         }
  4236 	}
  4237 }
  4238 
  4239 
  4240 void VymModel::animate()
  4241 {
  4242 	animationTimer->stop();
  4243 	BranchObj *bo;
  4244 	int i=0;
  4245 	while (i<animObjList.size() )
  4246 	{
  4247 		bo=(BranchObj*)animObjList.at(i);
  4248 		if (!bo->animate())
  4249 		{
  4250 			if (i>=0) 
  4251 			{	
  4252 				animObjList.removeAt(i);
  4253 				i--;
  4254 			}
  4255 		}
  4256 		bo->reposition();
  4257 		i++;
  4258 	} 
  4259 	QItemSelection sel=selModel->selection();
  4260 	emit (selectionChanged(sel,sel));
  4261 
  4262 	mapScene->update();
  4263 	if (!animObjList.isEmpty()) animationTimer->start();
  4264 }
  4265 
  4266 
  4267 void VymModel::startAnimation(BranchObj *bo, const QPointF &start, const QPointF &dest)
  4268 {
  4269 	if (bo && bo->getDepth()>0) 
  4270 	{
  4271 		AnimPoint ap;
  4272 		ap.setStart (start);
  4273 		ap.setDest  (dest);
  4274 		ap.setTicks (animationTicks);
  4275 		ap.setAnimated (true);
  4276 		bo->setAnimation (ap);
  4277 		animObjList.append( bo );
  4278 		animationTimer->setSingleShot (true);
  4279 		animationTimer->start(animationInterval);
  4280 	}
  4281 }
  4282 
  4283 void VymModel::stopAnimation (MapObj *mo)
  4284 {
  4285 	int i=animObjList.indexOf(mo);
  4286     if (i>=0)
  4287 		animObjList.removeAt (i);
  4288 }
  4289 
  4290 void VymModel::sendSelection()
  4291 {
  4292 	if (netstate!=Server) return;
  4293 	sendData (QString("select (\"%1\")").arg(selection.getSelectString()) );
  4294 }
  4295 
  4296 void VymModel::newServer()
  4297 {
  4298 	port=54321;
  4299 	sendCounter=0;
  4300     tcpServer = new QTcpServer(this);
  4301     if (!tcpServer->listen(QHostAddress::Any,port)) {
  4302         QMessageBox::critical(NULL, "vym server",
  4303                               QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
  4304         //FIXME-3 needed? we are no widget any longer... close();
  4305         return;
  4306     }
  4307 	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
  4308 	netstate=Server;
  4309 	cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
  4310 }
  4311 
  4312 void VymModel::connectToServer()
  4313 {
  4314 	port=54321;
  4315 	server="salam.suse.de";
  4316 	server="localhost";
  4317 	clientSocket = new QTcpSocket (this);
  4318 	clientSocket->abort();
  4319     clientSocket->connectToHost(server ,port);
  4320 	connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
  4321     connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
  4322             this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
  4323 	netstate=Client;		
  4324 	cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
  4325 
  4326 	
  4327 }
  4328 
  4329 void VymModel::newClient()
  4330 {
  4331     QTcpSocket *newClient = tcpServer->nextPendingConnection();
  4332     connect(newClient, SIGNAL(disconnected()),
  4333             newClient, SLOT(deleteLater()));
  4334 
  4335 	cout <<"ME::newClient  at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
  4336 
  4337 	clientList.append (newClient);
  4338 }
  4339 
  4340 
  4341 void VymModel::sendData(const QString &s)
  4342 {
  4343 	if (clientList.size()==0) return;
  4344 
  4345 	// Create bytearray to send
  4346 	QByteArray block;
  4347     QDataStream out(&block, QIODevice::WriteOnly);
  4348     out.setVersion(QDataStream::Qt_4_0);
  4349 
  4350 	// Reserve some space for blocksize
  4351     out << (quint16)0;
  4352 
  4353 	// Write sendCounter
  4354     out << sendCounter++;
  4355 
  4356 	// Write data
  4357     out << s;
  4358 
  4359 	// Go back and write blocksize so far
  4360     out.device()->seek(0);
  4361     quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
  4362 	out << bs;
  4363 
  4364 	if (debug)
  4365 		cout << "ME::sendData  bs="<<bs<<"  counter="<<sendCounter<<"  s="<<qPrintable(s)<<endl;
  4366 
  4367 	for (int i=0; i<clientList.size(); ++i)
  4368 	{
  4369 		//cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
  4370 		clientList.at(i)->write (block);
  4371 	}
  4372 }
  4373 
  4374 void VymModel::readData ()
  4375 {
  4376 	while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
  4377 	{
  4378 		if (debug)
  4379 			cout <<"readData  bytesAvail="<<clientSocket->bytesAvailable();
  4380 		quint16 recCounter;
  4381 		quint16 blockSize;
  4382 
  4383 		QDataStream in(clientSocket);
  4384 		in.setVersion(QDataStream::Qt_4_0);
  4385 
  4386 		in >> blockSize;
  4387 		in >> recCounter;
  4388 		
  4389 		QString t;
  4390 		in >>t;
  4391 		if (debug)
  4392 			cout << "  t="<<qPrintable (t)<<endl;
  4393 		parseAtom (t);
  4394 	}
  4395 	return;
  4396 }
  4397 
  4398 void VymModel::displayNetworkError(QAbstractSocket::SocketError socketError)
  4399 {
  4400     switch (socketError) {
  4401     case QAbstractSocket::RemoteHostClosedError:
  4402         break;
  4403     case QAbstractSocket::HostNotFoundError:
  4404         QMessageBox::information(NULL, vymName +" Network client",
  4405                                  "The host was not found. Please check the "
  4406                                     "host name and port settings.");
  4407         break;
  4408     case QAbstractSocket::ConnectionRefusedError:
  4409         QMessageBox::information(NULL, vymName + " Network client",
  4410                                  "The connection was refused by the peer. "
  4411                                     "Make sure the fortune server is running, "
  4412                                     "and check that the host name and port "
  4413                                     "settings are correct.");
  4414         break;
  4415     default:
  4416         QMessageBox::information(NULL, vymName + " Network client",
  4417                                  QString("The following error occurred: %1.")
  4418                                  .arg(clientSocket->errorString()));
  4419     }
  4420 }
  4421 
  4422 
  4423 
  4424 
  4425 void VymModel::selectMapSelectionColor()
  4426 {
  4427 	QColor col = QColorDialog::getColor( defLinkColor, NULL);
  4428 	setSelectionColor (col);
  4429 }
  4430 
  4431 void VymModel::setSelectionColorInt (QColor col)
  4432 {
  4433 	if ( !col.isValid() ) return;
  4434 	saveState (
  4435 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4436 		QString("setSelectionColor (%1)").arg(col.name()),
  4437 		QString("Set color of selection box to %1").arg(col.name())
  4438 	);
  4439 
  4440 	mapEditor->setSelectionColor (col);
  4441 }
  4442 
  4443 /*
  4444 void VymModel::changeSelection (const QItemSelection &newsel,const QItemSelection &oldsel)
  4445 {
  4446 	cout << "VymModel::changeSelection (";
  4447 	if (!newsel.indexes().isEmpty() )
  4448 		cout << getItem(newsel.indexes().first() )->getHeading().toStdString();
  4449 	cout << ",";
  4450 	if (!oldsel.indexes().isEmpty() )
  4451 		cout << getItem(oldsel.indexes().first() )->getHeading().toStdString();
  4452 	cout << ")\n";
  4453 }
  4454 */
  4455 
  4456 void VymModel::updateSelection(const QItemSelection &newsel)
  4457 {
  4458 	emit (selectionChanged(newsel,newsel));	// needed e.g. to update geometry in editor
  4459 	ensureSelectionVisible();
  4460 	sendSelection();
  4461 }
  4462 
  4463 void VymModel::updateSelection()
  4464 {
  4465 	QItemSelection newsel=selModel->selection();
  4466 	updateSelection (newsel);
  4467 }
  4468 
  4469 void VymModel::setSelectionColor(QColor col)
  4470 {
  4471 	if ( !col.isValid() ) return;
  4472 	saveState (
  4473 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4474 		QString("setSelectionColor (%1)").arg(col.name()),
  4475 		QString("Set color of selection box to %1").arg(col.name())
  4476 	);
  4477 	setSelectionColorInt (col);
  4478 }
  4479 
  4480 QColor VymModel::getSelectionColor()
  4481 {
  4482 	return mapEditor->getSelectionColor();
  4483 }
  4484 
  4485 void VymModel::setHideTmpMode (HideTmpMode mode)
  4486 {
  4487 	hidemode=mode;
  4488 	for (int i=0;i<mapCenters.count(); i++)
  4489 		mapCenters.at(i)->setHideTmp (mode);	
  4490 	reposition();
  4491 	// FIXME-3 needed? scene()->update();
  4492 }
  4493 
  4494 
  4495 QRectF VymModel::getTotalBBox()
  4496 {
  4497 	QRectF r;
  4498 	for (int i=0;i<mapCenters.count(); i++)
  4499 		r=addBBox (mapCenters.at(i)->getTotalBBox(), r);
  4500 	return r;	
  4501 }
  4502 
  4503 //////////////////////////////////////////////
  4504 // Selection related
  4505 //////////////////////////////////////////////
  4506 
  4507 void VymModel::setSelectionModel (QItemSelectionModel *sm)
  4508 {
  4509 	selModel=sm;
  4510 }
  4511 
  4512 QItemSelectionModel* VymModel::getSelectionModel()
  4513 {
  4514 	return selModel;
  4515 }
  4516 
  4517 void VymModel::setSelectionBlocked (bool b)
  4518 {
  4519 	if (b)
  4520 		selection.block();
  4521 	else	
  4522 		selection.unblock();
  4523 }
  4524 
  4525 bool VymModel::isSelectionBlocked()
  4526 {
  4527 	return selection.isBlocked();
  4528 }
  4529 
  4530 bool VymModel::select ()
  4531 {
  4532 	QModelIndex index=selModel->selectedIndexes().first();	// TODO no multiselections yet
  4533 
  4534 	TreeItem *item = getItem (index);
  4535 	return select (item->getLMO() );
  4536 }
  4537 
  4538 bool VymModel::select (const QString &s)
  4539 {
  4540 	LinkableMapObj *lmo=findObjBySelect(s);
  4541 
  4542 	// Finally select the found object
  4543 	if (lmo)
  4544 	{
  4545 		unselect();
  4546 		select (lmo);
  4547 		return true;
  4548 	} 
  4549 	return false;
  4550 }
  4551 
  4552 bool VymModel::select (LinkableMapObj *lmo)
  4553 {
  4554 	QItemSelection oldsel=selModel->selection();
  4555 
  4556 	if (lmo)
  4557 		return select (lmo->getTreeItem() );
  4558 	else	
  4559 		return false;
  4560 }
  4561 
  4562 bool VymModel::select (TreeItem *ti)
  4563 {
  4564 	if (ti)
  4565 	{
  4566 		QModelIndex ix=index(ti);
  4567 		selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4568 		ti->setLastSelectedBranch();
  4569 		//updateSelection(oldsel);	//FIXME-3 needed?
  4570 		return true;
  4571 	}
  4572 	return false;
  4573 }
  4574 
  4575 void VymModel::unselect()
  4576 {
  4577 	selModel->clearSelection();
  4578 }	
  4579 
  4580 void VymModel::reselect()
  4581 {
  4582 	selection.reselect();
  4583 }	
  4584 
  4585 void VymModel::ensureSelectionVisible()		//FIXME-3 needed? in vymmodel.h commented...
  4586 {
  4587 	LinkableMapObj *lmo=getSelectedLMO();
  4588 	if (lmo &&mapEditor) mapEditor->ensureVisible (lmo->getBBox() );
  4589 }
  4590 
  4591 void VymModel::emitContentHasChanged (TreeItem *ti)
  4592 {
  4593 	QModelIndex ix=index(ti);
  4594 	emit (contentHasChanged (ix) );
  4595 }
  4596 
  4597 void VymModel::selectInt (LinkableMapObj *lmo)
  4598 {
  4599 	if (selection.select(lmo))
  4600 	{
  4601 		//selection.update();
  4602 		sendSelection ();	// FIXME-4 VM use signal
  4603 	}
  4604 }
  4605 
  4606 
  4607 void VymModel::selectNextBranchInt()
  4608 {
  4609 	// Increase number of branch
  4610 	LinkableMapObj *sel=getSelectedBranch();
  4611 	if (sel)
  4612 	{
  4613 		QString s=getSelectString();
  4614 		QString part;
  4615 		QString typ;
  4616 		QString num;
  4617 
  4618 		// Where am I? 
  4619 		part=s.section(",",-1);
  4620 		typ=part.left (3);
  4621 		num=part.right(part.length() - 3);
  4622 
  4623 		s=s.left (s.length() -num.length());
  4624 
  4625 		// Go to next lmo
  4626 		num=QString ("%1").arg(num.toUInt()+1);
  4627 
  4628 		s=s+num;
  4629 		
  4630 		// Try to select this one
  4631 		if (select (s)) return;
  4632 
  4633 		// We have no direct successor, 
  4634 		// try to increase the parental number in order to
  4635 		// find a successor with same depth
  4636 
  4637 		int d=getSelectedLMO()->getDepth();
  4638 		int oldDepth=d;
  4639 		int i;
  4640 		bool found=false;
  4641 		bool b;
  4642 		while (!found && d>0)
  4643 		{
  4644 			s=s.section (",",0,d-1);
  4645 			// replace substring of current depth in s with "1"
  4646 			part=s.section(",",-1);
  4647 			typ=part.left (3);
  4648 			num=part.right(part.length() - 3);
  4649 
  4650 			if (d>1)
  4651 			{	
  4652 				// increase number of parent
  4653 				num=QString ("%1").arg(num.toUInt()+1);
  4654 				s=s.section (",",0,d-2) + ","+ typ+num;
  4655 			} else
  4656 			{
  4657 				// Special case, look at orientation
  4658 				if (getSelectedLMO()->getOrientation()==LinkableMapObj::RightOfCenter)
  4659 					num=QString ("%1").arg(num.toUInt()+1);
  4660 				else	
  4661 					num=QString ("%1").arg(num.toUInt()-1);
  4662 				s=typ+num;
  4663 			}	
  4664 
  4665 			if (select (s))
  4666 				// pad to oldDepth, select the first branch for each depth
  4667 				for (i=d;i<oldDepth;i++)
  4668 				{
  4669 					b=select (s);
  4670 					if (b)
  4671 					{	
  4672 						if ( getSelectedBranch()->countBranches()>0)
  4673 							s+=",bo:0";
  4674 						else	
  4675 							break;
  4676 					} else
  4677 						break;
  4678 				}	
  4679 
  4680 			// try to select the freshly built string
  4681 			found=select(s);
  4682 			d--;
  4683 		}
  4684 		return;
  4685 	}	
  4686 }
  4687 
  4688 void VymModel::selectPrevBranchInt()
  4689 {
  4690 	// Decrease number of branch
  4691 	if (selectionType()==TreeItem::Branch)
  4692 	{
  4693 		QString s=getSelectString();
  4694 		QString part;
  4695 		QString typ;
  4696 		QString num;
  4697 
  4698 		// Where am I? 
  4699 		part=s.section(",",-1);
  4700 		typ=part.left (3);
  4701 		num=part.right(part.length() - 3);
  4702 
  4703 		s=s.left (s.length() -num.length());
  4704 
  4705 		int n=num.toInt()-1;
  4706 		
  4707 		// Go to next lmo
  4708 		num=QString ("%1").arg(n);
  4709 		s=s+num;
  4710 		
  4711 		// Try to select this one
  4712 		if (n>=0 && select (s)) return;
  4713 
  4714 		// We have no direct precessor, 
  4715 		// try to decrease the parental number in order to
  4716 		// find a precessor with same depth
  4717 
  4718 		int d=getSelectedLMO()->getDepth();
  4719 		int oldDepth=d;
  4720 		int i;
  4721 		bool found=false;
  4722 		bool b;
  4723 		while (!found && d>0)
  4724 		{
  4725 			s=s.section (",",0,d-1);
  4726 			// replace substring of current depth in s with "1"
  4727 			part=s.section(",",-1);
  4728 			typ=part.left (3);
  4729 			num=part.right(part.length() - 3);
  4730 
  4731 			if (d>1)
  4732 			{
  4733 				// decrease number of parent
  4734 				num=QString ("%1").arg(num.toInt()-1);
  4735 				s=s.section (",",0,d-2) + ","+ typ+num;
  4736 			} else
  4737 			{
  4738 				// Special case, look at orientation
  4739 				if (getSelectedLMO()->getOrientation()==LinkableMapObj::RightOfCenter)
  4740 					num=QString ("%1").arg(num.toInt()-1);
  4741 				else	
  4742 					num=QString ("%1").arg(num.toInt()+1);
  4743 				s=typ+num;
  4744 			}	
  4745 
  4746 			if (select(s))
  4747 				// pad to oldDepth, select the last branch for each depth
  4748 				for (i=d;i<oldDepth;i++)
  4749 				{
  4750 					b=select (s);
  4751 					if (b)
  4752 						if ( getSelectedBranch()->countBranches()>0)
  4753 							s+=",bo:"+ QString ("%1").arg( getSelectedBranch()->countBranches()-1 );
  4754 						else	
  4755 							break;
  4756 					else
  4757 						break;
  4758 				}	
  4759 			
  4760 			// try to select the freshly built string
  4761 			found=select(s);
  4762 			d--;
  4763 		}
  4764 		return;
  4765 	}	
  4766 }
  4767 
  4768 void VymModel::selectUpperBranch()
  4769 {
  4770 	if (selection.isBlocked() ) return;
  4771 
  4772 	BranchObj *bo=getSelectedBranch();
  4773 	if (bo && selectionType()==TreeItem::Branch)
  4774 	{
  4775 		if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  4776 			selectPrevBranchInt();
  4777 		else
  4778 			if (bo->getDepth()==1)
  4779 				selectNextBranchInt();
  4780 			else
  4781 				selectPrevBranchInt();
  4782 	}
  4783 }
  4784 
  4785 void VymModel::selectLowerBranch()
  4786 {
  4787 	if (selection.isBlocked() ) return;
  4788 
  4789 	BranchObj *bo=getSelectedBranch();
  4790 	if (bo && selectionType()==TreeItem::Branch)
  4791 	{
  4792 		if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  4793 			selectNextBranchInt();
  4794 		else
  4795 			if (bo->getDepth()==1)
  4796 				selectPrevBranchInt();
  4797 			else
  4798 				selectNextBranchInt();
  4799 	}			
  4800 }
  4801 
  4802 
  4803 void VymModel::selectLeftBranch()
  4804 {
  4805 	if (selection.isBlocked() ) return;
  4806 
  4807 	QItemSelection oldsel=selModel->selection();
  4808 
  4809 	BranchObj* par;
  4810 	LinkableMapObj *sel=getSelectedBranch();
  4811 	if (sel)
  4812 	{
  4813 		if (selectionType()== TreeItem::MapCenter)
  4814 		{
  4815 			QModelIndex ix=getSelectedIndex();
  4816 			selModel->select (index (rowCount(ix)-1,0,ix),QItemSelectionModel::ClearAndSelect  );
  4817 		} else
  4818 		{
  4819 			par=(BranchObj*)(sel->getParObj());
  4820 			if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
  4821 			{
  4822 				// right of center
  4823 				if (selectionType() == TreeItem::Branch ||
  4824 					selectionType() == TreeItem::Image)
  4825 				{
  4826 					QModelIndex ix=getSelectedIndex();
  4827 					ix=parent(ix);
  4828 					selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4829 				}
  4830 			} else
  4831 			{
  4832 				// left of center
  4833 				if (selectionType() == TreeItem::Branch )
  4834 				{
  4835 					selectLastSelectedBranch();
  4836 					return;
  4837 				}
  4838 			}
  4839 		}	
  4840 		updateSelection (oldsel);
  4841 	}
  4842 }
  4843 
  4844 void VymModel::selectRightBranch()
  4845 {
  4846 	if (selection.isBlocked() ) return;
  4847 
  4848 	QItemSelection oldsel=selModel->selection();
  4849 
  4850 	BranchObj* par;
  4851 	LinkableMapObj *sel=getSelectedBranch();
  4852 	if (sel)
  4853 	{
  4854 		if (selectionType()== TreeItem::MapCenter)
  4855 		{
  4856 			QModelIndex ix=getSelectedIndex();
  4857 			selModel->select (index (0,0,ix),QItemSelectionModel::ClearAndSelect  );
  4858 		} else
  4859 		{
  4860 			par=(BranchObj*)(sel->getParObj());
  4861 			if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
  4862 			{
  4863 				// right of center
  4864 				if (selectionType() == TreeItem::Branch )
  4865 				{
  4866 					selectLastSelectedBranch();
  4867 					return;
  4868 				}
  4869 			} else
  4870 			{
  4871 				// left of center
  4872 				if (selectionType() == TreeItem::Branch ||
  4873 					selectionType() == TreeItem::Image)
  4874 				{
  4875 					QModelIndex ix=getSelectedIndex();
  4876 					ix=parent(ix);
  4877 					selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4878 				}
  4879 			}
  4880 		}	
  4881 		updateSelection (oldsel);
  4882 	}
  4883 }
  4884 
  4885 void VymModel::selectFirstBranch()
  4886 {
  4887 	TreeItem *ti=getSelectedBranchItem();
  4888 	if (ti)
  4889 	{
  4890 		TreeItem *par=ti->parent();
  4891 		if (!par) return;
  4892 		TreeItem *ti2=par->getFirstBranch();
  4893 		if (ti2) {
  4894 			select(ti2);
  4895 			selection.update();
  4896 			ensureSelectionVisible();
  4897 			sendSelection();
  4898 		}
  4899 	}		
  4900 }
  4901 
  4902 void VymModel::selectLastBranch()
  4903 {
  4904 	TreeItem *ti=getSelectedBranchItem();
  4905 	if (ti)
  4906 	{
  4907 		TreeItem *par=ti->parent();
  4908 		if (!par) return;
  4909 		TreeItem *ti2=par->getLastBranch();
  4910 		if (ti2) {
  4911 			select(ti2);
  4912 			selection.update();
  4913 			ensureSelectionVisible();
  4914 			sendSelection();
  4915 		}
  4916 	}		
  4917 }
  4918 
  4919 void VymModel::selectLastSelectedBranch()
  4920 {
  4921 	TreeItem *ti=getSelectedBranchItem();
  4922 	if (ti)
  4923 	{
  4924 		ti=ti->getLastSelectedBranch();
  4925 		if (ti) select (ti);
  4926 	}		
  4927 }
  4928 
  4929 void VymModel::selectParent()
  4930 {
  4931 	TreeItem *ti=getSelectedItem();
  4932 	TreeItem *par;
  4933 	if (ti)
  4934 	{
  4935 		par=ti->parent();
  4936 		if (!par) return;
  4937 		select(par);
  4938 		selection.update();
  4939 		ensureSelectionVisible();
  4940 		sendSelection();
  4941 	}		
  4942 }
  4943 
  4944 TreeItem::Type VymModel::selectionType()
  4945 {
  4946 	QModelIndexList list=selModel->selectedIndexes();
  4947 	if (list.isEmpty()) return TreeItem::Undefined;	
  4948 	TreeItem *ti = getItem (list.first() );
  4949 	return ti->getType();
  4950 
  4951 }
  4952 
  4953 LinkableMapObj* VymModel::getSelectedLMO()
  4954 {
  4955 	QModelIndexList list=selModel->selectedIndexes();
  4956 	if (!list.isEmpty() )
  4957 	{
  4958 		TreeItem *ti = getItem (list.first() );
  4959 		TreeItem::Type type=ti->getType();
  4960 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter || type==TreeItem::Image)
  4961 		{
  4962 			return ti->getLMO();
  4963 		}	
  4964 	}
  4965 	return NULL;
  4966 }
  4967 
  4968 BranchObj* VymModel::getSelectedBranch()
  4969 {
  4970 	TreeItem *ti = getSelectedBranchItem();
  4971 	if (ti)
  4972 		return (BranchObj*)ti->getLMO();
  4973 	else	
  4974 		return NULL;
  4975 }
  4976 
  4977 TreeItem* VymModel::getSelectedBranchItem()
  4978 {
  4979 	QModelIndexList list=selModel->selectedIndexes();
  4980 	if (!list.isEmpty() )
  4981 	{
  4982 		TreeItem *ti = getItem (list.first() );
  4983 		TreeItem::Type type=ti->getType();
  4984 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter)
  4985 			return ti;
  4986 	}
  4987 	return NULL;
  4988 }
  4989 
  4990 TreeItem* VymModel::getSelectedItem()
  4991 {
  4992 	QModelIndexList list=selModel->selectedIndexes();
  4993 	if (!list.isEmpty() )
  4994 		return getItem (list.first() );
  4995 	else	
  4996 		return NULL;
  4997 }
  4998 
  4999 QModelIndex VymModel::getSelectedIndex()
  5000 {
  5001 	QModelIndexList list=selModel->selectedIndexes();
  5002 	if (list.isEmpty() )
  5003 		return QModelIndex();
  5004 	else
  5005 		return list.first();
  5006 }
  5007 
  5008 FloatImageObj* VymModel::getSelectedFloatImage()
  5009 {
  5010 	return selection.getFloatImage();	
  5011 }
  5012 
  5013 QString VymModel::getSelectString ()
  5014 {
  5015 	LinkableMapObj *lmo=getSelectedLMO();
  5016 	if (lmo) 
  5017 		return getSelectString(lmo);
  5018 	else
  5019 		return QString();
  5020 }
  5021 
  5022 QString VymModel::getSelectString (LinkableMapObj *lmo)	// FIXME-2 VM needs to use TreeModel
  5023 {
  5024 	QString s;
  5025 	if (!lmo) return s;
  5026 	if (typeid(*lmo)==typeid(BranchObj) ||
  5027 		typeid(*lmo)==typeid(MapCenterObj) )
  5028 	{	
  5029 		LinkableMapObj *par=lmo->getParObj();
  5030 		if (par)
  5031 		{
  5032 			if (lmo->getDepth() ==1)
  5033 				// Mainbranch, return 
  5034 				s= "bo:" + QString("%1").arg(((BranchObj*)lmo)->getNum());
  5035 			else	
  5036 				// Branch, call myself recursively
  5037 				s= getSelectString(par) + ",bo:" + QString("%1").arg(((BranchObj*)lmo)->getNum());
  5038 		} else
  5039 		{
  5040 			// MapCenter
  5041 			int i=mapCenters.indexOf ((MapCenterObj*)lmo);
  5042 			if (i>=0) s=QString("mc:%1").arg(i);
  5043 		}	
  5044 	}	
  5045 	return s;
  5046 }
  5047