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