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