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