vymmodel.cpp
author insilmaril
Wed, 04 Feb 2009 16:33:16 +0000
changeset 740 6dc0a20031f7
parent 739 3d43b46a8564
child 741 1b4d1ea6ea8c
permissions -rw-r--r--
started to rewrite first(), next()
     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 LinkableMapObj* VymModel::findMapObj(QPointF p, LinkableMapObj *excludeLMO)
  1357 {
  1358 	LinkableMapObj *lmo;
  1359 
  1360 	for (int i=0;i<mapCenters.count(); i++)
  1361 	{
  1362 		lmo=mapCenters.at(i)->findMapObj (p,excludeLMO);
  1363 		if (lmo) return lmo;
  1364 	}
  1365 	return NULL;
  1366 }
  1367 
  1368 LinkableMapObj* VymModel::findObjBySelect(const QString &s)
  1369 {
  1370 	LinkableMapObj *lmo;
  1371 	if (!s.isEmpty() )
  1372 	{
  1373 		QString part;
  1374 		QString typ;
  1375 		QString num;
  1376 		part=s.section(",",0,0);
  1377 		typ=part.left (2);
  1378 		num=part.right(part.length() - 3);
  1379 		if (typ=="mc" && num.toInt()>=0 && num.toInt() <mapCenters.count() )
  1380 			return mapCenters.at(num.toInt() );
  1381 	}		
  1382 
  1383 	for (int i=0; i<mapCenters.count(); i++)
  1384 	{
  1385 		lmo=mapCenters.at(i)->findObjBySelect(s);
  1386 		if (lmo) return lmo;
  1387 	}	
  1388 	return NULL;
  1389 }
  1390 
  1391 LinkableMapObj* VymModel::findID (const QString &s)
  1392 {
  1393 	LinkableMapObj *lmo;
  1394 	for (int i=0; i<mapCenters.count(); i++)
  1395 	{
  1396 		lmo=mapCenters.at(i)->findID (s);
  1397 		if (lmo) return lmo;
  1398 	}	
  1399 	return NULL;
  1400 }
  1401 
  1402 QString VymModel::saveToDir (const QString &tmpdir,const QString &prefix, int verbose, const QPointF &offset)
  1403 {
  1404     QString s;
  1405 
  1406 	for (int i=0; i<mapCenters.count(); i++)
  1407 		s+=mapCenters.at(i)->saveToDir (tmpdir,prefix,verbose,offset);
  1408     return s;
  1409 }
  1410 
  1411 //////////////////////////////////////////////
  1412 // Interface 
  1413 //////////////////////////////////////////////
  1414 void VymModel::setVersion (const QString &s)
  1415 {
  1416 	version=s;
  1417 }
  1418 
  1419 void VymModel::setAuthor (const QString &s)
  1420 {
  1421 	saveState (
  1422 		QString ("setMapAuthor (\"%1\")").arg(author),
  1423 		QString ("setMapAuthor (\"%1\")").arg(s),
  1424 		QString ("Set author of map to \"%1\"").arg(s)
  1425 	);
  1426 
  1427 	author=s;
  1428 }
  1429 
  1430 QString VymModel::getAuthor()
  1431 {
  1432 	return author;
  1433 }
  1434 
  1435 void VymModel::setComment (const QString &s)
  1436 {
  1437 	saveState (
  1438 		QString ("setMapComment (\"%1\")").arg(comment),
  1439 		QString ("setMapComment (\"%1\")").arg(s),
  1440 		QString ("Set comment of map")
  1441 	);
  1442 
  1443 	comment=s;
  1444 }
  1445 
  1446 QString VymModel::getComment ()
  1447 {
  1448 	return comment;
  1449 }
  1450 
  1451 QString VymModel::getDate ()
  1452 {
  1453 	return QDate::currentDate().toString ("yyyy-MM-dd");
  1454 }
  1455 
  1456 void VymModel::setHeading(const QString &s)
  1457 {
  1458 	BranchObj *sel=getSelectedBranch();
  1459 	if (sel)
  1460 	{
  1461 		saveState(
  1462 			sel,
  1463 			"setHeading (\""+sel->getHeading()+"\")", 
  1464 			sel,
  1465 			"setHeading (\""+s+"\")", 
  1466 			QString("Set heading of %1 to \"%2\"").arg(getObjectName(sel)).arg(s) );
  1467 		sel->setHeading(s );
  1468 		/* FIXME testing only
  1469 		*/
  1470 		TreeItem *ti=getSelectedItem();
  1471 		if (ti)
  1472 		{
  1473 			ti->setHeading (s);
  1474 			//FIXME VM ix is wrong ModelIndex below, ix2 is (hopefully) correct:
  1475 			//QModelIndex ix=index( ti->row(), ti->column(), index (0,0,QModelIndex()) );
  1476 			//FIXME VM testing only cout <<"VM::setHeading  s="<<s.toStdString()<<"  ti="<<ti<<"  r,c=("<<ti->row()<<","<<ti->column()<<")"<<endl;
  1477 			QModelIndex ix2=index (ti);
  1478 			emit (dataChanged ( ix2,ix2));
  1479 		}
  1480 		else
  1481 		{
  1482 			cout << "Warning: VM::setHeading ti==NULL\n";
  1483 		}
  1484 
  1485 		//cout <<"                (r,c)=("<<ix2.row()<<","<<ix2.column()<<")"<<endl;
  1486 
  1487 		reposition();
  1488 		selection.update();
  1489 		ensureSelectionVisible();
  1490 	}
  1491 }
  1492 
  1493 BranchObj* VymModel::findText (QString s, bool cs)   // FIXME needs to converted to first() next() next (ti)
  1494 {
  1495 	/*
  1496 	QTextDocument::FindFlags flags=0;
  1497 	if (cs) flags=QTextDocument::FindCaseSensitively;
  1498 
  1499 	if (!itFind) 
  1500 	{	// Nothing found or new find process
  1501 		if (EOFind)
  1502 			// nothing found, start again
  1503 			EOFind=false;
  1504 		itFind=first();
  1505 	}	
  1506 	bool searching=true;
  1507 	bool foundNote=false;
  1508 	while (searching && !EOFind)
  1509 	{
  1510 		if (itFind)
  1511 		{
  1512 			// Searching in Note
  1513 			if (itFind->getNote().contains(s,cs))
  1514 			{
  1515 				if (getSelectedBranch()!=itFind) 
  1516 				{
  1517 					select(itFind);
  1518 					ensureSelectionVisible();
  1519 				}
  1520 				if (textEditor->findText(s,flags)) 
  1521 				{
  1522 					searching=false;
  1523 					foundNote=true;
  1524 				}	
  1525 			}
  1526 			// Searching in Heading
  1527 			if (searching && itFind->getHeading().contains (s,cs) ) 
  1528 			{
  1529 				select(itFind);
  1530 				ensureSelectionVisible();
  1531 				searching=false;
  1532 			}
  1533 		}	
  1534 		if (!foundNote)
  1535 		{
  1536 			itFind=next(itFind);
  1537 			if (!itFind) EOFind=true;
  1538 		}
  1539 	//cout <<"still searching...  "<<qPrintable( itFind->getHeading())<<endl;
  1540 	}	
  1541 	if (!searching)
  1542 		return getSelectedBranch();
  1543 	else
  1544 		return NULL;
  1545 		*/
  1546 }
  1547 
  1548 void VymModel::findReset()
  1549 {	// Necessary if text to find changes during a find process
  1550 	itFind=NULL;
  1551 	EOFind=false;
  1552 }
  1553 
  1554 
  1555 
  1556 void VymModel::setScene (QGraphicsScene *s)
  1557 {
  1558 	cout << "VM::setscene scene="<<s<<endl;
  1559 	mapScene=s;	// FIXME VM should not be necessary anymore, move all occurences to MapEditor
  1560     //init();	// Here we have a mapScene set, 
  1561 			// which is (still) needed to create MapCenters
  1562 }
  1563 
  1564 void VymModel::setURL(const QString &url)
  1565 {
  1566 	BranchObj *bo=getSelectedBranch();
  1567 	if (bo)
  1568 	{
  1569 		QString oldurl=bo->getURL();
  1570 		bo->setURL (url);
  1571 		saveState (
  1572 			bo,
  1573 			QString ("setURL (\"%1\")").arg(oldurl),
  1574 			bo,
  1575 			QString ("setURL (\"%1\")").arg(url),
  1576 			QString ("set URL of %1 to %2").arg(getObjectName(bo)).arg(url)
  1577 		);
  1578 		updateActions();
  1579 		reposition();
  1580 		selection.update();
  1581 		ensureSelectionVisible();
  1582 	}
  1583 }	
  1584 
  1585 QString VymModel::getURL()
  1586 {
  1587 	BranchObj *bo=getSelectedBranch();
  1588 	if (bo)
  1589 		return bo->getURL();
  1590 	else
  1591 		return "";
  1592 }
  1593 
  1594 QStringList VymModel::getURLs()
  1595 {
  1596 	QStringList urls;
  1597 	BranchObj *bo=getSelectedBranch();
  1598 	if (bo)
  1599 	{		
  1600 		bo=bo->first();	
  1601 		while (bo) 
  1602 		{
  1603 			if (!bo->getURL().isEmpty()) urls.append( bo->getURL());
  1604 			bo=bo->next();
  1605 		}	
  1606 	}	
  1607 	return urls;
  1608 }
  1609 
  1610 void VymModel::linkFloatImageTo(const QString &dstString)	
  1611 {
  1612 	FloatImageObj *fio=selection.getFloatImage();
  1613 	if (fio)
  1614 	{
  1615 		BranchObj *dst=(BranchObj*)findObjBySelect(dstString);
  1616 		if (dst && (typeid(*dst)==typeid (BranchObj) || 
  1617 					typeid(*dst)==typeid (MapCenterObj)))
  1618 		{			
  1619 			LinkableMapObj *dstPar=dst->getParObj();
  1620 			QString parString=getSelectString(dstPar);
  1621 			QString fioPreSelectString=getSelectString(fio);
  1622 			QString fioPreParentSelectString=getSelectString (fio->getParObj());
  1623 			((BranchObj*)dst)->addFloatImage (fio);
  1624 			selection.unselect();
  1625 			((BranchObj*)(fio->getParObj()))->removeFloatImage (fio);
  1626 			fio=((BranchObj*)dst)->getLastFloatImage();
  1627 			fio->setRelPos();
  1628 			fio->reposition();
  1629 			selection.select(fio);
  1630 			saveState(
  1631 				getSelectString(fio),
  1632 				QString("linkTo (\"%1\")").arg(fioPreParentSelectString), 
  1633 				fioPreSelectString, 
  1634 				QString ("linkTo (\"%1\")").arg(dstString),
  1635 				QString ("Link floatimage to %1").arg(getObjectName(dst)));
  1636 		}
  1637 	}
  1638 }
  1639 
  1640 
  1641 void VymModel::setFrameType(const FrameObj::FrameType &t)
  1642 {
  1643 	BranchObj *bo=getSelectedBranch();
  1644 	if (bo)
  1645 	{
  1646 		QString s=bo->getFrameTypeName();
  1647 		bo->setFrameType (t);
  1648 		saveState (bo, QString("setFrameType (\"%1\")").arg(s),
  1649 			bo, QString ("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),QString ("set type of frame to %1").arg(s));
  1650 		reposition();
  1651 		bo->updateLink();
  1652 	}
  1653 }
  1654 
  1655 void VymModel::setFrameType(const QString &s)	
  1656 {
  1657 	BranchObj *bo=getSelectedBranch();
  1658 	if (bo)
  1659 	{
  1660 		saveState (bo, QString("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),
  1661 			bo, QString ("setFrameType (\"%1\")").arg(s),QString ("set type of frame to %1").arg(s));
  1662 		bo->setFrameType (s);
  1663 		reposition();
  1664 		bo->updateLink();
  1665 	}
  1666 }
  1667 
  1668 void VymModel::setFramePenColor(const QColor &c)	
  1669 {
  1670 	BranchObj *bo=getSelectedBranch();
  1671 	if (bo)
  1672 	{
  1673 		saveState (bo, QString("setFramePenColor (\"%1\")").arg(bo->getFramePenColor().name() ),
  1674 			bo, QString ("setFramePenColor (\"%1\")").arg(c.name() ),QString ("set pen color of frame to %1").arg(c.name() ));
  1675 		bo->setFramePenColor (c);
  1676 	}	
  1677 }
  1678 
  1679 void VymModel::setFrameBrushColor(const QColor &c)	
  1680 {
  1681 	BranchObj *bo=getSelectedBranch();
  1682 	if (bo)
  1683 	{
  1684 		saveState (bo, QString("setFrameBrushColor (\"%1\")").arg(bo->getFrameBrushColor().name() ),
  1685 			bo, QString ("setFrameBrushColor (\"%1\")").arg(c.name() ),QString ("set brush color of frame to %1").arg(c.name() ));
  1686 		bo->setFrameBrushColor (c);
  1687 	}	
  1688 }
  1689 
  1690 void VymModel::setFramePadding (const int &i)
  1691 {
  1692 	BranchObj *bo=getSelectedBranch();
  1693 	if (bo)
  1694 	{
  1695 		saveState (bo, QString("setFramePadding (\"%1\")").arg(bo->getFramePadding() ),
  1696 			bo, QString ("setFramePadding (\"%1\")").arg(i),QString ("set brush color of frame to %1").arg(i));
  1697 		bo->setFramePadding (i);
  1698 		reposition();
  1699 		bo->updateLink();
  1700 	}	
  1701 }
  1702 
  1703 void VymModel::setFrameBorderWidth(const int &i)
  1704 {
  1705 	BranchObj *bo=getSelectedBranch();
  1706 	if (bo)
  1707 	{
  1708 		saveState (bo, QString("setFrameBorderWidth (\"%1\")").arg(bo->getFrameBorderWidth() ),
  1709 			bo, QString ("setFrameBorderWidth (\"%1\")").arg(i),QString ("set border width of frame to %1").arg(i));
  1710 		bo->setFrameBorderWidth (i);
  1711 		reposition();
  1712 		bo->updateLink();
  1713 	}	
  1714 }
  1715 
  1716 void VymModel::setIncludeImagesVer(bool b)	
  1717 {
  1718 	BranchObj *bo=getSelectedBranch();
  1719 	if (bo)
  1720 	{
  1721 		QString u= b ? "false" : "true";
  1722 		QString r=!b ? "false" : "true";
  1723 		
  1724 		saveState(
  1725 			bo,
  1726 			QString("setIncludeImagesVertically (%1)").arg(u),
  1727 			bo, 
  1728 			QString("setIncludeImagesVertically (%1)").arg(r),
  1729 			QString("Include images vertically in %1").arg(getObjectName(bo))
  1730 		);	
  1731 		bo->setIncludeImagesVer(b);
  1732 		reposition();
  1733 	}	
  1734 }
  1735 
  1736 void VymModel::setIncludeImagesHor(bool b)	
  1737 {
  1738 	BranchObj *bo=getSelectedBranch();
  1739 	if (bo)
  1740 	{
  1741 		QString u= b ? "false" : "true";
  1742 		QString r=!b ? "false" : "true";
  1743 		
  1744 		saveState(
  1745 			bo,
  1746 			QString("setIncludeImagesHorizontally (%1)").arg(u),
  1747 			bo, 
  1748 			QString("setIncludeImagesHorizontally (%1)").arg(r),
  1749 			QString("Include images horizontally in %1").arg(getObjectName(bo))
  1750 		);	
  1751 		bo->setIncludeImagesHor(b);
  1752 		reposition();
  1753 	}	
  1754 }
  1755 
  1756 void VymModel::setHideLinkUnselected (bool b)
  1757 {
  1758 	LinkableMapObj *sel=getSelectedLMO();
  1759 	if (sel &&
  1760 		(selectionType() == TreeItem::Branch || 
  1761 		selectionType() == TreeItem::MapCenter  ||
  1762 		selectionType() == TreeItem::Image ))
  1763 	{
  1764 		QString u= b ? "false" : "true";
  1765 		QString r=!b ? "false" : "true";
  1766 		
  1767 		saveState(
  1768 			sel,
  1769 			QString("setHideLinkUnselected (%1)").arg(u),
  1770 			sel, 
  1771 			QString("setHideLinkUnselected (%1)").arg(r),
  1772 			QString("Hide link of %1 if unselected").arg(getObjectName(sel))
  1773 		);	
  1774 		sel->setHideLinkUnselected(b);
  1775 	}
  1776 }
  1777 
  1778 void VymModel::setHideExport(bool b)
  1779 {
  1780 	BranchObj *bo=getSelectedBranch();
  1781 	if (bo)
  1782 	{
  1783 		bo->setHideInExport (b);
  1784 		QString u= b ? "false" : "true";
  1785 		QString r=!b ? "false" : "true";
  1786 		
  1787 		saveState(
  1788 			bo,
  1789 			QString ("setHideExport (%1)").arg(u),
  1790 			bo,
  1791 			QString ("setHideExport (%1)").arg(r),
  1792 			QString ("Set HideExport flag of %1 to %2").arg(getObjectName(bo)).arg (r)
  1793 		);	
  1794 		updateActions();
  1795 		reposition();
  1796 		selection.update();
  1797 		// FIXME VM needed? scene()->update();
  1798 	}
  1799 }
  1800 
  1801 void VymModel::toggleHideExport()
  1802 {
  1803 	BranchObj *bo=getSelectedBranch();
  1804 	if (bo)
  1805 		setHideExport ( !bo->hideInExport() );
  1806 }
  1807 
  1808 
  1809 void VymModel::copy()
  1810 {
  1811 	LinkableMapObj *sel=getSelectedLMO();
  1812 	if (sel &&
  1813 		(selectionType() == TreeItem::Branch || 
  1814 		selectionType() == TreeItem::MapCenter  ||
  1815 		selectionType() == TreeItem::Image ))
  1816 	{
  1817 		if (redosAvail == 0)
  1818 		{
  1819 			// Copy to history
  1820 			QString s=getSelectString(sel);
  1821 			saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",sel  );
  1822 			curClipboard=curStep;
  1823 		}
  1824 
  1825 		// Copy also to global clipboard, because we are at last step in history
  1826 		QString bakMapName(QString("history-%1").arg(curStep));
  1827 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1828 		copyDir (bakMapDir,clipboardDir );
  1829 
  1830 		clipboardEmpty=false;
  1831 		updateActions();
  1832 	}	    
  1833 }
  1834 
  1835 
  1836 void VymModel::pasteNoSave(const int &n)
  1837 {
  1838 	bool old=blockSaveState;
  1839 	blockSaveState=true;
  1840 	bool zippedOrg=zipped;
  1841 	if (redosAvail > 0 || n!=0)
  1842 	{
  1843 		// Use the "historical" buffer
  1844 		QString bakMapName(QString("history-%1").arg(n));
  1845 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1846 		load (bakMapDir+"/"+clipboardFile,ImportAdd, VymMap);
  1847 	} else
  1848 		// Use the global buffer
  1849 		load (clipboardDir+"/"+clipboardFile,ImportAdd, VymMap);
  1850 	zipped=zippedOrg;
  1851 	blockSaveState=old;
  1852 }
  1853 
  1854 void VymModel::paste()		
  1855 {   
  1856 	BranchObj *sel=getSelectedBranch();
  1857 	if (sel)
  1858 	{
  1859 		saveStateChangingPart(
  1860 			sel,
  1861 			sel,
  1862 			QString ("paste (%1)").arg(curClipboard),
  1863 			QString("Paste to %1").arg( getObjectName(sel))
  1864 		);
  1865 		pasteNoSave(0);
  1866 		reposition();
  1867 	}
  1868 }
  1869 
  1870 void VymModel::cut()
  1871 {
  1872 	LinkableMapObj *sel=getSelectedLMO();
  1873 	if ( sel && (selectionType() == TreeItem::Branch ||
  1874 		selectionType()==TreeItem::MapCenter ||
  1875 		selectionType()==TreeItem::Image))
  1876 	{
  1877 	/* No savestate! savestate is called in cutNoSave
  1878 		saveStateChangingPart(
  1879 			sel->getParObj(),
  1880 			sel,
  1881 			"cut ()",
  1882 			QString("Cut %1").arg(getObjectName(sel ))
  1883 		);
  1884 	*/	
  1885 		copy();
  1886 		deleteSelection();
  1887 		reposition();
  1888 	}
  1889 }
  1890 
  1891 void VymModel::moveBranchUp()
  1892 {
  1893 	BranchObj* bo=getSelectedBranch();
  1894 	BranchObj* par;
  1895 	if (bo)
  1896 	{
  1897 		if (!bo->canMoveBranchUp()) return;
  1898 		par=(BranchObj*)(bo->getParObj());
  1899 		BranchObj *obo=par->moveBranchUp (bo);	// bo will be the one below selection
  1900 		saveState (getSelectString(bo),"moveBranchDown ()",getSelectString(obo),"moveBranchUp ()",QString("Move up %1").arg(getObjectName(bo)));
  1901 		reposition();
  1902 		//FIXME VM needed? scene()->update();
  1903 		selection.update();
  1904 		ensureSelectionVisible();
  1905 	}
  1906 }
  1907 
  1908 void VymModel::moveBranchDown()
  1909 {
  1910 	BranchObj* bo=getSelectedBranch();
  1911 	BranchObj* par;
  1912 	if (bo)
  1913 	{
  1914 		if (!bo->canMoveBranchDown()) return;
  1915 		par=(BranchObj*)(bo->getParObj());
  1916 		BranchObj *obo=par->moveBranchDown(bo);	// bo will be the one above selection
  1917 		saveState(getSelectString(bo),"moveBranchUp ()",getSelectString(obo),"moveBranchDown ()",QString("Move down %1").arg(getObjectName(bo)));
  1918 		reposition();
  1919 		//FIXME VM needed? scene()->update();
  1920 		selection.update();
  1921 		ensureSelectionVisible();
  1922 	}	
  1923 }
  1924 
  1925 void VymModel::sortChildren()
  1926 {
  1927 	BranchObj* bo=getSelectedBranch();
  1928 	if (bo)
  1929 	{
  1930 		if(bo->countBranches()>1)
  1931 		{
  1932 			saveStateChangingPart(bo,bo, "sortChildren ()",QString("Sort children of %1").arg(getObjectName(bo)));
  1933 			bo->sortChildren();
  1934 			reposition();
  1935 			ensureSelectionVisible();
  1936 		}
  1937 	}
  1938 }
  1939 
  1940 void VymModel::createMapCenter()
  1941 {
  1942 	MapCenterObj *mco=addMapCenter (QPointF (0,0) );
  1943 	select (mco);
  1944 }
  1945 
  1946 void VymModel::createBranch()
  1947 {
  1948 	addNewBranchInt (-2);
  1949 	return;
  1950 }
  1951 
  1952 TreeItem* VymModel::createImage()
  1953 {
  1954 	BranchObj *bo=getSelectedBranch();
  1955 	if (bo)
  1956 	{
  1957 		FloatImageObj *newfio=bo->addFloatImage(); // FIXME VM Old model, merge with below
  1958 
  1959 		// Create TreeItem
  1960 		QList<QVariant> cData;
  1961 		cData << "VM:createImage" << "undef"<<"undef";
  1962 		TreeItem *parti=bo->getTreeItem();
  1963 		TreeItem *ti=new TreeItem (cData,parti);
  1964 		ti->setLMO (newfio);
  1965 		ti->setType (TreeItem::Image);
  1966 		parti->appendChild (ti);
  1967 
  1968 		if (newfio)
  1969 		{
  1970 			newfio->setTreeItem (ti);
  1971 			select (newfio); // FIXME VM really needed here?
  1972 			return ti;
  1973 		}
  1974 	}
  1975 	return NULL;
  1976 }
  1977 
  1978 MapCenterObj* VymModel::addMapCenter ()
  1979 {
  1980 	MapCenterObj *mco=addMapCenter (contextPos);
  1981 	cout <<"VM::addMCO ()  mapScene="<<mapScene<<endl;
  1982 	selection.select (mco);
  1983 	updateActions();
  1984 	ensureSelectionVisible();
  1985 	saveState (
  1986 		mco,
  1987 		"delete()",
  1988 		NULL,
  1989 		QString ("addMapCenter (%1,%2)").arg (contextPos.x()).arg(contextPos.y()),
  1990 		QString ("Adding MapCenter to (%1,%2)").arg (contextPos.x()).arg(contextPos.y())
  1991 	);	
  1992 	return mco;	
  1993 }
  1994 
  1995 MapCenterObj* VymModel::addMapCenter(QPointF absPos)
  1996 {
  1997 	MapCenterObj *mapCenter = new MapCenterObj(mapScene,this);
  1998 	mapCenter->setMapEditor(mapEditor);		//FIXME VM needed to get defLinkStyle, mapLinkColorHint ... for later added objects
  1999 	mapCenter->move (absPos);
  2000     mapCenter->setVisibility (true);
  2001 	mapCenter->setHeading (QApplication::translate("Heading of mapcenter in new map", "New map"));
  2002 	mapCenters.append(mapCenter);
  2003 
  2004 	// Create TreeItem
  2005 	QList<QVariant> cData;
  2006 	cData << "VM:addMapCenter" << "undef"<<"undef";
  2007 	TreeItem *ti=new TreeItem (cData,rootItem);
  2008 	ti->setLMO (mapCenter);
  2009 	ti->setType (TreeItem::MapCenter);
  2010 	mapCenter->setTreeItem (ti);
  2011 	rootItem->appendChild (ti);
  2012 
  2013 	return mapCenter;
  2014 }
  2015 
  2016 MapCenterObj* VymModel::removeMapCenter(MapCenterObj* mco)
  2017 {
  2018 	int i=mapCenters.indexOf (mco);
  2019 	if (i>=0)
  2020 	{
  2021 		mapCenters.removeAt (i);
  2022 		delete (mco);
  2023 		if (i>0) return mapCenters.at(i-1);	// Return previous MCO
  2024 	}
  2025 	return NULL;
  2026 }
  2027 
  2028 MapCenterObj* VymModel::getLastMapCenter()
  2029 {
  2030 	if (mapCenters.size()>0)
  2031 		return mapCenters.last();
  2032 	else
  2033 		return NULL;
  2034 
  2035 }
  2036 
  2037 
  2038 BranchObj* VymModel::addNewBranchInt(int num)
  2039 {
  2040 	// Depending on pos:
  2041 	// -3		insert in children of parent  above selection 
  2042 	// -2		add branch to selection 
  2043 	// -1		insert in children of parent below selection 
  2044 	// 0..n		insert in children of parent at pos
  2045 	BranchObj *newbo=NULL;
  2046 	BranchObj *bo=getSelectedBranch();
  2047 	if (bo)
  2048 	{
  2049 		if (num==-2)
  2050 		{
  2051 			// save scroll state. If scrolled, automatically select
  2052 			// new branch in order to tmp unscroll parent...
  2053 			newbo=bo->addBranch();
  2054 
  2055 			// Create TreeItem
  2056 			QList<QVariant> cData;
  2057 			cData << "VM:createBranch" << "undef"<<"undef";
  2058 			TreeItem *parti=bo->getTreeItem();
  2059 			TreeItem *ti=new TreeItem (cData,parti);
  2060 			ti->setLMO (newbo);
  2061 			ti->setType (TreeItem::Branch);
  2062 			parti->appendChild (ti);
  2063 
  2064 			if (newbo)
  2065 			{
  2066 				newbo->setTreeItem (ti);
  2067 				select (newbo); // FIXME VM really needed here?
  2068 			}
  2069 			
  2070 		}else if (num==-1)
  2071 		{
  2072 			num=bo->getNum()+1;
  2073 			bo=(BranchObj*)bo->getParObj();
  2074 			if (bo) newbo=bo->insertBranch(num);
  2075 		}else if (num==-3)
  2076 		{
  2077 			num=bo->getNum();
  2078 			bo=(BranchObj*)bo->getParObj();
  2079 			if (bo) newbo=bo->insertBranch(num);
  2080 		}
  2081 	}	
  2082 	return newbo;
  2083 }	
  2084 
  2085 BranchObj* VymModel::addNewBranch(int pos)
  2086 {
  2087 	// Different meaning than num in addNewBranchInt!
  2088 	// -1	add above
  2089 	//  0	add as child
  2090 	// +1	add below
  2091 	BranchObj *bo = getSelectedBranch();
  2092 	BranchObj *newbo=NULL;
  2093 
  2094 	if (bo)
  2095 	{
  2096 		// FIXME VM  do we still need this in model? setCursor (Qt::ArrowCursor);
  2097 
  2098 		newbo=addNewBranchInt (pos-2);
  2099 
  2100 		if (newbo)
  2101 		{
  2102 			saveState(
  2103 				newbo,		
  2104 				"delete ()",
  2105 				bo,
  2106 				QString ("addBranch (%1)").arg(pos),
  2107 				QString ("Add new branch to %1").arg(getObjectName(bo)));	
  2108 
  2109 			reposition();
  2110 			// selection.update(); FIXME
  2111 			latestSelectionString=getSelectString(newbo);
  2112 			// In Network mode, the client needs to know where the new branch is,
  2113 			// so we have to pass on this information via saveState.
  2114 			// TODO: Get rid of this positioning workaround
  2115 			QString ps=qpointfToString (newbo->getAbsPos());
  2116 			sendData ("selectLatestAdded ()");
  2117 			sendData (QString("move %1").arg(ps));
  2118 			sendSelection();
  2119 		}
  2120 	}	
  2121 	return newbo;
  2122 }
  2123 
  2124 
  2125 BranchObj* VymModel::addNewBranchBefore()
  2126 {
  2127 	BranchObj *newbo=NULL;
  2128 	BranchObj *bo = getSelectedBranch();
  2129 	if (bo && selectionType()==TreeItem::Branch)
  2130 		 // We accept no MapCenterObj here, so we _have_ a parent
  2131 	{
  2132 		QPointF p=bo->getRelPos();
  2133 
  2134 
  2135 		BranchObj *parbo=(BranchObj*)(bo->getParObj());
  2136 
  2137 		// add below selection
  2138 		newbo=parbo->insertBranch(bo->getNum()+1);
  2139 		if (newbo)
  2140 		{
  2141 			newbo->move2RelPos (p);
  2142 
  2143 			// Move selection to new branch
  2144 			bo->linkTo (newbo,-1);
  2145 
  2146 			saveState (newbo, "deleteKeepChildren ()", newbo, "addBranchBefore ()", 
  2147 				QString ("Add branch before %1").arg(getObjectName(bo)));
  2148 
  2149 			reposition();
  2150 			// selection.update(); FIXME 
  2151 		}
  2152 	}	
  2153 	latestSelectionString=selection.getSelectString();
  2154 	return newbo;
  2155 }
  2156 
  2157 void VymModel::deleteSelection()
  2158 {
  2159 	BranchObj *bo = getSelectedBranch();
  2160 	
  2161 	if (bo && selectionType()==TreeItem::MapCenter)
  2162 	{
  2163 	//	BranchObj* par=(BranchObj*)(bo->getParObj());
  2164 		selection.unselect();
  2165 	/* FIXME VM Note:  does saveStateRemovingPart work for MCO? (No parent!)
  2166 		saveStateRemovingPart (bo, QString ("Delete %1").arg(getObjectName(bo)));
  2167 		*/
  2168 		bo=removeMapCenter ((MapCenterObj*)bo);
  2169 		if (bo) 
  2170 		{
  2171 			selection.select (bo);
  2172 			ensureSelectionVisible();
  2173 			selection.update();
  2174 		}	
  2175 		reposition();
  2176 		return;
  2177 	}
  2178 	if (bo && selectionType()==TreeItem::Branch)
  2179 	{
  2180 		QModelIndex ix=getSelectedIndex();
  2181 
  2182 		BranchObj* par=(BranchObj*)bo->getParObj();
  2183 		unselect();
  2184 		saveStateRemovingPart (bo, QString ("Delete %1").arg(getObjectName(bo)));
  2185 		par->removeBranch(bo);
  2186 		select (par);
  2187 		ensureSelectionVisible();
  2188 		reposition();
  2189 		selection.update();
  2190 		return;
  2191 	}
  2192 	FloatImageObj *fio=selection.getFloatImage();
  2193 	if (fio)
  2194 	{
  2195 		BranchObj* par=(BranchObj*)fio->getParObj();
  2196 		saveStateChangingPart(
  2197 			par, 
  2198 			fio,
  2199 			"delete ()",
  2200 			QString("Delete %1").arg(getObjectName(fio))
  2201 		);
  2202 		unselect();
  2203 		par->removeFloatImage(fio);
  2204 		select (par);
  2205 		reposition();
  2206 		selection.update();
  2207 		ensureSelectionVisible();
  2208 		return;
  2209 	}
  2210 }
  2211 
  2212 void VymModel::deleteKeepChildren()
  2213 {
  2214 	BranchObj *bo=getSelectedBranch();
  2215 	BranchObj *par;
  2216 	if (bo)
  2217 	{
  2218 		par=(BranchObj*)(bo->getParObj());
  2219 
  2220 		// Don't use this on mapcenter
  2221 		if (!par) return;
  2222 
  2223 		// Check if we have childs at all to keep
  2224 		if (bo->countBranches()==0) 
  2225 		{
  2226 			deleteSelection();
  2227 			return;
  2228 		}
  2229 
  2230 		QPointF p=bo->getRelPos();
  2231 		saveStateChangingPart(
  2232 			bo->getParObj(),
  2233 			bo,
  2234 			"deleteKeepChildren ()",
  2235 			QString("Remove %1 and keep its children").arg(getObjectName(bo))
  2236 		);
  2237 
  2238 		QString sel=getSelectString(bo);
  2239 		unselect();
  2240 		par->removeBranchHere(bo);
  2241 		reposition();
  2242 		select (sel);
  2243 		getSelectedBranch()->move2RelPos (p);
  2244 		reposition();
  2245 	}	
  2246 }
  2247 
  2248 void VymModel::deleteChildren()
  2249 {
  2250 	BranchObj *bo=getSelectedBranch();
  2251 	if (bo)
  2252 	{		
  2253 		saveStateChangingPart(
  2254 			bo, 
  2255 			bo,
  2256 			"deleteChildren ()",
  2257 			QString( "Remove children of branch %1").arg(getObjectName(bo))
  2258 		);
  2259 		bo->removeChildren();
  2260 		reposition();
  2261 	}	
  2262 }
  2263 
  2264 
  2265 bool VymModel::scrollBranch(BranchObj *bo)
  2266 {
  2267 	if (bo)
  2268 	{
  2269 		if (bo->isScrolled()) return false;
  2270 		if (bo->countBranches()==0) return false;
  2271 		if (bo->getDepth()==0) return false;
  2272 		QString u,r;
  2273 		r="scroll";
  2274 		u="unscroll";
  2275 		saveState(
  2276 			bo,
  2277 			QString ("%1 ()").arg(u),
  2278 			bo,
  2279 			QString ("%1 ()").arg(r),
  2280 			QString ("%1 %2").arg(r).arg(getObjectName(bo))
  2281 		);
  2282 		bo->toggleScroll();
  2283 		selection.update();
  2284 		// FIXME VM needed? scene()->update();
  2285 		return true;
  2286 	}	
  2287 	return false;
  2288 }
  2289 
  2290 bool VymModel::unscrollBranch(BranchObj *bo)
  2291 {
  2292 	if (bo)
  2293 	{
  2294 		if (!bo->isScrolled()) return false;
  2295 		if (bo->countBranches()==0) return false;
  2296 		if (bo->getDepth()==0) return false;
  2297 		QString u,r;
  2298 		u="scroll";
  2299 		r="unscroll";
  2300 		saveState(
  2301 			bo,
  2302 			QString ("%1 ()").arg(u),
  2303 			bo,
  2304 			QString ("%1 ()").arg(r),
  2305 			QString ("%1 %2").arg(r).arg(getObjectName(bo))
  2306 		);
  2307 		bo->toggleScroll();
  2308 		selection.update();
  2309 		// FIXME VM needed? scene()->update();
  2310 		return true;
  2311 	}	
  2312 	return false;
  2313 }
  2314 
  2315 void VymModel::toggleScroll()
  2316 {
  2317 	BranchObj *bo=getSelectedBranch();
  2318 	if (selectionType()==TreeItem::Branch )
  2319 	{
  2320 		if (bo->isScrolled())
  2321 			unscrollBranch (bo);
  2322 		else
  2323 			scrollBranch (bo);
  2324 	}
  2325 }
  2326 
  2327 void VymModel::unscrollChildren() 
  2328 {
  2329 	BranchObj *bo=getSelectedBranch();
  2330 	if (bo)
  2331 	{
  2332 		bo->first();
  2333 		while (bo) 
  2334 		{
  2335 			if (bo->isScrolled()) unscrollBranch (bo);
  2336 			bo=bo->next();
  2337 		}
  2338 	}	
  2339 }
  2340 void VymModel::addFloatImage (const QPixmap &img) 
  2341 {
  2342 	BranchObj *bo=getSelectedBranch();
  2343 	if (bo)
  2344   {
  2345 	FloatImageObj *fio=bo->addFloatImage();
  2346     fio->load(img);
  2347     fio->setOriginalFilename("No original filename (image added by dropevent)");	
  2348 	QString s=getSelectString(bo);
  2349 	saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",fio  );
  2350 	saveState (fio,"delete ()", bo,QString("paste(%1)").arg(curStep),"Pasting dropped image");
  2351     reposition();
  2352     // FIXME VM needed? scene()->update();
  2353   }
  2354 }
  2355 
  2356 
  2357 void VymModel::colorBranch (QColor c)
  2358 {
  2359 	BranchObj *bo=getSelectedBranch();
  2360 	if (bo)
  2361 	{
  2362 		saveState(
  2363 			bo, 
  2364 			QString ("colorBranch (\"%1\")").arg(bo->getColor().name()),
  2365 			bo,
  2366 			QString ("colorBranch (\"%1\")").arg(c.name()),
  2367 			QString("Set color of %1 to %2").arg(getObjectName(bo)).arg(c.name())
  2368 		);	
  2369 		bo->setColor(c); // color branch
  2370 	}
  2371 }
  2372 
  2373 void VymModel::colorSubtree (QColor c)
  2374 {
  2375 	BranchObj *bo=getSelectedBranch();
  2376 	if (bo) 
  2377 	{
  2378 		saveStateChangingPart(
  2379 			bo, 
  2380 			bo,
  2381 			QString ("colorSubtree (\"%1\")").arg(c.name()),
  2382 			QString ("Set color of %1 and children to %2").arg(getObjectName(bo)).arg(c.name())
  2383 		);	
  2384 		bo->setColorSubtree (c); // color links, color children
  2385 	}
  2386 }
  2387 
  2388 QColor VymModel::getCurrentHeadingColor()
  2389 {
  2390 	BranchObj *bo=getSelectedBranch();
  2391 	if (bo) return bo->getColor(); 
  2392 	
  2393 	QMessageBox::warning(0,"Warning","Can't get color of heading,\nthere's no branch selected");
  2394 	return Qt::black;
  2395 }
  2396 
  2397 
  2398 
  2399 void VymModel::editURL()
  2400 {
  2401 	BranchObj *bo=getSelectedBranch();
  2402 	if (bo)
  2403 	{		
  2404 		bool ok;
  2405 		QString text = QInputDialog::getText(
  2406 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2407 				bo->getURL(), &ok, NULL);
  2408 		if ( ok) 
  2409 			// user entered something and pressed OK
  2410 			setURL(text);
  2411 	}
  2412 }
  2413 
  2414 void VymModel::editLocalURL()
  2415 {
  2416 	BranchObj *bo=getSelectedBranch();
  2417 	if (bo)
  2418 	{		
  2419 		QStringList filters;
  2420 		filters <<"All files (*)";
  2421 		filters << tr("Text","Filedialog") + " (*.txt)";
  2422 		filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
  2423 		filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
  2424 		filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
  2425 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Set URL to a local file"));
  2426 		fd->setFilters (filters);
  2427 		fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
  2428 		fd->setDirectory (lastFileDir);
  2429 		if (! bo->getVymLink().isEmpty() )
  2430 			fd->selectFile( bo->getURL() );
  2431 		fd->show();
  2432 
  2433 		if ( fd->exec() == QDialog::Accepted )
  2434 		{
  2435 			lastFileDir=QDir (fd->directory().path());
  2436 			setURL (fd->selectedFile() );
  2437 		}
  2438 	}
  2439 }
  2440 
  2441 
  2442 void VymModel::editHeading2URL()
  2443 {
  2444 	BranchObj *bo=getSelectedBranch();
  2445 	if (bo)
  2446 		setURL (bo->getHeading());
  2447 }	
  2448 
  2449 void VymModel::editBugzilla2URL()
  2450 {
  2451 	BranchObj *bo=getSelectedBranch();
  2452 	if (bo)
  2453 	{		
  2454 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
  2455 		setURL (url);
  2456 	}
  2457 }	
  2458 
  2459 void VymModel::editFATE2URL()
  2460 {
  2461 	BranchObj *bo=getSelectedBranch();
  2462 	if (bo)
  2463 	{		
  2464 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
  2465 		saveState(
  2466 			bo,
  2467 			"setURL (\""+bo->getURL()+"\")",
  2468 			bo,
  2469 			"setURL (\""+url+"\")",
  2470 			QString("Use heading of %1 as link to FATE").arg(getObjectName(bo))
  2471 		);	
  2472 		bo->setURL (url);
  2473 		updateActions();
  2474 	}
  2475 }	
  2476 
  2477 void VymModel::editVymLink()
  2478 {
  2479 	BranchObj *bo=getSelectedBranch();
  2480 	if (bo)
  2481 	{		
  2482 		QStringList filters;
  2483 		filters <<"VYM map (*.vym)";
  2484 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Link to another map"));
  2485 		fd->setFilters (filters);
  2486 		fd->setCaption(vymName+" - " +tr("Link to another map"));
  2487 		fd->setDirectory (lastFileDir);
  2488 		if (! bo->getVymLink().isEmpty() )
  2489 			fd->selectFile( bo->getVymLink() );
  2490 		fd->show();
  2491 
  2492 		QString fn;
  2493 		if ( fd->exec() == QDialog::Accepted )
  2494 		{
  2495 			lastFileDir=QDir (fd->directory().path());
  2496 			saveState(
  2497 				bo,
  2498 				"setVymLink (\""+bo->getVymLink()+"\")",
  2499 				bo,
  2500 				"setVymLink (\""+fd->selectedFile()+"\")",
  2501 				QString("Set vymlink of %1 to %2").arg(getObjectName(bo)).arg(fd->selectedFile())
  2502 			);	
  2503 			setVymLink (fd->selectedFile() );	// FIXME ok?
  2504 		}
  2505 	}
  2506 }
  2507 
  2508 void VymModel::setVymLink (const QString &s)
  2509 {
  2510 	// Internal function, no saveState needed
  2511 	BranchObj *bo=getSelectedBranch();
  2512 	if (bo)
  2513 	{
  2514 		bo->setVymLink(s);
  2515 		reposition();
  2516 		updateActions();
  2517 		selection.update();
  2518 		ensureSelectionVisible();
  2519 	}
  2520 }
  2521 
  2522 void VymModel::deleteVymLink()
  2523 {
  2524 	BranchObj *bo=getSelectedBranch();
  2525 	if (bo)
  2526 	{		
  2527 		saveState(
  2528 			bo,
  2529 			"setVymLink (\""+bo->getVymLink()+"\")",
  2530 			bo,
  2531 			"setVymLink (\"\")",
  2532 			QString("Unset vymlink of %1").arg(getObjectName(bo))
  2533 		);	
  2534 		bo->setVymLink ("" );
  2535 		updateActions();
  2536 		reposition();
  2537 		// FIXME VM needed? scene()->update();
  2538 	}
  2539 }
  2540 
  2541 QString VymModel::getVymLink()
  2542 {
  2543 	BranchObj *bo=getSelectedBranch();
  2544 	if (bo)
  2545 		return bo->getVymLink();
  2546 	else	
  2547 		return "";
  2548 	
  2549 }
  2550 
  2551 QStringList VymModel::getVymLinks()
  2552 {
  2553 	QStringList links;
  2554 	BranchObj *bo=getSelectedBranch();
  2555 	if (bo)
  2556 	{		
  2557 		bo=bo->first();	
  2558 		while (bo) 
  2559 		{
  2560 			if (!bo->getVymLink().isEmpty()) links.append( bo->getVymLink());
  2561 			bo=bo->next();
  2562 		}	
  2563 	}	
  2564 	return links;
  2565 }
  2566 
  2567 
  2568 void VymModel::followXLink(int i)
  2569 {
  2570 	BranchObj *bo=getSelectedBranch();
  2571 	if (bo)
  2572 	{
  2573 		bo=bo->XLinkTargetAt(i);
  2574 		if (bo) 
  2575 		{
  2576 			selection.select(bo);
  2577 			ensureSelectionVisible();
  2578 		}
  2579 	}
  2580 }
  2581 
  2582 void VymModel::editXLink(int i)	// FIXME VM missing saveState
  2583 {
  2584 	BranchObj *bo=getSelectedBranch();
  2585 	if (bo)
  2586 	{
  2587 		XLinkObj *xlo=bo->XLinkAt(i);
  2588 		if (xlo) 
  2589 		{
  2590 			EditXLinkDialog dia;
  2591 			dia.setXLink (xlo);
  2592 			dia.setSelection(bo);
  2593 			if (dia.exec() == QDialog::Accepted)
  2594 			{
  2595 				if (dia.useSettingsGlobal() )
  2596 				{
  2597 					setMapDefXLinkColor (xlo->getColor() );
  2598 					setMapDefXLinkWidth (xlo->getWidth() );
  2599 				}
  2600 				if (dia.deleteXLink())
  2601 					bo->deleteXLinkAt(i);
  2602 			}
  2603 		}	
  2604 	}
  2605 }
  2606 
  2607 
  2608 
  2609 
  2610 
  2611 //////////////////////////////////////////////
  2612 // Scripting
  2613 //////////////////////////////////////////////
  2614 
  2615 void VymModel::parseAtom(const QString &atom)
  2616 {
  2617 	BranchObj *selb=getSelectedBranch();
  2618 	QString s,t;
  2619 	double x,y;
  2620 	int n;
  2621 	bool b,ok;
  2622 
  2623 	// Split string s into command and parameters
  2624 	parser.parseAtom (atom);
  2625 	QString com=parser.getCommand();
  2626 	
  2627 	// External commands
  2628 	/////////////////////////////////////////////////////////////////////
  2629 	if (com=="addBranch")
  2630 	{
  2631 		if (selection.isEmpty())
  2632 		{
  2633 			parser.setError (Aborted,"Nothing selected");
  2634 		} else if (! selb )
  2635 		{				  
  2636 			parser.setError (Aborted,"Type of selection is not a branch");
  2637 		} else 
  2638 		{	
  2639 			QList <int> pl;
  2640 			pl << 0 <<1;
  2641 			if (parser.checkParCount(pl))
  2642 			{
  2643 				if (parser.parCount()==0)
  2644 					addNewBranch (0);
  2645 				else
  2646 				{
  2647 					n=parser.parInt (ok,0);
  2648 					if (ok ) addNewBranch (n);
  2649 				}
  2650 			}
  2651 		}
  2652 	/////////////////////////////////////////////////////////////////////
  2653 	} else if (com=="addBranchBefore")
  2654 	{
  2655 		if (selection.isEmpty())
  2656 		{
  2657 			parser.setError (Aborted,"Nothing selected");
  2658 		} else if (! selb )
  2659 		{				  
  2660 			parser.setError (Aborted,"Type of selection is not a branch");
  2661 		} else 
  2662 		{	
  2663 			if (parser.parCount()==0)
  2664 			{
  2665 				addNewBranchBefore ();
  2666 			}	
  2667 		}
  2668 	/////////////////////////////////////////////////////////////////////
  2669 	} else if (com==QString("addMapCenter"))
  2670 	{
  2671 		if (parser.checkParCount(2))
  2672 		{
  2673 			x=parser.parDouble (ok,0);
  2674 			if (ok)
  2675 			{
  2676 				y=parser.parDouble (ok,1);
  2677 				if (ok) addMapCenter (QPointF(x,y));
  2678 			}
  2679 		}	
  2680 	/////////////////////////////////////////////////////////////////////
  2681 	} else if (com==QString("addMapReplace"))
  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 if (parser.checkParCount(1))
  2690 		{
  2691 			//s=parser.parString (ok,0);	// selection
  2692 			t=parser.parString (ok,0);	// path to map
  2693 			if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2694 			addMapReplaceInt(getSelectString(selb),t);	
  2695 		}
  2696 	/////////////////////////////////////////////////////////////////////
  2697 	} else if (com==QString("addMapInsert"))
  2698 	{
  2699 		if (selection.isEmpty())
  2700 		{
  2701 			parser.setError (Aborted,"Nothing selected");
  2702 		} else if (! selb )
  2703 		{				  
  2704 			parser.setError (Aborted,"Type of selection is not a branch");
  2705 		} else 
  2706 		{	
  2707 			if (parser.checkParCount(2))
  2708 			{
  2709 				t=parser.parString (ok,0);	// path to map
  2710 				n=parser.parInt(ok,1);		// position
  2711 				if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2712 				addMapInsertInt(t,n);	
  2713 			}
  2714 		}
  2715 	/////////////////////////////////////////////////////////////////////
  2716 	} else if (com=="clearFlags")
  2717 	{
  2718 		if (selection.isEmpty() )
  2719 		{
  2720 			parser.setError (Aborted,"Nothing selected");
  2721 		} else if (! selb )
  2722 		{				  
  2723 			parser.setError (Aborted,"Type of selection is not a branch");
  2724 		} else if (parser.checkParCount(0))
  2725 		{
  2726 			selb->clearStandardFlags();	
  2727 			selb->updateFlagsToolbar();
  2728 		}
  2729 	/////////////////////////////////////////////////////////////////////
  2730 	} else if (com=="colorBranch")
  2731 	{
  2732 		if (selection.isEmpty())
  2733 		{
  2734 			parser.setError (Aborted,"Nothing selected");
  2735 		} else if (! selb )
  2736 		{				  
  2737 			parser.setError (Aborted,"Type of selection is not a branch");
  2738 		} else if (parser.checkParCount(1))
  2739 		{	
  2740 			QColor c=parser.parColor (ok,0);
  2741 			if (ok) colorBranch (c);
  2742 		}	
  2743 	/////////////////////////////////////////////////////////////////////
  2744 	} else if (com=="colorSubtree")
  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(1))
  2753 		{	
  2754 			QColor c=parser.parColor (ok,0);
  2755 			if (ok) colorSubtree (c);
  2756 		}	
  2757 	/////////////////////////////////////////////////////////////////////
  2758 	} else if (com=="copy")
  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(0))
  2767 		{	
  2768 			//FIXME missing action for copy
  2769 		}	
  2770 	/////////////////////////////////////////////////////////////////////
  2771 	} else if (com=="cut")
  2772 	{
  2773 		if (selection.isEmpty())
  2774 		{
  2775 			parser.setError (Aborted,"Nothing selected");
  2776 		} else if ( selectionType()!=TreeItem::Branch  && 
  2777 					selectionType()!=TreeItem::MapCenter  &&
  2778 					selectionType()!=TreeItem::Image )
  2779 		{				  
  2780 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  2781 		} else if (parser.checkParCount(0))
  2782 		{	
  2783 			cut();
  2784 		}	
  2785 	/////////////////////////////////////////////////////////////////////
  2786 	} else if (com=="delete")
  2787 	{
  2788 		if (selection.isEmpty())
  2789 		{
  2790 			parser.setError (Aborted,"Nothing selected");
  2791 		} 
  2792 		/*else if (selectionType() != TreeItem::Branch && selectionType() != TreeItem::Image )
  2793 		{
  2794 			parser.setError (Aborted,"Type of selection is wrong.");
  2795 		} 
  2796 		*/
  2797 		else if (parser.checkParCount(0))
  2798 		{	
  2799 			deleteSelection();
  2800 		}	
  2801 	/////////////////////////////////////////////////////////////////////
  2802 	} else if (com=="deleteKeepChildren")
  2803 	{
  2804 		if (selection.isEmpty())
  2805 		{
  2806 			parser.setError (Aborted,"Nothing selected");
  2807 		} else if (! selb )
  2808 		{
  2809 			parser.setError (Aborted,"Type of selection is not a branch");
  2810 		} else if (parser.checkParCount(0))
  2811 		{	
  2812 			deleteKeepChildren();
  2813 		}	
  2814 	/////////////////////////////////////////////////////////////////////
  2815 	} else if (com=="deleteChildren")
  2816 	{
  2817 		if (selection.isEmpty())
  2818 		{
  2819 			parser.setError (Aborted,"Nothing selected");
  2820 		} else if (! selb)
  2821 		{
  2822 			parser.setError (Aborted,"Type of selection is not a branch");
  2823 		} else if (parser.checkParCount(0))
  2824 		{	
  2825 			deleteChildren();
  2826 		}	
  2827 	/////////////////////////////////////////////////////////////////////
  2828 	} else if (com=="exportASCII")
  2829 	{
  2830 		QString fname="";
  2831 		ok=true;
  2832 		if (parser.parCount()>=1)
  2833 			// Hey, we even have a filename
  2834 			fname=parser.parString(ok,0); 
  2835 		if (!ok)
  2836 		{
  2837 			parser.setError (Aborted,"Could not read filename");
  2838 		} else
  2839 		{
  2840 				exportASCII (fname,false);
  2841 		}
  2842 	/////////////////////////////////////////////////////////////////////
  2843 	} else if (com=="exportImage")
  2844 	{
  2845 		QString fname="";
  2846 		ok=true;
  2847 		if (parser.parCount()>=2)
  2848 			// Hey, we even have a filename
  2849 			fname=parser.parString(ok,0); 
  2850 		if (!ok)
  2851 		{
  2852 			parser.setError (Aborted,"Could not read filename");
  2853 		} else
  2854 		{
  2855 			QString format="PNG";
  2856 			if (parser.parCount()>=2)
  2857 			{
  2858 				format=parser.parString(ok,1);
  2859 			}
  2860 			exportImage (fname,false,format);
  2861 		}
  2862 	/////////////////////////////////////////////////////////////////////
  2863 	} else if (com=="exportXHTML")
  2864 	{
  2865 		QString fname="";
  2866 		ok=true;
  2867 		if (parser.parCount()>=2)
  2868 			// Hey, we even have a filename
  2869 			fname=parser.parString(ok,1); 
  2870 		if (!ok)
  2871 		{
  2872 			parser.setError (Aborted,"Could not read filename");
  2873 		} else
  2874 		{
  2875 			exportXHTML (fname,false);
  2876 		}
  2877 	/////////////////////////////////////////////////////////////////////
  2878 	} else if (com=="exportXML")
  2879 	{
  2880 		QString fname="";
  2881 		ok=true;
  2882 		if (parser.parCount()>=2)
  2883 			// Hey, we even have a filename
  2884 			fname=parser.parString(ok,1); 
  2885 		if (!ok)
  2886 		{
  2887 			parser.setError (Aborted,"Could not read filename");
  2888 		} else
  2889 		{
  2890 			exportXML (fname,false);
  2891 		}
  2892 	/////////////////////////////////////////////////////////////////////
  2893 	} else if (com=="importDir")
  2894 	{
  2895 		if (selection.isEmpty())
  2896 		{
  2897 			parser.setError (Aborted,"Nothing selected");
  2898 		} else if (! selb )
  2899 		{				  
  2900 			parser.setError (Aborted,"Type of selection is not a branch");
  2901 		} else if (parser.checkParCount(1))
  2902 		{
  2903 			s=parser.parString(ok,0);
  2904 			if (ok) importDirInt(s);
  2905 		}	
  2906 	/////////////////////////////////////////////////////////////////////
  2907 	} else if (com=="linkTo")
  2908 	{
  2909 		if (selection.isEmpty())
  2910 		{
  2911 			parser.setError (Aborted,"Nothing selected");
  2912 		} else if ( selb)
  2913 		{
  2914 			if (parser.checkParCount(4))
  2915 			{
  2916 				// 0	selectstring of parent
  2917 				// 1	num in parent (for branches)
  2918 				// 2,3	x,y of mainbranch or mapcenter
  2919 				s=parser.parString(ok,0);
  2920 				LinkableMapObj *dst=findObjBySelect (s);
  2921 				if (dst)
  2922 				{	
  2923 					if (typeid(*dst) == typeid(BranchObj) ) 
  2924 					{
  2925 						// Get number in parent
  2926 						n=parser.parInt (ok,1);
  2927 						if (ok)
  2928 						{
  2929 							selb->linkTo ((BranchObj*)(dst),n);
  2930 							selection.update();
  2931 						}	
  2932 					} else if (typeid(*dst) == typeid(MapCenterObj) ) 
  2933 					{
  2934 						selb->linkTo ((BranchObj*)(dst),-1);
  2935 						// Get coordinates of mainbranch
  2936 						x=parser.parDouble(ok,2);
  2937 						if (ok)
  2938 						{
  2939 							y=parser.parDouble(ok,3);
  2940 							if (ok) 
  2941 							{
  2942 								selb->move (x,y);
  2943 								selection.update();
  2944 							}
  2945 						}
  2946 					}	
  2947 				}	
  2948 			}	
  2949 		} else if ( selectionType() == TreeItem::Image) 
  2950 		{
  2951 			if (parser.checkParCount(1))
  2952 			{
  2953 				// 0	selectstring of parent
  2954 				s=parser.parString(ok,0);
  2955 				LinkableMapObj *dst=findObjBySelect (s);
  2956 				if (dst)
  2957 				{	
  2958 					if (typeid(*dst) == typeid(BranchObj) ||
  2959 						typeid(*dst) == typeid(MapCenterObj)) 
  2960 						linkFloatImageTo (getSelectString(dst));
  2961 				} else	
  2962 					parser.setError (Aborted,"Destination is not a branch");
  2963 			}		
  2964 		} else
  2965 			parser.setError (Aborted,"Type of selection is not a floatimage or branch");
  2966 	/////////////////////////////////////////////////////////////////////
  2967 	} else if (com=="loadImage")
  2968 	{
  2969 		if (selection.isEmpty())
  2970 		{
  2971 			parser.setError (Aborted,"Nothing selected");
  2972 		} else if (! selb )
  2973 		{				  
  2974 			parser.setError (Aborted,"Type of selection is not a branch");
  2975 		} else if (parser.checkParCount(1))
  2976 		{
  2977 			s=parser.parString(ok,0);
  2978 			if (ok) loadFloatImageInt (s);
  2979 		}	
  2980 	/////////////////////////////////////////////////////////////////////
  2981 	} else if (com=="moveBranchUp")
  2982 	{
  2983 		if (selection.isEmpty() )
  2984 		{
  2985 			parser.setError (Aborted,"Nothing selected");
  2986 		} else if (! selb )
  2987 		{				  
  2988 			parser.setError (Aborted,"Type of selection is not a branch");
  2989 		} else if (parser.checkParCount(0))
  2990 		{
  2991 			moveBranchUp();
  2992 		}	
  2993 	/////////////////////////////////////////////////////////////////////
  2994 	} else if (com=="moveBranchDown")
  2995 	{
  2996 		if (selection.isEmpty() )
  2997 		{
  2998 			parser.setError (Aborted,"Nothing selected");
  2999 		} else if (! selb )
  3000 		{				  
  3001 			parser.setError (Aborted,"Type of selection is not a branch");
  3002 		} else if (parser.checkParCount(0))
  3003 		{
  3004 			moveBranchDown();
  3005 		}	
  3006 	/////////////////////////////////////////////////////////////////////
  3007 	} else if (com=="move")
  3008 	{
  3009 		if (selection.isEmpty() )
  3010 		{
  3011 			parser.setError (Aborted,"Nothing selected");
  3012 		} else if ( selectionType()!=TreeItem::Branch  && 
  3013 					selectionType()!=TreeItem::MapCenter  &&
  3014 					selectionType()!=TreeItem::Image )
  3015 		{				  
  3016 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3017 		} else if (parser.checkParCount(2))
  3018 		{	
  3019 			x=parser.parDouble (ok,0);
  3020 			if (ok)
  3021 			{
  3022 				y=parser.parDouble (ok,1);
  3023 				if (ok) move (x,y);
  3024 			}
  3025 		}	
  3026 	/////////////////////////////////////////////////////////////////////
  3027 	} else if (com=="moveRel")
  3028 	{
  3029 		if (selection.isEmpty() )
  3030 		{
  3031 			parser.setError (Aborted,"Nothing selected");
  3032 		} else if ( selectionType()!=TreeItem::Branch  && 
  3033 					selectionType()!=TreeItem::MapCenter  &&
  3034 					selectionType()!=TreeItem::Image )
  3035 		{				  
  3036 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3037 		} else if (parser.checkParCount(2))
  3038 		{	
  3039 			x=parser.parDouble (ok,0);
  3040 			if (ok)
  3041 			{
  3042 				y=parser.parDouble (ok,1);
  3043 				if (ok) moveRel (x,y);
  3044 			}
  3045 		}	
  3046 	/////////////////////////////////////////////////////////////////////
  3047 	} else if (com=="nop")
  3048 	{
  3049 	/////////////////////////////////////////////////////////////////////
  3050 	} else if (com=="paste")
  3051 	{
  3052 		if (selection.isEmpty() )
  3053 		{
  3054 			parser.setError (Aborted,"Nothing selected");
  3055 		} else if (! selb )
  3056 		{				  
  3057 			parser.setError (Aborted,"Type of selection is not a branch");
  3058 		} else if (parser.checkParCount(1))
  3059 		{	
  3060 			n=parser.parInt (ok,0);
  3061 			if (ok) pasteNoSave(n);
  3062 		}	
  3063 	/////////////////////////////////////////////////////////////////////
  3064 	} else if (com=="qa")
  3065 	{
  3066 		if (selection.isEmpty() )
  3067 		{
  3068 			parser.setError (Aborted,"Nothing selected");
  3069 		} else if (! selb )
  3070 		{				  
  3071 			parser.setError (Aborted,"Type of selection is not a branch");
  3072 		} else if (parser.checkParCount(4))
  3073 		{	
  3074 			QString c,u;
  3075 			c=parser.parString (ok,0);
  3076 			if (!ok)
  3077 			{
  3078 				parser.setError (Aborted,"No comment given");
  3079 			} else
  3080 			{
  3081 				s=parser.parString (ok,1);
  3082 				if (!ok)
  3083 				{
  3084 					parser.setError (Aborted,"First parameter is not a string");
  3085 				} else
  3086 				{
  3087 					t=parser.parString (ok,2);
  3088 					if (!ok)
  3089 					{
  3090 						parser.setError (Aborted,"Condition is not a string");
  3091 					} else
  3092 					{
  3093 						u=parser.parString (ok,3);
  3094 						if (!ok)
  3095 						{
  3096 							parser.setError (Aborted,"Third parameter is not a string");
  3097 						} else
  3098 						{
  3099 							if (s!="heading")
  3100 							{
  3101 								parser.setError (Aborted,"Unknown type: "+s);
  3102 							} else
  3103 							{
  3104 								if (! (t=="eq") ) 
  3105 								{
  3106 									parser.setError (Aborted,"Unknown operator: "+t);
  3107 								} else
  3108 								{
  3109 									if (! selb    )
  3110 									{
  3111 										parser.setError (Aborted,"Type of selection is not a branch");
  3112 									} else
  3113 									{
  3114 										if (selb->getHeading() == u)
  3115 										{
  3116 											cout << "PASSED: " << qPrintable (c)  << endl;
  3117 										} else
  3118 										{
  3119 											cout << "FAILED: " << qPrintable (c)  << endl;
  3120 										}
  3121 									}
  3122 								}
  3123 							}
  3124 						} 
  3125 					} 
  3126 				} 
  3127 			}
  3128 		}	
  3129 	/////////////////////////////////////////////////////////////////////
  3130 	} else if (com=="saveImage")
  3131 	{
  3132 		FloatImageObj *fio=selection.getFloatImage();
  3133 		if (!fio)
  3134 		{
  3135 			parser.setError (Aborted,"Type of selection is not an image");
  3136 		} else if (parser.checkParCount(2))
  3137 		{
  3138 			s=parser.parString(ok,0);
  3139 			if (ok)
  3140 			{
  3141 				t=parser.parString(ok,1);
  3142 				if (ok) saveFloatImageInt (fio,t,s);
  3143 			}
  3144 		}	
  3145 	/////////////////////////////////////////////////////////////////////
  3146 	} else if (com=="scroll")
  3147 	{
  3148 		if (selection.isEmpty() )
  3149 		{
  3150 			parser.setError (Aborted,"Nothing selected");
  3151 		} else if (! selb )
  3152 		{				  
  3153 			parser.setError (Aborted,"Type of selection is not a branch");
  3154 		} else if (parser.checkParCount(0))
  3155 		{	
  3156 			if (!scrollBranch (selb))	
  3157 				parser.setError (Aborted,"Could not scroll branch");
  3158 		}	
  3159 	/////////////////////////////////////////////////////////////////////
  3160 	} else if (com=="select")
  3161 	{
  3162 		if (parser.checkParCount(1))
  3163 		{
  3164 			s=parser.parString(ok,0);
  3165 			if (ok) select (s);
  3166 		}	
  3167 	/////////////////////////////////////////////////////////////////////
  3168 	} else if (com=="selectLastBranch")
  3169 	{
  3170 		if (selection.isEmpty() )
  3171 		{
  3172 			parser.setError (Aborted,"Nothing selected");
  3173 		} else if (! selb )
  3174 		{				  
  3175 			parser.setError (Aborted,"Type of selection is not a branch");
  3176 		} else if (parser.checkParCount(0))
  3177 		{	
  3178 			BranchObj *bo=selb->getLastBranch();
  3179 			if (!bo)
  3180 				parser.setError (Aborted,"Could not select last branch");
  3181 			selectInt (bo);	
  3182 				
  3183 		}	
  3184 	/////////////////////////////////////////////////////////////////////
  3185 	} else if (com=="selectLastImage")
  3186 	{
  3187 		if (selection.isEmpty() )
  3188 		{
  3189 			parser.setError (Aborted,"Nothing selected");
  3190 		} else if (! selb )
  3191 		{				  
  3192 			parser.setError (Aborted,"Type of selection is not a branch");
  3193 		} else if (parser.checkParCount(0))
  3194 		{	
  3195 			FloatImageObj *fio=selb->getLastFloatImage();
  3196 			if (!fio)
  3197 				parser.setError (Aborted,"Could not select last image");
  3198 			selectInt (fio);	
  3199 				
  3200 		}	
  3201 	/////////////////////////////////////////////////////////////////////
  3202 	} else if (com=="selectLatestAdded")
  3203 	{
  3204 		if (latestSelectionString.isEmpty() )
  3205 		{
  3206 			parser.setError (Aborted,"No latest added object");
  3207 		} else
  3208 		{	
  3209 			if (!select (latestSelectionString))
  3210 				parser.setError (Aborted,"Could not select latest added object "+latestSelectionString);
  3211 		}	
  3212 	/////////////////////////////////////////////////////////////////////
  3213 	} else if (com=="setFrameType")
  3214 	{
  3215 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3216 		{
  3217 			parser.setError (Aborted,"Type of selection does not allow setting frame type");
  3218 		}
  3219 		else if (parser.checkParCount(1))
  3220 		{
  3221 			s=parser.parString(ok,0);
  3222 			if (ok) setFrameType (s);
  3223 		}	
  3224 	/////////////////////////////////////////////////////////////////////
  3225 	} else if (com=="setFramePenColor")
  3226 	{
  3227 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3228 		{
  3229 			parser.setError (Aborted,"Type of selection does not allow setting of pen color");
  3230 		}
  3231 		else if (parser.checkParCount(1))
  3232 		{
  3233 			QColor c=parser.parColor(ok,0);
  3234 			if (ok) setFramePenColor (c);
  3235 		}	
  3236 	/////////////////////////////////////////////////////////////////////
  3237 	} else if (com=="setFrameBrushColor")
  3238 	{
  3239 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3240 		{
  3241 			parser.setError (Aborted,"Type of selection does not allow setting brush color");
  3242 		}
  3243 		else if (parser.checkParCount(1))
  3244 		{
  3245 			QColor c=parser.parColor(ok,0);
  3246 			if (ok) setFrameBrushColor (c);
  3247 		}	
  3248 	/////////////////////////////////////////////////////////////////////
  3249 	} else if (com=="setFramePadding")
  3250 	{
  3251 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3252 		{
  3253 			parser.setError (Aborted,"Type of selection does not allow setting frame padding");
  3254 		}
  3255 		else if (parser.checkParCount(1))
  3256 		{
  3257 			n=parser.parInt(ok,0);
  3258 			if (ok) setFramePadding(n);
  3259 		}	
  3260 	/////////////////////////////////////////////////////////////////////
  3261 	} else if (com=="setFrameBorderWidth")
  3262 	{
  3263 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3264 		{
  3265 			parser.setError (Aborted,"Type of selection does not allow setting frame border width");
  3266 		}
  3267 		else if (parser.checkParCount(1))
  3268 		{
  3269 			n=parser.parInt(ok,0);
  3270 			if (ok) setFrameBorderWidth (n);
  3271 		}	
  3272 	/////////////////////////////////////////////////////////////////////
  3273 	} else if (com=="setMapAuthor")
  3274 	{
  3275 		if (parser.checkParCount(1))
  3276 		{
  3277 			s=parser.parString(ok,0);
  3278 			if (ok) setAuthor (s);
  3279 		}	
  3280 	/////////////////////////////////////////////////////////////////////
  3281 	} else if (com=="setMapComment")
  3282 	{
  3283 		if (parser.checkParCount(1))
  3284 		{
  3285 			s=parser.parString(ok,0);
  3286 			if (ok) setComment(s);
  3287 		}	
  3288 	/////////////////////////////////////////////////////////////////////
  3289 	} else if (com=="setMapBackgroundColor")
  3290 	{
  3291 		if (selection.isEmpty() )
  3292 		{
  3293 			parser.setError (Aborted,"Nothing selected");
  3294 		} else if (! getSelectedBranch() )
  3295 		{				  
  3296 			parser.setError (Aborted,"Type of selection is not a branch");
  3297 		} else if (parser.checkParCount(1))
  3298 		{
  3299 			QColor c=parser.parColor (ok,0);
  3300 			if (ok) setMapBackgroundColor (c);
  3301 		}	
  3302 	/////////////////////////////////////////////////////////////////////
  3303 	} else if (com=="setMapDefLinkColor")
  3304 	{
  3305 		if (selection.isEmpty() )
  3306 		{
  3307 			parser.setError (Aborted,"Nothing selected");
  3308 		} else if (! selb )
  3309 		{				  
  3310 			parser.setError (Aborted,"Type of selection is not a branch");
  3311 		} else if (parser.checkParCount(1))
  3312 		{
  3313 			QColor c=parser.parColor (ok,0);
  3314 			if (ok) setMapDefLinkColor (c);
  3315 		}	
  3316 	/////////////////////////////////////////////////////////////////////
  3317 	} else if (com=="setMapLinkStyle")
  3318 	{
  3319 		if (parser.checkParCount(1))
  3320 		{
  3321 			s=parser.parString (ok,0);
  3322 			if (ok) setMapLinkStyle(s);
  3323 		}	
  3324 	/////////////////////////////////////////////////////////////////////
  3325 	} else if (com=="setHeading")
  3326 	{
  3327 		if (selection.isEmpty() )
  3328 		{
  3329 			parser.setError (Aborted,"Nothing selected");
  3330 		} else if (! selb )
  3331 		{				  
  3332 			parser.setError (Aborted,"Type of selection is not a branch");
  3333 		} else if (parser.checkParCount(1))
  3334 		{
  3335 			s=parser.parString (ok,0);
  3336 			if (ok) 
  3337 				setHeading (s);
  3338 		}	
  3339 	/////////////////////////////////////////////////////////////////////
  3340 	} else if (com=="setHideExport")
  3341 	{
  3342 		if (selection.isEmpty() )
  3343 		{
  3344 			parser.setError (Aborted,"Nothing selected");
  3345 		} else if (selectionType()!=TreeItem::Branch && selectionType() != TreeItem::MapCenter &&selectionType()!=TreeItem::Image)
  3346 		{				  
  3347 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3348 		} else if (parser.checkParCount(1))
  3349 		{
  3350 			b=parser.parBool(ok,0);
  3351 			if (ok) setHideExport (b);
  3352 		}
  3353 	/////////////////////////////////////////////////////////////////////
  3354 	} else if (com=="setIncludeImagesHorizontally")
  3355 	{ 
  3356 		if (selection.isEmpty() )
  3357 		{
  3358 			parser.setError (Aborted,"Nothing selected");
  3359 		} else if (! selb)
  3360 		{				  
  3361 			parser.setError (Aborted,"Type of selection is not a branch");
  3362 		} else if (parser.checkParCount(1))
  3363 		{
  3364 			b=parser.parBool(ok,0);
  3365 			if (ok) setIncludeImagesHor(b);
  3366 		}
  3367 	/////////////////////////////////////////////////////////////////////
  3368 	} else if (com=="setIncludeImagesVertically")
  3369 	{
  3370 		if (selection.isEmpty() )
  3371 		{
  3372 			parser.setError (Aborted,"Nothing selected");
  3373 		} else if (! selb)
  3374 		{				  
  3375 			parser.setError (Aborted,"Type of selection is not a branch");
  3376 		} else if (parser.checkParCount(1))
  3377 		{
  3378 			b=parser.parBool(ok,0);
  3379 			if (ok) setIncludeImagesVer(b);
  3380 		}
  3381 	/////////////////////////////////////////////////////////////////////
  3382 	} else if (com=="setHideLinkUnselected")
  3383 	{
  3384 		if (selection.isEmpty() )
  3385 		{
  3386 			parser.setError (Aborted,"Nothing selected");
  3387 		} else if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3388 		{				  
  3389 			parser.setError (Aborted,"Type of selection does not allow hiding the link");
  3390 		} else if (parser.checkParCount(1))
  3391 		{
  3392 			b=parser.parBool(ok,0);
  3393 			if (ok) setHideLinkUnselected(b);
  3394 		}
  3395 	/////////////////////////////////////////////////////////////////////
  3396 	} else if (com=="setSelectionColor")
  3397 	{
  3398 		if (parser.checkParCount(1))
  3399 		{
  3400 			QColor c=parser.parColor (ok,0);
  3401 			if (ok) setSelectionColorInt (c);
  3402 		}	
  3403 	/////////////////////////////////////////////////////////////////////
  3404 	} else if (com=="setURL")
  3405 	{
  3406 		if (selection.isEmpty() )
  3407 		{
  3408 			parser.setError (Aborted,"Nothing selected");
  3409 		} else if (! selb )
  3410 		{				  
  3411 			parser.setError (Aborted,"Type of selection is not a branch");
  3412 		} else if (parser.checkParCount(1))
  3413 		{
  3414 			s=parser.parString (ok,0);
  3415 			if (ok) setURL(s);
  3416 		}	
  3417 	/////////////////////////////////////////////////////////////////////
  3418 	} else if (com=="setVymLink")
  3419 	{
  3420 		if (selection.isEmpty() )
  3421 		{
  3422 			parser.setError (Aborted,"Nothing selected");
  3423 		} else if (! selb )
  3424 		{				  
  3425 			parser.setError (Aborted,"Type of selection is not a branch");
  3426 		} else if (parser.checkParCount(1))
  3427 		{
  3428 			s=parser.parString (ok,0);
  3429 			if (ok) setVymLink(s);
  3430 		}	
  3431 	}
  3432 	/////////////////////////////////////////////////////////////////////
  3433 	else if (com=="setFlag")
  3434 	{
  3435 		if (selection.isEmpty() )
  3436 		{
  3437 			parser.setError (Aborted,"Nothing selected");
  3438 		} else if (! selb )
  3439 		{				  
  3440 			parser.setError (Aborted,"Type of selection is not a branch");
  3441 		} else if (parser.checkParCount(1))
  3442 		{
  3443 			s=parser.parString(ok,0);
  3444 			if (ok) 
  3445 			{
  3446 				selb->activateStandardFlag(s);
  3447 				selb->updateFlagsToolbar();
  3448 			}	
  3449 		}
  3450 	/////////////////////////////////////////////////////////////////////
  3451 	} else if (com=="setFrameType")
  3452 	{
  3453 		if (selection.isEmpty() )
  3454 		{
  3455 			parser.setError (Aborted,"Nothing selected");
  3456 		} else if (! selb )
  3457 		{				  
  3458 			parser.setError (Aborted,"Type of selection is not a branch");
  3459 		} else if (parser.checkParCount(1))
  3460 		{
  3461 			s=parser.parString(ok,0);
  3462 			if (ok) 
  3463 				setFrameType (s);
  3464 		}
  3465 	/////////////////////////////////////////////////////////////////////
  3466 	} else if (com=="sortChildren")
  3467 	{
  3468 		if (selection.isEmpty() )
  3469 		{
  3470 			parser.setError (Aborted,"Nothing selected");
  3471 		} else if (! selb )
  3472 		{				  
  3473 			parser.setError (Aborted,"Type of selection is not a branch");
  3474 		} else if (parser.checkParCount(0))
  3475 		{
  3476 			sortChildren();
  3477 		}
  3478 	/////////////////////////////////////////////////////////////////////
  3479 	} else if (com=="toggleFlag")
  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 			{
  3492 				selb->toggleStandardFlag(s);	
  3493 				selb->updateFlagsToolbar();
  3494 			}	
  3495 		}
  3496 	/////////////////////////////////////////////////////////////////////
  3497 	} else if (com=="unscroll")
  3498 	{
  3499 		if (selection.isEmpty() )
  3500 		{
  3501 			parser.setError (Aborted,"Nothing selected");
  3502 		} else if (! selb )
  3503 		{				  
  3504 			parser.setError (Aborted,"Type of selection is not a branch");
  3505 		} else if (parser.checkParCount(0))
  3506 		{	
  3507 			if (!unscrollBranch (selb))	
  3508 				parser.setError (Aborted,"Could not unscroll branch");
  3509 		}	
  3510 	/////////////////////////////////////////////////////////////////////
  3511 	} else if (com=="unscrollChildren")
  3512 	{
  3513 		if (selection.isEmpty() )
  3514 		{
  3515 			parser.setError (Aborted,"Nothing selected");
  3516 		} else if (! selb )
  3517 		{				  
  3518 			parser.setError (Aborted,"Type of selection is not a branch");
  3519 		} else if (parser.checkParCount(0))
  3520 		{	
  3521 			unscrollChildren ();
  3522 		}	
  3523 	/////////////////////////////////////////////////////////////////////
  3524 	} else if (com=="unsetFlag")
  3525 	{
  3526 		if (selection.isEmpty() )
  3527 		{
  3528 			parser.setError (Aborted,"Nothing selected");
  3529 		} else if (! selb )
  3530 		{				  
  3531 			parser.setError (Aborted,"Type of selection is not a branch");
  3532 		} else if (parser.checkParCount(1))
  3533 		{
  3534 			s=parser.parString(ok,0);
  3535 			if (ok) 
  3536 			{
  3537 				selb->deactivateStandardFlag(s);
  3538 				selb->updateFlagsToolbar();
  3539 			}	
  3540 		}
  3541 	} else
  3542 		parser.setError (Aborted,"Unknown command");
  3543 
  3544 	// Any errors?
  3545 	if (parser.errorLevel()==NoError)
  3546 	{
  3547 		// setChanged();  FIXME should not be called e.g. for export?!
  3548 		reposition();
  3549 	}	
  3550 	else	
  3551 	{
  3552 		// TODO Error handling
  3553 		qWarning("VymModel::parseAtom: Error!");
  3554 		qWarning(parser.errorMessage());
  3555 	} 
  3556 }
  3557 
  3558 void VymModel::runScript (QString script)
  3559 {
  3560 	parser.setScript (script);
  3561 	parser.runScript();
  3562 	while (parser.next() ) 
  3563 		parseAtom(parser.getAtom());
  3564 }
  3565 
  3566 void VymModel::setExportMode (bool b)
  3567 {
  3568 	// should be called before and after exports
  3569 	// depending on the settings
  3570 	if (b && settings.value("/export/useHideExport","true")=="true")
  3571 		setHideTmpMode (HideExport);
  3572 	else	
  3573 		setHideTmpMode (HideNone);
  3574 }
  3575 
  3576 void VymModel::exportImage(QString fname, bool askName, QString format)
  3577 {
  3578 	if (fname=="")
  3579 	{
  3580 		fname=getMapName()+".png";
  3581 		format="PNG";
  3582 	} 	
  3583 
  3584 	if (askName)
  3585 	{
  3586 		QStringList fl;
  3587 		QFileDialog *fd=new QFileDialog (NULL);
  3588 		fd->setCaption (tr("Export map as image"));
  3589 		fd->setDirectory (lastImageDir);
  3590 		fd->setFileMode(QFileDialog::AnyFile);
  3591 		fd->setFilters  (imageIO.getFilters() );
  3592 		if (fd->exec())
  3593 		{
  3594 			fl=fd->selectedFiles();
  3595 			fname=fl.first();
  3596 			format=imageIO.getType(fd->selectedFilter());
  3597 		} 
  3598 	}
  3599 
  3600 	setExportMode (true);
  3601 	QPixmap pix (getPixmap());
  3602 	pix.save(fname, format);
  3603 	setExportMode (false);
  3604 }
  3605 
  3606 
  3607 void VymModel::exportXML(QString dir, bool askForName)
  3608 {
  3609 	if (askForName)
  3610 	{
  3611 		dir=browseDirectory(NULL,tr("Export XML to directory"));
  3612 		if (dir =="" && !reallyWriteDirectory(dir) )
  3613 		return;
  3614 	}
  3615 
  3616 	// Hide stuff during export, if settings want this
  3617 	setExportMode (true);
  3618 
  3619 	// Create subdirectories
  3620 	makeSubDirs (dir);
  3621 
  3622 	// write to directory
  3623 	QString saveFile=saveToDir (dir,mapName+"-",true,getTotalBBox().topLeft() ,NULL);
  3624 	QFile file;
  3625 
  3626 	file.setName ( dir + "/"+mapName+".xml");
  3627 	if ( !file.open( QIODevice::WriteOnly ) )
  3628 	{
  3629 		// This should neverever happen
  3630 		QMessageBox::critical (0,tr("Critical Export Error"),tr("VymModel::exportXML couldn't open %1").arg(file.name()));
  3631 		return;
  3632 	}	
  3633 
  3634 	// Write it finally, and write in UTF8, no matter what 
  3635 	QTextStream ts( &file );
  3636 	ts.setEncoding (QTextStream::UnicodeUTF8);
  3637 	ts << saveFile;
  3638 	file.close();
  3639 
  3640 	// Now write image, too
  3641 	exportImage (dir+"/images/"+mapName+".png",false,"PNG");
  3642 
  3643 	setExportMode (false);
  3644 }
  3645 
  3646 void VymModel::exportASCII(QString fname,bool askName)
  3647 {
  3648 	ExportASCII ex;
  3649 	ex.setModel (this);
  3650 	if (fname=="") 
  3651 		ex.setFile (mapName+".txt");	
  3652 	else
  3653 		ex.setFile (fname);
  3654 
  3655 	if (askName)
  3656 	{
  3657 		//ex.addFilter ("TXT (*.txt)");
  3658 		ex.setDir(lastImageDir);
  3659 		//ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
  3660 		ex.execDialog() ; 
  3661 	} 
  3662 	if (!ex.canceled())
  3663 	{
  3664 		setExportMode(true);
  3665 		ex.doExport();
  3666 		setExportMode(false);
  3667 	}
  3668 }
  3669 
  3670 void VymModel::exportXHTML (const QString &dir, bool askForName)
  3671 {
  3672 			ExportXHTMLDialog dia(NULL);
  3673 			dia.setFilePath (filePath );
  3674 			dia.setMapName (mapName );
  3675 			dia.readSettings();
  3676 			if (dir!="") dia.setDir (dir);
  3677 
  3678 			bool ok=true;
  3679 			
  3680 			if (askForName)
  3681 			{
  3682 				if (dia.exec()!=QDialog::Accepted) 
  3683 					ok=false;
  3684 				else	
  3685 				{
  3686 					QDir d (dia.getDir());
  3687 					// Check, if warnings should be used before overwriting
  3688 					// the output directory
  3689 					if (d.exists() && d.count()>0)
  3690 					{
  3691 						WarningDialog warn;
  3692 						warn.showCancelButton (true);
  3693 						warn.setText(QString(
  3694 							"The directory %1 is not empty.\n"
  3695 							"Do you risk to overwrite some of its contents?").arg(d.path() ));
  3696 						warn.setCaption("Warning: Directory not empty");
  3697 						warn.setShowAgainName("mainwindow/overwrite-dir-xhtml");
  3698 
  3699 						if (warn.exec()!=QDialog::Accepted) ok=false;
  3700 					}
  3701 				}	
  3702 			}
  3703 
  3704 			if (ok)
  3705 			{
  3706 				exportXML (dia.getDir(),false );
  3707 				dia.doExport(mapName );
  3708 				//if (dia.hasChanged()) setChanged();
  3709 			}
  3710 }
  3711 
  3712 void VymModel::exportOOPresentation(const QString &fn, const QString &cf)
  3713 {
  3714 	ExportOO ex;
  3715 	ex.setFile (fn);
  3716 	ex.setModel (this);
  3717 	if (ex.setConfigFile(cf)) 
  3718 	{
  3719 		setExportMode (true);
  3720 		ex.exportPresentation();
  3721 		setExportMode (false);
  3722 	}
  3723 }
  3724 
  3725 
  3726 
  3727 
  3728 //////////////////////////////////////////////
  3729 // View related
  3730 //////////////////////////////////////////////
  3731 
  3732 void VymModel::registerEditor(QWidget *me)
  3733 {
  3734 	mapEditor=(MapEditor*)me;
  3735 	for (int i=0; i<mapCenters.count(); i++)
  3736 		mapCenters.at(i)->setMapEditor(mapEditor);
  3737 }
  3738 
  3739 void VymModel::unregisterEditor(QWidget *)
  3740 {
  3741 	mapEditor=NULL;
  3742 }
  3743 
  3744 void VymModel::setContextPos(QPointF p)
  3745 {
  3746 	contextPos=p;
  3747 }
  3748 
  3749 void VymModel::unsetContextPos()
  3750 {
  3751 	contextPos=QPointF();
  3752 }
  3753 
  3754 void VymModel::updateNoteFlag()
  3755 {
  3756 	setChanged();
  3757 	BranchObj *bo=getSelectedBranch();
  3758 	if (bo) 
  3759 	{
  3760 		bo->updateNoteFlag();
  3761 		mainWindow->updateActions();
  3762 	}	
  3763 }
  3764 
  3765 void VymModel::updateRelPositions()
  3766 {
  3767 	for (int i=0; i<mapCenters.count(); i++)
  3768 		mapCenters.at(i)->updateRelPositions();
  3769 }
  3770 
  3771 void VymModel::reposition()
  3772 {
  3773 	for (int i=0;i<mapCenters.count(); i++)
  3774 		mapCenters.at(i)->reposition();	//	for positioning heading
  3775 }
  3776 
  3777 QPolygonF VymModel::shape(BranchObj *bo)
  3778 {
  3779 	// Creating (arbitrary) shapes
  3780 
  3781 	QPolygonF p;
  3782 	QRectF rb=bo->getBBox();
  3783 	if (bo->getDepth()==0)
  3784 	{
  3785 		// Just take BBox of this mapCenter
  3786 		p<<rb.topLeft()<<rb.topRight()<<rb.bottomRight()<<rb.bottomLeft();
  3787 		return p;
  3788 	}
  3789 
  3790 	// Take union of BBox and TotalBBox 
  3791 
  3792 	QRectF ra=bo->getTotalBBox();
  3793 	if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
  3794 		p   <<ra.bottomLeft()
  3795 			<<ra.topLeft()
  3796 			<<QPointF (rb.topLeft().x(), ra.topLeft().y() )
  3797 			<<rb.topRight()
  3798 			<<rb.bottomRight()
  3799 			<<QPointF (rb.bottomLeft().x(), ra.bottomLeft().y() ) ;
  3800 	else		
  3801 		p   <<ra.bottomRight()
  3802 			<<ra.topRight()
  3803 			<<QPointF (rb.topRight().x(), ra.topRight().y() )
  3804 			<<rb.topLeft()
  3805 			<<rb.bottomLeft()
  3806 			<<QPointF (rb.bottomRight().x(), ra.bottomRight().y() ) ;
  3807 	return p;		
  3808 
  3809 }
  3810 
  3811 void VymModel::moveAway(LinkableMapObj *lmo)
  3812 {
  3813 	// Autolayout:
  3814 	//
  3815 	// Move all branches and MapCenters away from lmo 
  3816 	// to avoid collisions 
  3817 
  3818 	QPolygonF pA;
  3819 	QPolygonF pB;
  3820 
  3821 	BranchObj *boA=(BranchObj*)lmo;
  3822 	BranchObj *boB;
  3823 	for (int i=0; i<mapCenters.count(); i++)
  3824 	{
  3825 		boB=mapCenters.at(i);
  3826 		pA=shape (boA);
  3827 		pB=shape (boB);
  3828 		PolygonCollisionResult r = PolygonCollision(pA, pB, QPoint(0,0));
  3829 		cout <<"------->"
  3830 			<<"="<<r.intersect
  3831 			<<"  ("<<qPrintable(boA->getHeading() )<<")"
  3832 			<<"  with ("<< qPrintable (boB->getHeading() )
  3833 			<<")  willIntersect"
  3834 			<<r.willIntersect 
  3835 			<<"  minT="<<r.minTranslation<<endl<<endl;
  3836 	}
  3837 }
  3838 
  3839 QPixmap VymModel::getPixmap()
  3840 {
  3841 	QRectF mapRect=getTotalBBox();
  3842 	QPixmap pix((int)mapRect.width()+2,(int)mapRect.height()+1);
  3843 	QPainter pp (&pix);
  3844 	
  3845 	pp.setRenderHints(mapEditor->renderHints());
  3846 
  3847 	// Don't print the visualisation of selection
  3848 	selection.unselect();
  3849 
  3850 	mapScene->render (	&pp, 
  3851 		QRectF(0,0,mapRect.width()+2,mapRect.height()+2),
  3852 		QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
  3853 
  3854 	// Restore selection
  3855 	selection.reselect();
  3856 	
  3857 	return pix;
  3858 }
  3859 
  3860 
  3861 void VymModel::setMapLinkStyle (const QString & s)
  3862 {
  3863 	QString snow;
  3864 	switch (linkstyle)
  3865 	{
  3866 		case LinkableMapObj::Line :
  3867 			snow="StyleLine";
  3868 			break;
  3869 		case LinkableMapObj::Parabel:
  3870 			snow="StyleParabel";
  3871 			break;
  3872 		case LinkableMapObj::PolyLine:
  3873 			snow="StylePolyLine";
  3874 			break;
  3875 		case LinkableMapObj::PolyParabel:
  3876 			snow="StylePolyParabel";
  3877 			break;
  3878 		default:	
  3879 			snow="UndefinedStyle";
  3880 			break;
  3881 	}
  3882 
  3883 	saveState (
  3884 		QString("setMapLinkStyle (\"%1\")").arg(s),
  3885 		QString("setMapLinkStyle (\"%1\")").arg(snow),
  3886 		QString("Set map link style (\"%1\")").arg(s)
  3887 	);	
  3888 
  3889 	if (s=="StyleLine")
  3890 		linkstyle=LinkableMapObj::Line;
  3891 	else if (s=="StyleParabel")
  3892 		linkstyle=LinkableMapObj::Parabel;
  3893 	else if (s=="StylePolyLine")
  3894 		linkstyle=LinkableMapObj::PolyLine;
  3895 	else if (s=="StylePolyParabel")	
  3896 		linkstyle=LinkableMapObj::PolyParabel;
  3897 	else
  3898 		linkstyle=LinkableMapObj::UndefinedStyle;
  3899 
  3900 	TreeItem *ti=first();
  3901 	BranchObj *bo;
  3902 	while (ti) 
  3903 	{
  3904 		bo=(BranchObj*)(ti->getLMO() );
  3905 		bo->setLinkStyle(bo->getDefLinkStyle());
  3906 		ti=next();
  3907 	}
  3908 	reposition();
  3909 }
  3910 
  3911 LinkableMapObj::Style VymModel::getMapLinkStyle ()
  3912 {
  3913 	return linkstyle;
  3914 }	
  3915 
  3916 void VymModel::setMapDefLinkColor(QColor col)
  3917 {
  3918 	if ( !col.isValid() ) return;
  3919 	saveState (
  3920 		QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
  3921 		QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
  3922 		QString("Set map link color to %1").arg(col.name())
  3923 	);
  3924 
  3925 	defLinkColor=col;
  3926 	TreeItem *ti;
  3927 	BranchObj *bo;
  3928 	ti=first();
  3929 	while (ti) 
  3930 	{
  3931 		bo=(BranchObj*)(ti->getLMO() );
  3932 		bo->setLinkColor();
  3933 		ti=next();
  3934 	}
  3935 	updateActions();
  3936 }
  3937 
  3938 void VymModel::setMapLinkColorHintInt()
  3939 {
  3940 	// called from setMapLinkColorHint(lch) or at end of parse
  3941 	TreeItem *ti;
  3942 	BranchObj *bo;
  3943 	ti=first();
  3944 	while (ti) 
  3945 	{
  3946 		bo=(BranchObj*)(ti->getLMO() );
  3947 		bo->setLinkColor();
  3948 		ti=next();
  3949 	}
  3950 }
  3951 
  3952 void VymModel::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
  3953 {
  3954 	linkcolorhint=lch;
  3955 	setMapLinkColorHintInt();
  3956 }
  3957 
  3958 void VymModel::toggleMapLinkColorHint()
  3959 {
  3960 	if (linkcolorhint==LinkableMapObj::HeadingColor)
  3961 		linkcolorhint=LinkableMapObj::DefaultColor;
  3962 	else	
  3963 		linkcolorhint=LinkableMapObj::HeadingColor;
  3964 	TreeItem *ti;
  3965 	BranchObj *bo;
  3966 	ti=first();
  3967 	while (bo) 
  3968 	{
  3969 		bo=(BranchObj*)(ti->getLMO() );
  3970 		bo->setLinkColor();
  3971 		ti=next();
  3972 	}
  3973 }
  3974 
  3975 void VymModel::selectMapBackgroundImage ()	// FIXME move to ME
  3976 {
  3977 	Q3FileDialog *fd=new Q3FileDialog( NULL);
  3978 	fd->setMode (Q3FileDialog::ExistingFile);
  3979 	fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  3980 	ImagePreview *p =new ImagePreview (fd);
  3981 	fd->setContentsPreviewEnabled( TRUE );
  3982 	fd->setContentsPreview( p, p );
  3983 	fd->setPreviewMode( Q3FileDialog::Contents );
  3984 	fd->setCaption(vymName+" - " +tr("Load background image"));
  3985 	fd->setDir (lastImageDir);
  3986 	fd->show();
  3987 
  3988 	if ( fd->exec() == QDialog::Accepted )
  3989 	{
  3990 		// TODO selectMapBackgroundImg in QT4 use:	lastImageDir=fd->directory();
  3991 		lastImageDir=QDir (fd->dirPath());
  3992 		setMapBackgroundImage (fd->selectedFile());
  3993 	}
  3994 }	
  3995 
  3996 void VymModel::setMapBackgroundImage (const QString &fn)	//FIXME missing savestate
  3997 {
  3998 	QColor oldcol=mapScene->backgroundBrush().color();
  3999 	/*
  4000 	saveState(
  4001 		selection,
  4002 		QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
  4003 		selection,
  4004 		QString ("setMapBackgroundImage (%1)").arg(col.name()),
  4005 		QString("Set background color of map to %1").arg(col.name()));
  4006 	*/	
  4007 	QBrush brush;
  4008 	brush.setTextureImage (QPixmap (fn));
  4009 	mapScene->setBackgroundBrush(brush);
  4010 }
  4011 
  4012 void VymModel::selectMapBackgroundColor()	// FIXME move to ME
  4013 {
  4014 	QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), NULL);
  4015 	if ( !col.isValid() ) return;
  4016 	setMapBackgroundColor( col );
  4017 }
  4018 
  4019 
  4020 void VymModel::setMapBackgroundColor(QColor col)	// FIXME move to ME
  4021 {
  4022 	QColor oldcol=mapScene->backgroundBrush().color();
  4023 	saveState(
  4024 		QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
  4025 		QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
  4026 		QString("Set background color of map to %1").arg(col.name()));
  4027 	mapScene->setBackgroundBrush(col);
  4028 }
  4029 
  4030 QColor VymModel::getMapBackgroundColor()	// FIXME move to ME
  4031 {
  4032     return mapScene->backgroundBrush().color();
  4033 }
  4034 
  4035 
  4036 LinkableMapObj::ColorHint VymModel::getMapLinkColorHint()	// FIXME move to ME
  4037 {
  4038 	return linkcolorhint;
  4039 }
  4040 
  4041 QColor VymModel::getMapDefLinkColor()	// FIXME move to ME
  4042 {
  4043 	return defLinkColor;
  4044 }
  4045 
  4046 void VymModel::setMapDefXLinkColor(QColor col)	// FIXME move to ME
  4047 {
  4048 	defXLinkColor=col;
  4049 }
  4050 
  4051 QColor VymModel::getMapDefXLinkColor()	// FIXME move to ME
  4052 {
  4053 	return defXLinkColor;
  4054 }
  4055 
  4056 void VymModel::setMapDefXLinkWidth (int w)	// FIXME move to ME
  4057 {
  4058 	defXLinkWidth=w;
  4059 }
  4060 
  4061 int VymModel::getMapDefXLinkWidth()	// FIXME move to ME
  4062 {
  4063 	return defXLinkWidth;
  4064 }
  4065 
  4066 void VymModel::move(const double &x, const double &y)
  4067 {
  4068 	BranchObj *bo = getSelectedBranch();
  4069 	if (bo && 
  4070 		(selectionType()==TreeItem::Branch ||
  4071 		 selectionType()==TreeItem::MapCenter ||
  4072 		 selectionType()==TreeItem::Image
  4073 		))
  4074 	{
  4075         QPointF ap(bo->getAbsPos());
  4076         QPointF to(x, y);
  4077         if (ap != to)
  4078         {
  4079             QString ps=qpointfToString(ap);
  4080             QString s=getSelectString();
  4081             saveState(
  4082                 s, "move "+ps, 
  4083                 s, "move "+qpointfToString(to), 
  4084                 QString("Move %1 to %2").arg(getObjectName(bo)).arg(ps));
  4085             bo->move(x,y);
  4086             reposition();
  4087             selection.update();
  4088         }
  4089 	}
  4090 }
  4091 
  4092 void VymModel::moveRel (const double &x, const double &y)
  4093 {
  4094 	BranchObj *bo = getSelectedBranch();
  4095 	if (bo && 
  4096 		(selectionType()==TreeItem::Branch ||
  4097 		 selectionType()==TreeItem::MapCenter ||
  4098 		 selectionType()==TreeItem::Image
  4099 		))
  4100 	if (bo)
  4101 	{
  4102         QPointF rp(bo->getRelPos());
  4103         QPointF to(x, y);
  4104         if (rp != to)
  4105         {
  4106             QString ps=qpointfToString (bo->getRelPos());
  4107             QString s=getSelectString(bo);
  4108             saveState(
  4109                 s, "moveRel "+ps, 
  4110                 s, "moveRel "+qpointfToString(to), 
  4111                 QString("Move %1 to relative position %2").arg(getObjectName(bo)).arg(ps));
  4112             ((OrnamentedObj*)bo)->move2RelPos (x,y);
  4113             reposition();
  4114             bo->updateLink();
  4115             selection.update();
  4116         }
  4117 	}
  4118 }
  4119 
  4120 
  4121 void VymModel::animate()
  4122 {
  4123 	animationTimer->stop();
  4124 	BranchObj *bo;
  4125 	int i=0;
  4126 	while (i<animObjList.size() )
  4127 	{
  4128 		bo=(BranchObj*)animObjList.at(i);
  4129 		if (!bo->animate())
  4130 		{
  4131 			if (i>=0) 
  4132 			{	
  4133 				animObjList.removeAt(i);
  4134 				i--;
  4135 			}
  4136 		}
  4137 		bo->reposition();
  4138 		i++;
  4139 	} 
  4140 	QItemSelection sel=selModel->selection();
  4141 	emit (selectionChanged(sel,sel));
  4142 
  4143 	mapScene->update();
  4144 	if (!animObjList.isEmpty()) animationTimer->start();
  4145 }
  4146 
  4147 
  4148 void VymModel::startAnimation(BranchObj *bo, const QPointF &start, const QPointF &dest)
  4149 {
  4150 	if (bo && bo->getDepth()>0) 
  4151 	{
  4152 		AnimPoint ap;
  4153 		ap.setStart (start);
  4154 		ap.setDest  (dest);
  4155 		ap.setTicks (animationTicks);
  4156 		ap.setAnimated (true);
  4157 		bo->setAnimation (ap);
  4158 		animObjList.append( bo );
  4159 		animationTimer->setSingleShot (true);
  4160 		animationTimer->start(animationInterval);
  4161 	}
  4162 }
  4163 
  4164 void VymModel::stopAnimation (MapObj *mo)
  4165 {
  4166 	int i=animObjList.indexOf(mo);
  4167     if (i>=0)
  4168 		animObjList.removeAt (i);
  4169 }
  4170 
  4171 void VymModel::sendSelection()
  4172 {
  4173 	if (netstate!=Server) return;
  4174 	sendData (QString("select (\"%1\")").arg(selection.getSelectString()) );
  4175 }
  4176 
  4177 void VymModel::newServer()
  4178 {
  4179 	port=54321;
  4180 	sendCounter=0;
  4181     tcpServer = new QTcpServer(this);
  4182     if (!tcpServer->listen(QHostAddress::Any,port)) {
  4183         QMessageBox::critical(NULL, "vym server",
  4184                               QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
  4185         //FIXME needed? we are no widget any longer... close();
  4186         return;
  4187     }
  4188 	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
  4189 	netstate=Server;
  4190 	cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
  4191 }
  4192 
  4193 void VymModel::connectToServer()
  4194 {
  4195 	port=54321;
  4196 	server="salam.suse.de";
  4197 	server="localhost";
  4198 	clientSocket = new QTcpSocket (this);
  4199 	clientSocket->abort();
  4200     clientSocket->connectToHost(server ,port);
  4201 	connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
  4202     connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
  4203             this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
  4204 	netstate=Client;		
  4205 	cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
  4206 
  4207 	
  4208 }
  4209 
  4210 void VymModel::newClient()
  4211 {
  4212     QTcpSocket *newClient = tcpServer->nextPendingConnection();
  4213     connect(newClient, SIGNAL(disconnected()),
  4214             newClient, SLOT(deleteLater()));
  4215 
  4216 	cout <<"ME::newClient  at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
  4217 
  4218 	clientList.append (newClient);
  4219 }
  4220 
  4221 
  4222 void VymModel::sendData(const QString &s)
  4223 {
  4224 	if (clientList.size()==0) return;
  4225 
  4226 	// Create bytearray to send
  4227 	QByteArray block;
  4228     QDataStream out(&block, QIODevice::WriteOnly);
  4229     out.setVersion(QDataStream::Qt_4_0);
  4230 
  4231 	// Reserve some space for blocksize
  4232     out << (quint16)0;
  4233 
  4234 	// Write sendCounter
  4235     out << sendCounter++;
  4236 
  4237 	// Write data
  4238     out << s;
  4239 
  4240 	// Go back and write blocksize so far
  4241     out.device()->seek(0);
  4242     quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
  4243 	out << bs;
  4244 
  4245 	if (debug)
  4246 		cout << "ME::sendData  bs="<<bs<<"  counter="<<sendCounter<<"  s="<<qPrintable(s)<<endl;
  4247 
  4248 	for (int i=0; i<clientList.size(); ++i)
  4249 	{
  4250 		//cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
  4251 		clientList.at(i)->write (block);
  4252 	}
  4253 }
  4254 
  4255 void VymModel::readData ()
  4256 {
  4257 	while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
  4258 	{
  4259 		if (debug)
  4260 			cout <<"readData  bytesAvail="<<clientSocket->bytesAvailable();
  4261 		quint16 recCounter;
  4262 		quint16 blockSize;
  4263 
  4264 		QDataStream in(clientSocket);
  4265 		in.setVersion(QDataStream::Qt_4_0);
  4266 
  4267 		in >> blockSize;
  4268 		in >> recCounter;
  4269 		
  4270 		QString t;
  4271 		in >>t;
  4272 		if (debug)
  4273 			cout << "  t="<<qPrintable (t)<<endl;
  4274 		parseAtom (t);
  4275 	}
  4276 	return;
  4277 }
  4278 
  4279 void VymModel::displayNetworkError(QAbstractSocket::SocketError socketError)
  4280 {
  4281     switch (socketError) {
  4282     case QAbstractSocket::RemoteHostClosedError:
  4283         break;
  4284     case QAbstractSocket::HostNotFoundError:
  4285         QMessageBox::information(NULL, vymName +" Network client",
  4286                                  "The host was not found. Please check the "
  4287                                     "host name and port settings.");
  4288         break;
  4289     case QAbstractSocket::ConnectionRefusedError:
  4290         QMessageBox::information(NULL, vymName + " Network client",
  4291                                  "The connection was refused by the peer. "
  4292                                     "Make sure the fortune server is running, "
  4293                                     "and check that the host name and port "
  4294                                     "settings are correct.");
  4295         break;
  4296     default:
  4297         QMessageBox::information(NULL, vymName + " Network client",
  4298                                  QString("The following error occurred: %1.")
  4299                                  .arg(clientSocket->errorString()));
  4300     }
  4301 }
  4302 
  4303 
  4304 
  4305 
  4306 void VymModel::selectMapSelectionColor()
  4307 {
  4308 	QColor col = QColorDialog::getColor( defLinkColor, NULL);
  4309 	setSelectionColor (col);
  4310 }
  4311 
  4312 void VymModel::setSelectionColorInt (QColor col)
  4313 {
  4314 	if ( !col.isValid() ) return;
  4315 	saveState (
  4316 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4317 		QString("setSelectionColor (%1)").arg(col.name()),
  4318 		QString("Set color of selection box to %1").arg(col.name())
  4319 	);
  4320 
  4321 	mapEditor->setSelectionColor (col);
  4322 }
  4323 
  4324 void VymModel::updateSelection()
  4325 {
  4326 	QItemSelection newsel=selModel->selection();
  4327 	updateSelection (newsel);
  4328 }
  4329 
  4330 void VymModel::updateSelection(const QItemSelection &)
  4331 {
  4332 	QItemSelection newsel=selModel->selection();
  4333 	/*
  4334 	cout << "VM::updateSelection   new=";
  4335 	if (!newsel.indexes().isEmpty() )
  4336 		cout << newsel.indexes().first().row()<<"," << newsel.indexes().first().column();
  4337 	cout << "  old=";
  4338 	if (!oldsel.indexes().isEmpty() )
  4339 		cout << oldsel.indexes().first().row()<<"," << oldsel.indexes().first().column();
  4340 	cout <<endl;
  4341 	*/
  4342 	//emit (selectionChanged(newsel,oldsel));	// FIXME needed?
  4343 	ensureSelectionVisible();
  4344 	sendSelection();
  4345 }
  4346 
  4347 void VymModel::setSelectionColor(QColor col)
  4348 {
  4349 	if ( !col.isValid() ) return;
  4350 	saveState (
  4351 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4352 		QString("setSelectionColor (%1)").arg(col.name()),
  4353 		QString("Set color of selection box to %1").arg(col.name())
  4354 	);
  4355 	setSelectionColorInt (col);
  4356 }
  4357 
  4358 QColor VymModel::getSelectionColor()
  4359 {
  4360 	return mapEditor->getSelectionColor();
  4361 }
  4362 
  4363 void VymModel::setHideTmpMode (HideTmpMode mode)
  4364 {
  4365 	hidemode=mode;
  4366 	for (int i=0;i<mapCenters.count(); i++)
  4367 		mapCenters.at(i)->setHideTmp (mode);	
  4368 	reposition();
  4369 	// FIXME needed? scene()->update();
  4370 }
  4371 
  4372 
  4373 QRectF VymModel::getTotalBBox()
  4374 {
  4375 	QRectF r;
  4376 	for (int i=0;i<mapCenters.count(); i++)
  4377 		r=addBBox (mapCenters.at(i)->getTotalBBox(), r);
  4378 	return r;	
  4379 }
  4380 
  4381 //////////////////////////////////////////////
  4382 // Selection related
  4383 //////////////////////////////////////////////
  4384 
  4385 void VymModel::setSelectionModel (QItemSelectionModel *sm)
  4386 {
  4387 	selModel=sm;
  4388 	cout << "VM::setSelModel  selModel="<<selModel<<endl;
  4389 }
  4390 
  4391 QItemSelectionModel* VymModel::getSelectionModel()
  4392 {
  4393 	return selModel;
  4394 }
  4395 
  4396 void VymModel::setSelectionBlocked (bool b)
  4397 {
  4398 	if (b)
  4399 		selection.block();
  4400 	else	
  4401 		selection.unblock();
  4402 }
  4403 
  4404 bool VymModel::isSelectionBlocked()
  4405 {
  4406 	return selection.isBlocked();
  4407 }
  4408 
  4409 bool VymModel::select ()
  4410 {
  4411 	QModelIndex index=selModel->selectedIndexes().first();	// TODO no multiselections yet
  4412 
  4413 	TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
  4414 	return select (item->getLMO() );
  4415 }
  4416 
  4417 bool VymModel::select (const QString &s)
  4418 {
  4419 	LinkableMapObj *lmo=findObjBySelect(s);
  4420 
  4421 	// Finally select the found object
  4422 	if (lmo)
  4423 	{
  4424 		unselect();
  4425 		select (lmo);
  4426 		return true;
  4427 	} 
  4428 	return false;
  4429 }
  4430 
  4431 bool VymModel::select (LinkableMapObj *lmo)
  4432 {
  4433 	QItemSelection oldsel=selModel->selection();
  4434 
  4435 	if (lmo)
  4436 		return select (lmo->getTreeItem() );
  4437 	else	
  4438 		return false;
  4439 }
  4440 
  4441 bool VymModel::select (TreeItem *ti)
  4442 {
  4443 	if (ti)
  4444 	{
  4445 		QModelIndex ix=index(ti);
  4446 		selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4447 		ti->setLastSelectedBranch();
  4448 		//updateSelection(oldsel);	//FIXME needed?
  4449 		return true;
  4450 	}
  4451 	return false;
  4452 }
  4453 
  4454 void VymModel::unselect()
  4455 {
  4456 	selModel->clearSelection();
  4457 }	
  4458 
  4459 void VymModel::reselect()
  4460 {
  4461 	selection.reselect();
  4462 }	
  4463 
  4464 void VymModel::ensureSelectionVisible()
  4465 {
  4466 	LinkableMapObj *lmo=getSelectedLMO();
  4467 	if (lmo &&mapEditor) mapEditor->ensureVisible (lmo->getBBox() );
  4468 	
  4469 }
  4470 
  4471 void VymModel::selectInt (LinkableMapObj *lmo)
  4472 {
  4473 	if (selection.select(lmo))
  4474 	{
  4475 		//selection.update();
  4476 		sendSelection ();	// FIXME VM use signal
  4477 	}
  4478 }
  4479 
  4480 
  4481 void VymModel::selectNextBranchInt()
  4482 {
  4483 	// Increase number of branch
  4484 	LinkableMapObj *sel=getSelectedBranch();
  4485 	if (sel)
  4486 	{
  4487 		QString s=getSelectString();
  4488 		QString part;
  4489 		QString typ;
  4490 		QString num;
  4491 
  4492 		// Where am I? 
  4493 		part=s.section(",",-1);
  4494 		typ=part.left (3);
  4495 		num=part.right(part.length() - 3);
  4496 
  4497 		s=s.left (s.length() -num.length());
  4498 
  4499 		// Go to next lmo
  4500 		num=QString ("%1").arg(num.toUInt()+1);
  4501 
  4502 		s=s+num;
  4503 		
  4504 		// Try to select this one
  4505 		if (select (s)) return;
  4506 
  4507 		// We have no direct successor, 
  4508 		// try to increase the parental number in order to
  4509 		// find a successor with same depth
  4510 
  4511 		int d=getSelectedLMO()->getDepth();
  4512 		int oldDepth=d;
  4513 		int i;
  4514 		bool found=false;
  4515 		bool b;
  4516 		while (!found && d>0)
  4517 		{
  4518 			s=s.section (",",0,d-1);
  4519 			// replace substring of current depth in s with "1"
  4520 			part=s.section(",",-1);
  4521 			typ=part.left (3);
  4522 			num=part.right(part.length() - 3);
  4523 
  4524 			if (d>1)
  4525 			{	
  4526 				// increase number of parent
  4527 				num=QString ("%1").arg(num.toUInt()+1);
  4528 				s=s.section (",",0,d-2) + ","+ typ+num;
  4529 			} else
  4530 			{
  4531 				// Special case, look at orientation
  4532 				if (getSelectedLMO()->getOrientation()==LinkableMapObj::RightOfCenter)
  4533 					num=QString ("%1").arg(num.toUInt()+1);
  4534 				else	
  4535 					num=QString ("%1").arg(num.toUInt()-1);
  4536 				s=typ+num;
  4537 			}	
  4538 
  4539 			if (select (s))
  4540 				// pad to oldDepth, select the first branch for each depth
  4541 				for (i=d;i<oldDepth;i++)
  4542 				{
  4543 					b=select (s);
  4544 					if (b)
  4545 					{	
  4546 						if ( getSelectedBranch()->countBranches()>0)
  4547 							s+=",bo:0";
  4548 						else	
  4549 							break;
  4550 					} else
  4551 						break;
  4552 				}	
  4553 
  4554 			// try to select the freshly built string
  4555 			found=select(s);
  4556 			d--;
  4557 		}
  4558 		return;
  4559 	}	
  4560 }
  4561 
  4562 void VymModel::selectPrevBranchInt()
  4563 {
  4564 	// Decrease number of branch
  4565 	if (selectionType()==TreeItem::Branch)
  4566 	{
  4567 		QString s=getSelectString();
  4568 		QString part;
  4569 		QString typ;
  4570 		QString num;
  4571 
  4572 		// Where am I? 
  4573 		part=s.section(",",-1);
  4574 		typ=part.left (3);
  4575 		num=part.right(part.length() - 3);
  4576 
  4577 		s=s.left (s.length() -num.length());
  4578 
  4579 		int n=num.toInt()-1;
  4580 		
  4581 		// Go to next lmo
  4582 		num=QString ("%1").arg(n);
  4583 		s=s+num;
  4584 		
  4585 		cout <<"SP::  s0="<<s.toStdString()<<endl;
  4586 
  4587 
  4588 		// Try to select this one
  4589 		if (n>=0 && select (s)) return;
  4590 
  4591 		// We have no direct precessor, 
  4592 		// try to decrease the parental number in order to
  4593 		// find a precessor with same depth
  4594 
  4595 		int d=getSelectedLMO()->getDepth();
  4596 		int oldDepth=d;
  4597 		int i;
  4598 		bool found=false;
  4599 		bool b;
  4600 		while (!found && d>0)
  4601 		{
  4602 			s=s.section (",",0,d-1);
  4603 			// replace substring of current depth in s with "1"
  4604 			part=s.section(",",-1);
  4605 			typ=part.left (3);
  4606 			num=part.right(part.length() - 3);
  4607 
  4608 			if (d>1)
  4609 			{
  4610 				// decrease number of parent
  4611 				num=QString ("%1").arg(num.toInt()-1);
  4612 				s=s.section (",",0,d-2) + ","+ typ+num;
  4613 			} else
  4614 			{
  4615 				// Special case, look at orientation
  4616 				if (getSelectedLMO()->getOrientation()==LinkableMapObj::RightOfCenter)
  4617 					num=QString ("%1").arg(num.toInt()-1);
  4618 				else	
  4619 					num=QString ("%1").arg(num.toInt()+1);
  4620 				s=typ+num;
  4621 			}	
  4622 
  4623 		cout <<"SP::  si="<<s.toStdString()<<endl;
  4624 			if (select(s))
  4625 				// pad to oldDepth, select the last branch for each depth
  4626 				for (i=d;i<oldDepth;i++)
  4627 				{
  4628 					b=select (s);
  4629 					if (b)
  4630 						if ( getSelectedBranch()->countBranches()>0)
  4631 							s+=",bo:"+ QString ("%1").arg( getSelectedBranch()->countBranches()-1 );
  4632 						else	
  4633 							break;
  4634 					else
  4635 						break;
  4636 				}	
  4637 			
  4638 			// try to select the freshly built string
  4639 			found=select(s);
  4640 			d--;
  4641 		}
  4642 		return;
  4643 	}	
  4644 }
  4645 
  4646 void VymModel::selectUpperBranch()
  4647 {
  4648 	if (selection.isBlocked() ) return;
  4649 
  4650 	BranchObj *bo=getSelectedBranch();
  4651 	if (bo && selectionType()==TreeItem::Branch)
  4652 	{
  4653 		if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  4654 			selectPrevBranchInt();
  4655 		else
  4656 			if (bo->getDepth()==1)
  4657 				selectNextBranchInt();
  4658 			else
  4659 				selectPrevBranchInt();
  4660 	}
  4661 }
  4662 
  4663 void VymModel::selectLowerBranch()
  4664 {
  4665 	if (selection.isBlocked() ) return;
  4666 
  4667 	BranchObj *bo=getSelectedBranch();
  4668 	if (bo && selectionType()==TreeItem::Branch)
  4669 	{
  4670 		if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  4671 			selectNextBranchInt();
  4672 		else
  4673 			if (bo->getDepth()==1)
  4674 				selectPrevBranchInt();
  4675 			else
  4676 				selectNextBranchInt();
  4677 	}			
  4678 }
  4679 
  4680 
  4681 void VymModel::selectLeftBranch()
  4682 {
  4683 	if (selection.isBlocked() ) return;
  4684 
  4685 	QItemSelection oldsel=selModel->selection();
  4686 
  4687 	BranchObj* par;
  4688 	LinkableMapObj *sel=getSelectedBranch();
  4689 	if (sel)
  4690 	{
  4691 		if (selectionType()== TreeItem::MapCenter)
  4692 		{
  4693 			QModelIndex ix=getSelectedIndex();
  4694 			selModel->select (index (rowCount(ix)-1,0,ix),QItemSelectionModel::ClearAndSelect  );
  4695 		} else
  4696 		{
  4697 			par=(BranchObj*)(sel->getParObj());
  4698 			if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
  4699 			{
  4700 				// right of center
  4701 				if (selectionType() == TreeItem::Branch ||
  4702 					selectionType() == TreeItem::Image)
  4703 				{
  4704 					QModelIndex ix=getSelectedIndex();
  4705 					ix=parent(ix);
  4706 					selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4707 				}
  4708 			} else
  4709 			{
  4710 				// left of center
  4711 				if (selectionType() == TreeItem::Branch )
  4712 				{
  4713 					selectLastSelectedBranch();
  4714 					return;
  4715 				}
  4716 			}
  4717 		}	
  4718 		updateSelection (oldsel);
  4719 	}
  4720 }
  4721 
  4722 void VymModel::selectRightBranch()
  4723 {
  4724 	if (selection.isBlocked() ) return;
  4725 
  4726 	QItemSelection oldsel=selModel->selection();
  4727 
  4728 	BranchObj* par;
  4729 	LinkableMapObj *sel=getSelectedBranch();
  4730 	if (sel)
  4731 	{
  4732 		if (selectionType()== TreeItem::MapCenter)
  4733 		{
  4734 			QModelIndex ix=getSelectedIndex();
  4735 			selModel->select (index (0,0,ix),QItemSelectionModel::ClearAndSelect  );
  4736 		} else
  4737 		{
  4738 			par=(BranchObj*)(sel->getParObj());
  4739 			if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
  4740 			{
  4741 				// right of center
  4742 				if (selectionType() == TreeItem::Branch )
  4743 				{
  4744 					selectLastSelectedBranch();
  4745 					return;
  4746 				}
  4747 			} else
  4748 			{
  4749 				// left of center
  4750 				if (selectionType() == TreeItem::Branch ||
  4751 					selectionType() == TreeItem::Image)
  4752 				{
  4753 					QModelIndex ix=getSelectedIndex();
  4754 					ix=parent(ix);
  4755 					selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4756 				}
  4757 			}
  4758 		}	
  4759 		updateSelection (oldsel);
  4760 	}
  4761 }
  4762 
  4763 void VymModel::selectFirstBranch()
  4764 {
  4765 	TreeItem *ti=getSelectedBranchItem();
  4766 	if (ti)
  4767 	{
  4768 		TreeItem *par=ti->parent();
  4769 		if (!par) return;
  4770 		TreeItem *ti2=par->getFirstBranch();
  4771 		if (ti2) {
  4772 			select(ti2);
  4773 			selection.update();
  4774 			ensureSelectionVisible();
  4775 			sendSelection();
  4776 		}
  4777 	}		
  4778 }
  4779 
  4780 void VymModel::selectLastBranch()
  4781 {
  4782 	TreeItem *ti=getSelectedBranchItem();
  4783 	if (ti)
  4784 	{
  4785 		TreeItem *par=ti->parent();
  4786 		if (!par) return;
  4787 		TreeItem *ti2=par->getLastBranch();
  4788 		if (ti2) {
  4789 			select(ti2);
  4790 			selection.update();
  4791 			ensureSelectionVisible();
  4792 			sendSelection();
  4793 		}
  4794 	}		
  4795 }
  4796 
  4797 void VymModel::selectLastSelectedBranch()
  4798 {
  4799 	TreeItem *ti=getSelectedBranchItem();
  4800 	if (ti)
  4801 	{
  4802 		ti=ti->getLastSelectedBranch();
  4803 		if (ti) select (ti);
  4804 	}		
  4805 }
  4806 
  4807 void VymModel::selectParent()
  4808 {
  4809 	TreeItem *ti=getSelectedItem();
  4810 	TreeItem *par;
  4811 	if (ti)
  4812 	{
  4813 		par=ti->parent();
  4814 		if (!par) return;
  4815 		select(par);
  4816 		selection.update();
  4817 		ensureSelectionVisible();
  4818 		sendSelection();
  4819 	}		
  4820 }
  4821 
  4822 TreeItem::Type VymModel::selectionType()
  4823 {
  4824 	QModelIndexList list=selModel->selectedIndexes();
  4825 	if (list.isEmpty()) return TreeItem::Undefined;	
  4826 	TreeItem *ti = static_cast<TreeItem*>(list.first().internalPointer());
  4827 	return ti->getType();
  4828 
  4829 }
  4830 
  4831 LinkableMapObj* VymModel::getSelectedLMO()
  4832 {
  4833 	QModelIndexList list=selModel->selectedIndexes();
  4834 	if (!list.isEmpty() )
  4835 	{
  4836 		TreeItem *ti = static_cast<TreeItem*>(list.first().internalPointer());
  4837 		TreeItem::Type type=ti->getType();
  4838 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter || type==TreeItem::Image)
  4839 		{
  4840 			return ti->getLMO();
  4841 		}	
  4842 	}
  4843 	return NULL;
  4844 }
  4845 
  4846 BranchObj* VymModel::getSelectedBranch()
  4847 {
  4848 	TreeItem *ti = getSelectedBranchItem();
  4849 	if (ti)
  4850 		return (BranchObj*)ti->getLMO();
  4851 	else	
  4852 		return NULL;
  4853 }
  4854 
  4855 TreeItem* VymModel::getSelectedBranchItem()
  4856 {
  4857 	QModelIndexList list=selModel->selectedIndexes();
  4858 	if (!list.isEmpty() )
  4859 	{
  4860 		TreeItem *ti = static_cast<TreeItem*>(list.first().internalPointer());
  4861 		TreeItem::Type type=ti->getType();
  4862 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter)
  4863 			return ti;
  4864 	}
  4865 	return NULL;
  4866 }
  4867 
  4868 TreeItem* VymModel::getSelectedItem()
  4869 {
  4870 	// FIXME this may not only be branch, but also float etc...
  4871 	BranchObj* bo=getSelectedBranch();
  4872 	if (bo) return bo->getTreeItem(); // FIXME VM get directly from treemodl
  4873 	return NULL;
  4874 }
  4875 
  4876 QModelIndex VymModel::getSelectedIndex()
  4877 {
  4878 	QModelIndexList list=selModel->selectedIndexes();
  4879 	if (list.isEmpty() )
  4880 		return QModelIndex();
  4881 	else
  4882 		return list.first();
  4883 }
  4884 
  4885 FloatImageObj* VymModel::getSelectedFloatImage()
  4886 {
  4887 	return selection.getFloatImage();	
  4888 }
  4889 
  4890 QString VymModel::getSelectString ()
  4891 {
  4892 	LinkableMapObj *lmo=getSelectedLMO();
  4893 	if (lmo) 
  4894 		return getSelectString(lmo);
  4895 	else
  4896 		return QString();
  4897 }
  4898 
  4899 QString VymModel::getSelectString (LinkableMapObj *lmo)	// FIXME VM needs to use TreeModel
  4900 {
  4901 	QString s;
  4902 	if (!lmo) return s;
  4903 	if (typeid(*lmo)==typeid(BranchObj) ||
  4904 		typeid(*lmo)==typeid(MapCenterObj) )
  4905 	{	
  4906 		LinkableMapObj *par=lmo->getParObj();
  4907 		if (par)
  4908 		{
  4909 			if (lmo->getDepth() ==1)
  4910 				// Mainbranch, return 
  4911 				s= "bo:" + QString("%1").arg(((BranchObj*)lmo)->getNum());
  4912 			else	
  4913 				// Branch, call myself recursively
  4914 				s= getSelectString(par) + ",bo:" + QString("%1").arg(((BranchObj*)lmo)->getNum());
  4915 		} else
  4916 		{
  4917 			// MapCenter
  4918 			int i=mapCenters.indexOf ((MapCenterObj*)lmo);
  4919 			if (i>=0) s=QString("mc:%1").arg(i);
  4920 		}	
  4921 	}	
  4922 	return s;
  4923 }
  4924