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