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