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