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