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