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