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