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