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