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