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