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