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