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