vymmodel.cpp
author insilmaril
Mon, 29 Jun 2009 10:27:42 +0000
changeset 777 8acac4fade1b
parent 776 25e634a7e1dc
child 779 1fb50e79661c
permissions -rw-r--r--
more fixes
     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->updateLink();
  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->updateLink();
  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->updateLink();
  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->updateLink();
  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 /*
  1767 	LinkableMapObj *sel=getSelectedLMO();
  1768 	if (sel &&
  1769 		(selectionType() == TreeItem::Branch || 
  1770 		selectionType() == TreeItem::MapCenter  ||
  1771 		selectionType() == TreeItem::Image ))
  1772 	{
  1773 		QString u= b ? "false" : "true";
  1774 		QString r=!b ? "false" : "true";
  1775 		
  1776 		saveState(
  1777 			sel,
  1778 			QString("setHideLinkUnselected (%1)").arg(u),
  1779 			sel, 
  1780 			QString("setHideLinkUnselected (%1)").arg(r),
  1781 			QString("Hide link of %1 if unselected").arg(getObjectName(sel))
  1782 		);	
  1783 		sel->setHideLinkUnselected(b);
  1784 	}
  1785 */
  1786 }
  1787 
  1788 void VymModel::setHideExport(bool b)
  1789 {
  1790 	TreeItem *ti=getSelectedItem();
  1791 	if (ti && 
  1792 		(ti->getType()==TreeItem::Image ||ti->isBranchLikeType()))
  1793 	{
  1794 		ti->setHideInExport (b);
  1795 		QString u= b ? "false" : "true";
  1796 		QString r=!b ? "false" : "true";
  1797 		
  1798 		saveState(
  1799 			ti,
  1800 			QString ("setHideExport (%1)").arg(u),
  1801 			ti,
  1802 			QString ("setHideExport (%1)").arg(r),
  1803 			QString ("Set HideExport flag of %1 to %2").arg(getObjectName(ti)).arg (r)
  1804 		);	
  1805 			emitDataHasChanged(ti);
  1806 			emitSelectionChanged();
  1807 		updateActions();
  1808 		reposition();
  1809 		// emitSelectionChanged();
  1810 		// FIXME-3 VM needed? scene()->update();
  1811 	}
  1812 }
  1813 
  1814 void VymModel::toggleHideExport()
  1815 {
  1816 	TreeItem *selti=getSelectedItem();
  1817 	if (selti)
  1818 		setHideExport ( !selti->hideInExport() );
  1819 }
  1820 
  1821 
  1822 void VymModel::copy()	
  1823 {
  1824 	TreeItem *selti=getSelectedItem();
  1825 	if (selti &&
  1826 		(selti->getType() == TreeItem::Branch || 
  1827 		selti->getType() == TreeItem::MapCenter  ||
  1828 		selti->getType() == TreeItem::Image ))
  1829 	{
  1830 		if (redosAvail == 0)
  1831 		{
  1832 			// Copy to history
  1833 			QString s=getSelectString(selti);
  1834 			saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",selti  );
  1835 			curClipboard=curStep;
  1836 		}
  1837 
  1838 		// Copy also to global clipboard, because we are at last step in history
  1839 		QString bakMapName(QString("history-%1").arg(curStep));
  1840 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1841 		copyDir (bakMapDir,clipboardDir );
  1842 
  1843 		clipboardEmpty=false;
  1844 		updateActions();
  1845 	}	    
  1846 }
  1847 
  1848 
  1849 void VymModel::pasteNoSave(const int &n)
  1850 {
  1851 	bool old=blockSaveState;
  1852 	blockSaveState=true;
  1853 	bool zippedOrg=zipped;
  1854 	if (redosAvail > 0 || n!=0)
  1855 	{
  1856 		// Use the "historical" buffer
  1857 		QString bakMapName(QString("history-%1").arg(n));
  1858 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1859 		load (bakMapDir+"/"+clipboardFile,ImportAdd, VymMap);
  1860 	} else
  1861 		// Use the global buffer
  1862 		load (clipboardDir+"/"+clipboardFile,ImportAdd, VymMap);
  1863 	zipped=zippedOrg;
  1864 	blockSaveState=old;
  1865 }
  1866 
  1867 void VymModel::paste()	
  1868 {   
  1869 	BranchItem *selbi=getSelectedBranchItem();
  1870 	if (selbi)
  1871 	{
  1872 		saveStateChangingPart(
  1873 			selbi,
  1874 			selbi,
  1875 			QString ("paste (%1)").arg(curClipboard),
  1876 			QString("Paste to %1").arg( getObjectName(selbi))
  1877 		);
  1878 		pasteNoSave(0);
  1879 		reposition();
  1880 	}
  1881 }
  1882 
  1883 void VymModel::cut()	
  1884 {
  1885 	TreeItem *selti=getSelectedItem();
  1886 	if ( selti && (selti->isBranchLikeType() ||selti->getType()==TreeItem::Image))
  1887 	{
  1888 		copy();
  1889 		deleteSelection();
  1890 		reposition();
  1891 	}
  1892 }
  1893 
  1894 void VymModel::moveUp()	
  1895 {
  1896 	BranchItem *selbi=getSelectedBranchItem();
  1897 	if (selbi)
  1898 	{
  1899 		if (!selbi->canMoveUp()) return;
  1900 		QString oldsel=getSelectString();
  1901 		if (relinkBranch (selbi,(BranchItem*)selbi->parent(),selbi->num()-1) )
  1902 
  1903 			saveState (getSelectString(),"moveDown ()",oldsel,"moveUp ()",QString("Move up %1").arg(getObjectName(selbi)));
  1904 	}
  1905 }
  1906 
  1907 void VymModel::moveDown()	
  1908 {
  1909 	BranchItem *selbi=getSelectedBranchItem();
  1910 	if (selbi)
  1911 	{
  1912 		if (!selbi->canMoveDown()) return;
  1913 		QString oldsel=getSelectString();
  1914 		if ( relinkBranch (selbi,(BranchItem*)selbi->parent(),selbi->num()+1) )
  1915 
  1916 			saveState (getSelectString(),"moveUp ()",oldsel,"moveDown ()",QString("Move down %1").arg(getObjectName(selbi)));
  1917 	}
  1918 }
  1919 
  1920 void VymModel::sortChildren()	// FIXME-2 not implemented yet
  1921 {
  1922 /*
  1923 	BranchObj* bo=getSelectedBranch();
  1924 	if (bo)
  1925 	{
  1926 		if(treeItem->branchCount()>1)
  1927 		{
  1928 			saveStateChangingPart(bo,bo, "sortChildren ()",QString("Sort children of %1").arg(getObjectName(bo)));
  1929 			bo->sortChildren();
  1930 			reposition();
  1931 			emitShowSelection();
  1932 		}
  1933 	}
  1934 */
  1935 }
  1936 
  1937 BranchItem* VymModel::createMapCenter()
  1938 {
  1939 	BranchItem *newbi=addMapCenter (QPointF (0,0) );
  1940 	return newbi;
  1941 }
  1942 
  1943 BranchItem* VymModel::createBranch(BranchItem *dst)	
  1944 {
  1945 	if (dst)
  1946 		return addNewBranchInt (dst,-2);
  1947 	else
  1948 		return NULL;
  1949 }
  1950 
  1951 ImageItem* VymModel::createImage(BranchItem *dst)
  1952 {
  1953 	if (dst)
  1954 	{
  1955 		QModelIndex parix;
  1956 		int n;
  1957 
  1958 		QList<QVariant> cData;
  1959 		cData << "new" << "undef"<<"undef";
  1960 
  1961 		ImageItem *newii=new ImageItem(cData) ;	
  1962 		//newii->setHeading (QApplication::translate("Heading of new image in map", "new image"));
  1963 
  1964 		emit (layoutAboutToBeChanged() );
  1965 
  1966 			parix=index(dst);
  1967 			n=dst->getRowNumAppend(newii);
  1968 			beginInsertRows (parix,n,n+1);
  1969 			dst->appendChild (newii);	
  1970 			endInsertRows ();
  1971 
  1972 		emit (layoutChanged() );
  1973 
  1974 		// save scroll state. If scrolled, automatically select
  1975 		// new branch in order to tmp unscroll parent...
  1976 		newii->createMapObj(mapScene);
  1977 		reposition();
  1978 		return newii;
  1979 	} 
  1980 	return NULL;
  1981 }
  1982 
  1983 BranchItem* VymModel::addMapCenter ()
  1984 {
  1985 	BranchItem *bi=addMapCenter (contextPos);
  1986 	updateActions();
  1987 	emitShowSelection();
  1988 	saveState (
  1989 		bi,
  1990 		"delete()",
  1991 		NULL,
  1992 		QString ("addMapCenter (%1,%2)").arg (contextPos.x()).arg(contextPos.y()),
  1993 		QString ("Adding MapCenter to (%1,%2)").arg (contextPos.x()).arg(contextPos.y())
  1994 	);	
  1995 	return bi;	
  1996 }
  1997 
  1998 BranchItem* VymModel::addMapCenter(QPointF absPos)	//FIXME-2 absPos not used in context menu?!
  1999 // createMapCenter could then probably be merged with createBranch
  2000 {
  2001 
  2002 	// Create TreeItem
  2003 	QModelIndex parix=index(rootItem);
  2004 
  2005 	int n=rootItem->branchCount();
  2006 
  2007 	emit (layoutAboutToBeChanged() );
  2008 	beginInsertRows (parix,n,n+1);
  2009 
  2010 	QList<QVariant> cData;
  2011 	cData << "VM:addMapCenter" << "undef"<<"undef";
  2012 	BranchItem *newbi=new BranchItem (cData);
  2013 	newbi->setHeading (QApplication::translate("Heading of mapcenter in new map", "New map"));
  2014 	rootItem->appendChild (newbi);
  2015 
  2016 	endInsertRows();
  2017 	emit (layoutChanged() );
  2018 
  2019 	// Create MapObj
  2020 	newbi->setPositionMode (MapItem::Absolute);
  2021 	newbi->createMapObj(mapScene);
  2022 		
  2023 	return newbi;
  2024 }
  2025 
  2026 BranchItem* VymModel::addNewBranchInt(BranchItem *dst,int num)	
  2027 {
  2028 	// Depending on pos:
  2029 	// -3		insert in children of parent  above selection 
  2030 	// -2		add branch to selection 
  2031 	// -1		insert in children of parent below selection 
  2032 	// 0..n		insert in children of parent at pos
  2033 
  2034 	// Create TreeItem
  2035 	QList<QVariant> cData;
  2036 	cData << "new" << "undef"<<"undef";
  2037 
  2038 	BranchItem *parbi;
  2039 	QModelIndex parix;
  2040 	int n;
  2041 	BranchItem *newbi=new BranchItem (cData);	
  2042 	newbi->setHeading (QApplication::translate("Heading of new branch in map", "new"));
  2043 
  2044 	emit (layoutAboutToBeChanged() );
  2045 
  2046 	if (num==-2)
  2047 	{
  2048 		parbi=dst;
  2049 		parix=index(parbi);
  2050 		n=parbi->getRowNumAppend (newbi);
  2051 		beginInsertRows (parix,n,n+1);	
  2052 		parbi->appendChild (newbi);	
  2053 		endInsertRows ();
  2054 	}else if (num==-1 || num==-3)
  2055 	{
  2056 		// insert below selection
  2057 		parbi=(BranchItem*)dst->parent();
  2058 		parix=index(parbi);  
  2059 		
  2060 		n=dst->childNumber() + (3+num)/2;	//-1 |-> 1;-3 |-> 0
  2061 		beginInsertRows (parix,n,n);	
  2062 		parbi->insertBranch(n,newbi);	
  2063 		endInsertRows ();
  2064 	}
  2065 	emit (layoutChanged() );
  2066 
  2067 	// save scroll state. If scrolled, automatically select
  2068 	// new branch in order to tmp unscroll parent...
  2069 	newbi->createMapObj(mapScene);
  2070 	reposition();
  2071 	return newbi;
  2072 }	
  2073 
  2074 BranchItem* VymModel::addNewBranch(int pos)
  2075 {
  2076 	// Different meaning than num in addNewBranchInt!
  2077 	// -1	add above
  2078 	//  0	add as child
  2079 	// +1	add below
  2080 	BranchItem *newbi=NULL;
  2081 	BranchItem *selbi=getSelectedBranchItem();
  2082 
  2083 	if (selbi)
  2084 	{
  2085 		// FIXME-3 setCursor (Qt::ArrowCursor);  //Still needed?
  2086 
  2087 		newbi=addNewBranchInt (selbi,pos-2);
  2088 
  2089 		if (newbi)
  2090 		{
  2091 			saveState(
  2092 				newbi,		
  2093 				"delete ()",
  2094 				selbi,
  2095 				QString ("addBranch (%1)").arg(pos),
  2096 				QString ("Add new branch to %1").arg(getObjectName(selbi)));	
  2097 
  2098 			reposition();
  2099 			// emitSelectionChanged(); FIXME-3
  2100 			latestAddedItem=newbi;
  2101 			// In Network mode, the client needs to know where the new branch is,
  2102 			// so we have to pass on this information via saveState.
  2103 			// TODO: Get rid of this positioning workaround
  2104 			/* FIXME-4  network problem:  QString ps=qpointfToString (newbo->getAbsPos());
  2105 			sendData ("selectLatestAdded ()");
  2106 			sendData (QString("move %1").arg(ps));
  2107 			sendSelection();
  2108 			*/
  2109 		}
  2110 	}	
  2111 	return newbi;
  2112 }
  2113 
  2114 
  2115 BranchItem* VymModel::addNewBranchBefore()	
  2116 {
  2117 	BranchItem *newbi=NULL;
  2118 	BranchItem *selbi=getSelectedBranchItem();
  2119 	if (selbi && selbi->getType()==TreeItem::Branch)
  2120 		 // We accept no MapCenter here, so we _have_ a parent
  2121 	{
  2122 		//QPointF p=bo->getRelPos();
  2123 
  2124 
  2125 		// add below selection
  2126 		newbi=addNewBranchInt (selbi,-1);
  2127 
  2128 		if (newbi)
  2129 		{
  2130 			//newbi->move2RelPos (p);
  2131 
  2132 			// Move selection to new branch
  2133 			relinkBranch (selbi,newbi,0);
  2134 
  2135 			saveState (newbi, "deleteKeepChildren ()", newbi, "addBranchBefore ()", 
  2136 				QString ("Add branch before %1").arg(getObjectName(selbi)));
  2137 
  2138 			// FIXME-3 needed? reposition();
  2139 			// emitSelectionChanged(); FIXME-3 
  2140 		}
  2141 	}	
  2142 	return newbi;
  2143 }
  2144 
  2145 bool VymModel::relinkBranch (BranchItem *branch, BranchItem *dst, int pos)
  2146 {
  2147 	if (branch && dst)
  2148 	{
  2149 		if (branch->depth()==0) 
  2150 		{
  2151 			cout <<"VM::relinkBranch  d=0 for "<<branch->getHeadingStd()<<endl;
  2152 		}
  2153 		emit (layoutAboutToBeChanged() );
  2154 		BranchItem *branchpi=(BranchItem*)branch->parent();
  2155 		// Remove at current position
  2156 		int n=branch->childNum();
  2157 		beginRemoveRows (index(branchpi),n,n);
  2158 		branchpi->removeChild (n);
  2159 		endRemoveRows();
  2160 
  2161 		if (pos<0 ||pos>dst->branchCount() ) pos=dst->branchCount();
  2162 
  2163 		// Append as last branch to dst
  2164 		if (dst->branchCount()==0)
  2165 			n=0;
  2166 		else	
  2167 			n=dst->getFirstBranch()->childNumber(); 
  2168 		beginInsertRows (index(dst),n+pos,n+pos);
  2169 		dst->insertBranch (pos,branch);
  2170 		endInsertRows();
  2171 
  2172 		// reset parObj, fonts, frame, etc in related LMO or other view-objects
  2173 		branch->updateStyles();
  2174 
  2175 		emit (layoutChanged() );
  2176 		reposition();	// both for moveUp/Down and relinking
  2177 		select (branch);
  2178 		return true;
  2179 	}
  2180 	return false;
  2181 }
  2182 
  2183 bool VymModel::relinkImage (ImageItem *image, BranchItem *dst)
  2184 {
  2185 	if (image && dst)
  2186 	{
  2187 		emit (layoutAboutToBeChanged() );
  2188 
  2189 		BranchItem *pi=(BranchItem*)(image->parent());
  2190 		QString oldParString=getSelectString (pi);
  2191 		// Remove at current position
  2192 		int n=image->childNum();
  2193 		beginRemoveRows (index(pi),n,n);
  2194 		pi->removeChild (n);
  2195 		endRemoveRows();
  2196 
  2197 		// Add at dst
  2198 		QModelIndex dstix=index(dst);
  2199 		n=dst->getRowNumAppend (image);
  2200 		beginInsertRows (dstix,n,n+1);	
  2201 		dst->appendChild (image);	
  2202 		endInsertRows ();
  2203 
  2204 		// Set new parent also for lmo
  2205 		if (image->getLMO() && dst->getLMO() )
  2206 			image->getLMO()->setParObj (dst->getLMO() );
  2207 
  2208 		emit (layoutChanged() );
  2209 		saveState(
  2210 			image,
  2211 			QString("relinkTo (\"%1\")").arg(oldParString), 
  2212 			image,
  2213 			QString ("relinkTo (\"%1\")").arg(getSelectString (dst)),
  2214 			QString ("Relink floatimage to %1").arg(getObjectName(dst)));
  2215 		return true;	
  2216 	}
  2217 	return false;
  2218 }
  2219 
  2220 void VymModel::deleteSelection()
  2221 {
  2222 	BranchItem *selbi=getSelectedBranchItem();
  2223 
  2224 	if (selbi && selbi->isBranchLikeType() )
  2225 	{
  2226 		unselect();
  2227 		saveStateRemovingPart (selbi, QString ("Delete %1").arg(getObjectName(selbi)));
  2228 
  2229 		TreeItem *pi=deleteItem (selbi);
  2230 		if (pi)
  2231 		{
  2232 			select (pi);
  2233 			emitShowSelection();
  2234 		}
  2235 		return;
  2236 	}
  2237 	ImageItem *ii=getSelectedImageItem();
  2238 	if (ii)
  2239 	{
  2240 		BranchItem *pi=(BranchItem*)(ii->parent());
  2241 		saveStateChangingPart(
  2242 			pi, 
  2243 			ii,
  2244 			"delete ()",
  2245 			QString("Delete %1").arg(getObjectName(ii))
  2246 		);
  2247 		unselect();
  2248 		deleteItem (ii);
  2249 		select (pi);
  2250 		reposition();
  2251 		emitShowSelection();
  2252 		return;
  2253 	}
  2254 }
  2255 
  2256 void VymModel::deleteKeepChildren()	//FIXME-2 does not work yet for mapcenters
  2257 
  2258 {
  2259 	BranchItem *selbi=getSelectedBranchItem();
  2260 	BranchItem *pi;
  2261 	if (selbi)
  2262 	{
  2263 		// Don't use this on mapcenter
  2264 		if (selbi->depth()<2) return;
  2265 
  2266 		pi=(BranchItem*)(selbi->parent());
  2267 		// Check if we have childs at all to keep
  2268 		if (selbi->branchCount()==0) 
  2269 		{
  2270 			deleteSelection();
  2271 			return;
  2272 		}
  2273 
  2274 		QPointF p;
  2275 		if (selbi->getLMO()) p=selbi->getLMO()->getRelPos();
  2276 		saveStateChangingPart(
  2277 			pi,
  2278 			selbi,
  2279 			"deleteKeepChildren ()",
  2280 			QString("Remove %1 and keep its children").arg(getObjectName(selbi))
  2281 		);
  2282 
  2283 		QString sel=getSelectString(selbi);
  2284 		unselect();
  2285 		int pos=selbi->num();
  2286 		BranchItem *bi=selbi->getFirstBranch();
  2287 		while (bi)
  2288 		{
  2289 			relinkBranch (bi,pi,pos);
  2290 			bi=selbi->getFirstBranch();
  2291 			pos++;
  2292 		}
  2293 		deleteItem (selbi);
  2294 		reposition();
  2295 		select (sel);
  2296 		BranchObj *bo=getSelectedBranchObj();
  2297 		if (bo) 
  2298 		{
  2299 			bo->move2RelPos (p);
  2300 			reposition();
  2301 		}
  2302 	}	
  2303 }
  2304 
  2305 void VymModel::deleteChildren()		
  2306 
  2307 {
  2308 	BranchItem *selbi=getSelectedBranchItem();
  2309 	if (selbi)
  2310 	{		
  2311 		saveStateChangingPart(
  2312 			selbi, 
  2313 			selbi,
  2314 			"deleteChildren ()",
  2315 			QString( "Remove children of branch %1").arg(getObjectName(selbi))
  2316 		);
  2317 		emit (layoutAboutToBeChanged() );
  2318 
  2319 		QModelIndex ix=index (selbi);
  2320 		int n=selbi->branchCount()-1;
  2321 		beginRemoveRows (ix,0,n);
  2322 		removeRows (0,n+1,ix);
  2323 		endRemoveRows();
  2324 		emit (layoutChanged() );
  2325 		reposition();
  2326 	}	
  2327 }
  2328 
  2329 TreeItem* VymModel::deleteItem (TreeItem *ti)
  2330 {
  2331 	if (ti)
  2332 	{
  2333 		TreeItem *pi=ti->parent();
  2334 		QModelIndex parentIndex=index(pi);
  2335 
  2336 		emit (layoutAboutToBeChanged() );
  2337 
  2338 		int n=ti->childNum();
  2339 		beginRemoveRows (parentIndex,n,n);
  2340 		removeRows (n,1,parentIndex);
  2341 		endRemoveRows();
  2342 		reposition();
  2343 
  2344 		emit (layoutChanged() );
  2345 		if (pi->depth()>0) return pi;
  2346 	}	
  2347 	return NULL;
  2348 }
  2349 
  2350 bool VymModel::scrollBranch(BranchItem *bi)
  2351 {
  2352 	if (bi)	
  2353 	{
  2354 		if (bi->isScrolled()) return false;
  2355 		if (bi->branchCount()==0) return false;
  2356 		if (bi->depth()==0) return false;
  2357 		if (bi->toggleScroll())
  2358 		{
  2359 			QString u,r;
  2360 			r="scroll";
  2361 			u="unscroll";
  2362 			saveState(
  2363 				bi,
  2364 				QString ("%1 ()").arg(u),
  2365 				bi,
  2366 				QString ("%1 ()").arg(r),
  2367 				QString ("%1 %2").arg(r).arg(getObjectName(bi))
  2368 			);
  2369 			emitDataHasChanged(bi);
  2370 			emitSelectionChanged();
  2371 			mapScene->update(); //Needed for _quick_ update,  even in 1.13.x //FIXME-3 force update via signal...
  2372 			return true;
  2373 		}
  2374 	}	
  2375 	return false;
  2376 }
  2377 
  2378 bool VymModel::unscrollBranch(BranchItem *bi)
  2379 {
  2380 	if (bi)
  2381 	{
  2382 		if (!bi->isScrolled()) return false;
  2383 		if (bi->branchCount()==0) return false;
  2384 		if (bi->depth()==0) return false;
  2385 
  2386 		QString u,r;
  2387 		u="scroll";
  2388 		r="unscroll";
  2389 		saveState(
  2390 			bi,
  2391 			QString ("%1 ()").arg(u),
  2392 			bi,
  2393 			QString ("%1 ()").arg(r),
  2394 			QString ("%1 %2").arg(r).arg(getObjectName(bi))
  2395 		);
  2396 		bi->toggleScroll();
  2397 		emitDataHasChanged(bi);
  2398 		emitSelectionChanged();
  2399 
  2400 		mapScene->update(); //Needed for _quick_ update,  even in 1.13.x //FIXME-3 force update via signal...
  2401 		return true;
  2402 	}	
  2403 	return false;
  2404 }
  2405 
  2406 void VymModel::toggleScroll()	
  2407 {
  2408 	BranchItem *bi=(BranchItem*)getSelectedBranchItem();
  2409 	if (bi && bi->isBranchLikeType() )
  2410 	{
  2411 		if (bi->isScrolled())
  2412 			unscrollBranch (bi);
  2413 		else
  2414 			scrollBranch (bi);
  2415 	}
  2416 	// saveState is called in above functions
  2417 }
  2418 
  2419 void VymModel::unscrollChildren() 	// FIXME-2	first, next moved to vymmodel
  2420 
  2421 {
  2422 /*
  2423 	BranchObj *bo=getSelectedBranch();
  2424 	if (bo)
  2425 	{
  2426 		bo->first();
  2427 		while (bo) 
  2428 		{
  2429 			if (bo->isScrolled()) unscrollBranch (bo);
  2430 			bo=bo->next();
  2431 		}
  2432 	}	
  2433 */	
  2434 }
  2435 
  2436 void VymModel::emitExpandAll()
  2437 {
  2438 	emit (expandAll() );
  2439 }
  2440 
  2441 void VymModel::toggleStandardFlag (const QString &name, FlagRow *master)
  2442 {
  2443 	BranchItem *bi=getSelectedBranchItem();
  2444 	if (bi) 
  2445 	{
  2446 		QString u,r;
  2447 		if (bi->isActiveStandardFlag(name))
  2448 		{
  2449 			r="unsetFlag";
  2450 			u="setFlag";
  2451 		}	
  2452 		else
  2453 		{
  2454 			u="unsetFlag";
  2455 			r="setFlag";
  2456 		}	
  2457 		saveState(
  2458 			bi,
  2459 			QString("%1 (\"%2\")").arg(u).arg(name), 
  2460 			bi,
  2461 			QString("%1 (\"%2\")").arg(r).arg(name),
  2462 			QString("Toggling standard flag \"%1\" of %2").arg(name).arg(getObjectName(bi)));
  2463 			bi->toggleStandardFlag (name, master);
  2464 		reposition();
  2465 		emitSelectionChanged();	
  2466 	}
  2467 }
  2468 
  2469 void VymModel::addFloatImage (const QPixmap &img) //FIXME-2 drag & drop
  2470 {
  2471 /*
  2472 	BranchObj *bo=getSelectedBranch();
  2473 	if (bo)
  2474   {
  2475 	FloatImageObj *fio=bo->addFloatImage();
  2476     fio->load(img);
  2477     fio->setOriginalFilename("No original filename (image added by dropevent)");	
  2478 	QString s=getSelectString(bo);
  2479 	saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",fio  );
  2480 	saveState (fio,"delete ()", bo,QString("paste(%1)").arg(curStep),"Pasting dropped image");
  2481     reposition();
  2482     // FIXME-3 VM needed? scene()->update();
  2483   }
  2484 */
  2485 }
  2486 
  2487 
  2488 void VymModel::colorBranch (QColor c)	
  2489 {
  2490 	BranchItem *selbi=getSelectedBranchItem();
  2491 	if (selbi)
  2492 	{
  2493 		saveState(
  2494 			selbi, 
  2495 			QString ("colorBranch (\"%1\")").arg(selbi->getHeadingColor().name()),
  2496 			selbi,
  2497 			QString ("colorBranch (\"%1\")").arg(c.name()),
  2498 			QString("Set color of %1 to %2").arg(getObjectName(selbi)).arg(c.name())
  2499 		);	
  2500 		selbi->setHeadingColor(c); // color branch
  2501 	}
  2502 }
  2503 
  2504 void VymModel::colorSubtree (QColor c) 
  2505 {
  2506 	BranchItem *selbi=getSelectedBranchItem();
  2507 	if (selbi)
  2508 	{
  2509 		saveStateChangingPart(
  2510 			selbi,
  2511 			selbi,
  2512 			QString ("colorSubtree (\"%1\")").arg(c.name()),
  2513 			QString ("Set color of %1 and children to %2").arg(getObjectName(selbi)).arg(c.name())
  2514 		);	
  2515 		BranchItem *prev=NULL;
  2516 		BranchItem *cur=selbi;
  2517 		while (cur) 
  2518 		{
  2519 			cur->setHeadingColor(c); // color links, color children
  2520 			cur=next (cur,prev,selbi);
  2521 		}	
  2522 
  2523 	}
  2524 }
  2525 
  2526 QColor VymModel::getCurrentHeadingColor()	
  2527 {
  2528 	BranchItem *selbi=getSelectedBranchItem();
  2529 	if (selbi)	return selbi->getHeadingColor();
  2530 		
  2531 	QMessageBox::warning(0,"Warning","Can't get color of heading,\nthere's no branch selected");
  2532 	return Qt::black;
  2533 }
  2534 
  2535 
  2536 
  2537 void VymModel::editURL()	
  2538 {
  2539 	TreeItem *selti=getSelectedItem();
  2540 	if (selti)
  2541 	{		
  2542 		bool ok;
  2543 		QString text = QInputDialog::getText(
  2544 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2545 				selti->getURL(), &ok, NULL);
  2546 		if ( ok) 
  2547 			// user entered something and pressed OK
  2548 			setURL(text);
  2549 	}
  2550 }
  2551 
  2552 void VymModel::editLocalURL()
  2553 {
  2554 	TreeItem *selti=getSelectedItem();
  2555 	if (selti)
  2556 	{		
  2557 		QStringList filters;
  2558 		filters <<"All files (*)";
  2559 		filters << tr("Text","Filedialog") + " (*.txt)";
  2560 		filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
  2561 		filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
  2562 		filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
  2563 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Set URL to a local file"));
  2564 		fd->setFilters (filters);
  2565 		fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
  2566 		fd->setDirectory (lastFileDir);
  2567 		if (! selti->getVymLink().isEmpty() )
  2568 			fd->selectFile( selti->getURL() );
  2569 		fd->show();
  2570 
  2571 		if ( fd->exec() == QDialog::Accepted )
  2572 		{
  2573 			lastFileDir=QDir (fd->directory().path());
  2574 			setURL (fd->selectedFile() );
  2575 		}
  2576 	}
  2577 }
  2578 
  2579 
  2580 void VymModel::editHeading2URL() 
  2581 {
  2582 	TreeItem *selti=getSelectedItem();
  2583 	if (selti)
  2584 		setURL (selti->getHeading());
  2585 }	
  2586 
  2587 void VymModel::editBugzilla2URL()	
  2588 {
  2589 	TreeItem *selti=getSelectedItem();
  2590 	if (selti)
  2591 	{		
  2592 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+selti->getHeading();
  2593 		setURL (url);
  2594 	}
  2595 }	
  2596 
  2597 void VymModel::editFATE2URL()
  2598 {
  2599 	TreeItem *selti=getSelectedItem();
  2600 	if (selti)
  2601 	{		
  2602 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+selti->getHeading();
  2603 		saveState(
  2604 			selti,
  2605 			"setURL (\""+selti->getURL()+"\")",
  2606 			selti,
  2607 			"setURL (\""+url+"\")",
  2608 			QString("Use heading of %1 as link to FATE").arg(getObjectName(selti))
  2609 		);	
  2610 		selti->setURL (url);
  2611 		// FIXME-4 updateActions();
  2612 	}
  2613 }	
  2614 
  2615 void VymModel::editVymLink()
  2616 {
  2617 	BranchItem *bi=getSelectedBranchItem();
  2618 	if (bi)
  2619 	{		
  2620 		QStringList filters;
  2621 		filters <<"VYM map (*.vym)";
  2622 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Link to another map"));
  2623 		fd->setFilters (filters);
  2624 		fd->setCaption(vymName+" - " +tr("Link to another map"));
  2625 		fd->setDirectory (lastFileDir);
  2626 		if (! bi->getVymLink().isEmpty() )
  2627 			fd->selectFile( bi->getVymLink() );
  2628 		fd->show();
  2629 
  2630 		QString fn;
  2631 		if ( fd->exec() == QDialog::Accepted )
  2632 		{
  2633 			lastFileDir=QDir (fd->directory().path());
  2634 			saveState(
  2635 				bi,
  2636 				"setVymLink (\""+bi->getVymLink()+"\")",
  2637 				bi,
  2638 				"setVymLink (\""+fd->selectedFile()+"\")",
  2639 				QString("Set vymlink of %1 to %2").arg(getObjectName(bi)).arg(fd->selectedFile())
  2640 			);	
  2641 			setVymLink (fd->selectedFile() );	// FIXME-2 ok?
  2642 		}
  2643 	}
  2644 }
  2645 
  2646 void VymModel::setVymLink (const QString &s)	// FIXME-3 no savestate?
  2647 {
  2648 	// Internal function, no saveState needed
  2649 	BranchItem *bi=getSelectedBranchItem();
  2650 	if (bi)
  2651 	{
  2652 		bi->setVymLink(s);
  2653 		reposition();
  2654 		updateActions();
  2655 		//emitSelectionChanged();
  2656 	}
  2657 }
  2658 
  2659 void VymModel::deleteVymLink()
  2660 {
  2661 	BranchItem *bi=getSelectedBranchItem();
  2662 	if (bi)
  2663 	{		
  2664 		saveState(
  2665 			bi,
  2666 			"setVymLink (\""+bi->getVymLink()+"\")", 
  2667 			bi,
  2668 			"setVymLink (\"\")",
  2669 			QString("Unset vymlink of %1").arg(getObjectName(bi))
  2670 		);	
  2671 		bi->setVymLink ("" );
  2672 		updateActions();
  2673 		reposition();
  2674 	}
  2675 }
  2676 
  2677 QString VymModel::getVymLink()
  2678 {
  2679 	BranchItem *bi=getSelectedBranchItem();
  2680 	if (bi)
  2681 		return bi->getVymLink();
  2682 	else	
  2683 		return "";
  2684 	
  2685 }
  2686 
  2687 QStringList VymModel::getVymLinks()	
  2688 {
  2689 	QStringList links;
  2690 	BranchItem *selbi=getSelectedBranchItem();
  2691 	BranchItem *cur=selbi;
  2692 	BranchItem *prev=NULL;
  2693 	while (cur) 
  2694 	{
  2695 		if (!cur->getVymLink().isEmpty()) links.append( cur->getVymLink());
  2696 		cur=next (cur,prev,selbi);
  2697 	}	
  2698 	return links;
  2699 }
  2700 
  2701 
  2702 void VymModel::followXLink(int i)	// FIXME-2
  2703 {
  2704 	i=0;
  2705 	/*
  2706 	BranchObj *bo=getSelectedBranch();
  2707 	if (bo)
  2708 	{
  2709 		bo=bo->XLinkTargetAt(i);
  2710 		if (bo) 
  2711 		{
  2712 			selection.select(bo);
  2713 			emitShowSelection();
  2714 		}
  2715 	}
  2716 	*/
  2717 }
  2718 
  2719 void VymModel::editXLink(int i)	// FIXME-2 VM missing saveState
  2720 {
  2721 	i=0;
  2722 	/*
  2723 	BranchObj *bo=getSelectedBranch();
  2724 	if (bo)
  2725 	{
  2726 		XLinkObj *xlo=bo->XLinkAt(i);
  2727 		if (xlo) 
  2728 		{
  2729 			EditXLinkDialog dia;
  2730 			dia.setXLink (xlo);
  2731 			dia.setSelection(bo);
  2732 			if (dia.exec() == QDialog::Accepted)
  2733 			{
  2734 				if (dia.useSettingsGlobal() )
  2735 				{
  2736 					setMapDefXLinkColor (xlo->getColor() );
  2737 					setMapDefXLinkWidth (xlo->getWidth() );
  2738 				}
  2739 				if (dia.deleteXLink())
  2740 					bo->deleteXLinkAt(i);
  2741 			}
  2742 		}	
  2743 	}
  2744 */	
  2745 }
  2746 
  2747 
  2748 
  2749 
  2750 
  2751 //////////////////////////////////////////////
  2752 // Scripting
  2753 //////////////////////////////////////////////
  2754 
  2755 void VymModel::parseAtom(const QString &atom)
  2756 {
  2757 	TreeItem* selti=getSelectedItem();
  2758 	BranchItem *selbi=getSelectedBranchItem();
  2759 	QString s,t;
  2760 	double x,y;
  2761 	int n;
  2762 	bool b,ok;
  2763 
  2764 	// Split string s into command and parameters
  2765 	parser.parseAtom (atom);
  2766 	QString com=parser.getCommand();
  2767 	
  2768 	// External commands
  2769 	/////////////////////////////////////////////////////////////////////
  2770 	if (com=="addBranch")
  2771 	{
  2772 		if (!selti)
  2773 		{
  2774 			parser.setError (Aborted,"Nothing selected");
  2775 		} else if (! selbi )
  2776 		{				  
  2777 			parser.setError (Aborted,"Type of selection is not a branch");
  2778 		} else 
  2779 		{	
  2780 			QList <int> pl;
  2781 			pl << 0 <<1;
  2782 			if (parser.checkParCount(pl))
  2783 			{
  2784 				if (parser.parCount()==0)
  2785 					addNewBranch (0);
  2786 				else
  2787 				{
  2788 					n=parser.parInt (ok,0);
  2789 					if (ok ) addNewBranch (n);
  2790 				}
  2791 			}
  2792 		}
  2793 	/////////////////////////////////////////////////////////////////////
  2794 	} else if (com=="addBranchBefore")
  2795 	{
  2796 		if (!selti)
  2797 		{
  2798 			parser.setError (Aborted,"Nothing selected");
  2799 		} else if (! selbi )
  2800 		{				  
  2801 			parser.setError (Aborted,"Type of selection is not a branch");
  2802 		} else 
  2803 		{	
  2804 			if (parser.parCount()==0)
  2805 			{
  2806 				addNewBranchBefore ();
  2807 			}	
  2808 		}
  2809 	/////////////////////////////////////////////////////////////////////
  2810 	} else if (com==QString("addMapCenter"))
  2811 	{
  2812 		if (parser.checkParCount(2))
  2813 		{
  2814 			x=parser.parDouble (ok,0);
  2815 			if (ok)
  2816 			{
  2817 				y=parser.parDouble (ok,1);
  2818 				if (ok) addMapCenter (QPointF(x,y));
  2819 			}
  2820 		}	
  2821 	/////////////////////////////////////////////////////////////////////
  2822 	} else if (com==QString("addMapReplace"))
  2823 	{
  2824 		if (!selti)
  2825 		{
  2826 			parser.setError (Aborted,"Nothing selected");
  2827 		} else if (! selbi )
  2828 		{				  
  2829 			parser.setError (Aborted,"Type of selection is not a branch");
  2830 		} else if (parser.checkParCount(1))
  2831 		{
  2832 			//s=parser.parString (ok,0);	// selection
  2833 			t=parser.parString (ok,0);	// path to map
  2834 			if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2835 			addMapReplaceInt(getSelectString(selbi),t);	
  2836 		}
  2837 	/////////////////////////////////////////////////////////////////////
  2838 	} else if (com==QString("addMapInsert"))
  2839 	{
  2840 		if (!selti)
  2841 		{
  2842 			parser.setError (Aborted,"Nothing selected");
  2843 		} else if (! selbi )
  2844 		{				  
  2845 			parser.setError (Aborted,"Type of selection is not a branch");
  2846 		} else 
  2847 		{	
  2848 			if (parser.checkParCount(2))
  2849 			{
  2850 				t=parser.parString (ok,0);	// path to map
  2851 				n=parser.parInt(ok,1);		// position
  2852 				if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2853 				addMapInsertInt(t,n);	
  2854 			}
  2855 		}
  2856 	/////////////////////////////////////////////////////////////////////
  2857 	} else if (com=="clearFlags")	
  2858 	{
  2859 		if (!selti )
  2860 		{
  2861 			parser.setError (Aborted,"Nothing selected");
  2862 		} else if (! selbi )
  2863 		{				  
  2864 			parser.setError (Aborted,"Type of selection is not a branch");
  2865 		} else if (parser.checkParCount(0))
  2866 		{
  2867 			selbi->deactivateAllStandardFlags();	
  2868 		}
  2869 	/////////////////////////////////////////////////////////////////////
  2870 	} else if (com=="colorBranch")
  2871 	{
  2872 		if (!selti)
  2873 		{
  2874 			parser.setError (Aborted,"Nothing selected");
  2875 		} else if (! selbi )
  2876 		{				  
  2877 			parser.setError (Aborted,"Type of selection is not a branch");
  2878 		} else if (parser.checkParCount(1))
  2879 		{	
  2880 			QColor c=parser.parColor (ok,0);
  2881 			if (ok) colorBranch (c);
  2882 		}	
  2883 	/////////////////////////////////////////////////////////////////////
  2884 	} else if (com=="colorSubtree")
  2885 	{
  2886 		if (!selti)
  2887 		{
  2888 			parser.setError (Aborted,"Nothing selected");
  2889 		} else if (! selbi )
  2890 		{				  
  2891 			parser.setError (Aborted,"Type of selection is not a branch");
  2892 		} else if (parser.checkParCount(1))
  2893 		{	
  2894 			QColor c=parser.parColor (ok,0);
  2895 			if (ok) colorSubtree (c);
  2896 		}	
  2897 	/////////////////////////////////////////////////////////////////////
  2898 	} else if (com=="copy")
  2899 	{
  2900 		if (!selti)
  2901 		{
  2902 			parser.setError (Aborted,"Nothing selected");
  2903 		} else if ( selectionType()!=TreeItem::Branch  && 
  2904 					selectionType()!=TreeItem::MapCenter  &&
  2905 					selectionType()!=TreeItem::Image )
  2906 		{				  
  2907 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  2908 		} else if (parser.checkParCount(0))
  2909 		{	
  2910 			copy();
  2911 		}	
  2912 	/////////////////////////////////////////////////////////////////////
  2913 	} else if (com=="cut")
  2914 	{
  2915 		if (!selti)
  2916 		{
  2917 			parser.setError (Aborted,"Nothing selected");
  2918 		} else if ( selectionType()!=TreeItem::Branch  && 
  2919 					selectionType()!=TreeItem::MapCenter  &&
  2920 					selectionType()!=TreeItem::Image )
  2921 		{				  
  2922 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  2923 		} else if (parser.checkParCount(0))
  2924 		{	
  2925 			cut();
  2926 		}	
  2927 	/////////////////////////////////////////////////////////////////////
  2928 	} else if (com=="delete")
  2929 	{
  2930 		if (!selti)
  2931 		{
  2932 			parser.setError (Aborted,"Nothing selected");
  2933 		} 
  2934 		/*else if (selectionType() != TreeItem::Branch && selectionType() != TreeItem::Image )
  2935 		{
  2936 			parser.setError (Aborted,"Type of selection is wrong.");
  2937 		} 
  2938 		*/
  2939 		else if (parser.checkParCount(0))
  2940 		{	
  2941 			deleteSelection();
  2942 		}	
  2943 	/////////////////////////////////////////////////////////////////////
  2944 	} else if (com=="deleteKeepChildren")
  2945 	{
  2946 		if (!selti)
  2947 		{
  2948 			parser.setError (Aborted,"Nothing selected");
  2949 		} else if (! selbi )
  2950 		{
  2951 			parser.setError (Aborted,"Type of selection is not a branch");
  2952 		} else if (parser.checkParCount(0))
  2953 		{	
  2954 			deleteKeepChildren();
  2955 		}	
  2956 	/////////////////////////////////////////////////////////////////////
  2957 	} else if (com=="deleteChildren")
  2958 	{
  2959 		if (!selti)
  2960 		{
  2961 			parser.setError (Aborted,"Nothing selected");
  2962 		} else if (! selbi)
  2963 		{
  2964 			parser.setError (Aborted,"Type of selection is not a branch");
  2965 		} else if (parser.checkParCount(0))
  2966 		{	
  2967 			deleteChildren();
  2968 		}	
  2969 	/////////////////////////////////////////////////////////////////////
  2970 	} else if (com=="exportASCII")
  2971 	{
  2972 		QString fname="";
  2973 		ok=true;
  2974 		if (parser.parCount()>=1)
  2975 			// Hey, we even have a filename
  2976 			fname=parser.parString(ok,0); 
  2977 		if (!ok)
  2978 		{
  2979 			parser.setError (Aborted,"Could not read filename");
  2980 		} else
  2981 		{
  2982 				exportASCII (fname,false);
  2983 		}
  2984 	/////////////////////////////////////////////////////////////////////
  2985 	} else if (com=="exportImage")
  2986 	{
  2987 		QString fname="";
  2988 		ok=true;
  2989 		if (parser.parCount()>=2)
  2990 			// Hey, we even have a filename
  2991 			fname=parser.parString(ok,0); 
  2992 		if (!ok)
  2993 		{
  2994 			parser.setError (Aborted,"Could not read filename");
  2995 		} else
  2996 		{
  2997 			QString format="PNG";
  2998 			if (parser.parCount()>=2)
  2999 			{
  3000 				format=parser.parString(ok,1);
  3001 			}
  3002 			exportImage (fname,false,format);
  3003 		}
  3004 	/////////////////////////////////////////////////////////////////////
  3005 	} else if (com=="exportXHTML")
  3006 	{
  3007 		QString fname="";
  3008 		ok=true;
  3009 		if (parser.parCount()>=2)
  3010 			// Hey, we even have a filename
  3011 			fname=parser.parString(ok,1); 
  3012 		if (!ok)
  3013 		{
  3014 			parser.setError (Aborted,"Could not read filename");
  3015 		} else
  3016 		{
  3017 			exportXHTML (fname,false);
  3018 		}
  3019 	/////////////////////////////////////////////////////////////////////
  3020 	} else if (com=="exportXML")
  3021 	{
  3022 		QString fname="";
  3023 		ok=true;
  3024 		if (parser.parCount()>=2)
  3025 			// Hey, we even have a filename
  3026 			fname=parser.parString(ok,1); 
  3027 		if (!ok)
  3028 		{
  3029 			parser.setError (Aborted,"Could not read filename");
  3030 		} else
  3031 		{
  3032 			exportXML (fname,false);
  3033 		}
  3034 	/////////////////////////////////////////////////////////////////////
  3035 	} else if (com=="importDir")
  3036 	{
  3037 		if (!selti)
  3038 		{
  3039 			parser.setError (Aborted,"Nothing selected");
  3040 		} else if (! selbi )
  3041 		{				  
  3042 			parser.setError (Aborted,"Type of selection is not a branch");
  3043 		} else if (parser.checkParCount(1))
  3044 		{
  3045 			s=parser.parString(ok,0);
  3046 			if (ok) importDirInt(s);
  3047 		}	
  3048 	/////////////////////////////////////////////////////////////////////
  3049 	} else if (com=="relinkTo")
  3050 	{
  3051 		if (!selti)
  3052 		{
  3053 			parser.setError (Aborted,"Nothing selected");
  3054 		} else if ( selbi)
  3055 		{
  3056 			if (parser.checkParCount(4))
  3057 			{
  3058 				// 0	selectstring of parent
  3059 				// 1	num in parent (for branches)
  3060 				// 2,3	x,y of mainbranch or mapcenter
  3061 				s=parser.parString(ok,0);
  3062 				TreeItem *dst=findBySelectString (s);
  3063 				if (dst)
  3064 				{	
  3065 					if (dst->getType()==TreeItem::Branch) 
  3066 					{
  3067 						// Get number in parent
  3068 						n=parser.parInt (ok,1);
  3069 						if (ok)
  3070 						{
  3071 							relinkBranch (selbi,(BranchItem*)dst,n);
  3072 							emitSelectionChanged();
  3073 						}	
  3074 					} else if (dst->getType()==TreeItem::MapCenter) 
  3075 					{
  3076 						relinkBranch (selbi,(BranchItem*)dst);
  3077 						// Get coordinates of mainbranch
  3078 						x=parser.parDouble(ok,2);
  3079 						if (ok)
  3080 						{
  3081 							y=parser.parDouble(ok,3);
  3082 							if (ok) 
  3083 							{
  3084 								if (selbi->getLMO()) selbi->getLMO()->move (x,y);
  3085 								emitSelectionChanged();
  3086 							}
  3087 						}
  3088 					}	
  3089 				}	
  3090 			}	
  3091 		} else if ( selti->getType() == TreeItem::Image) 
  3092 		{
  3093 			if (parser.checkParCount(1))
  3094 			{
  3095 				// 0	selectstring of parent
  3096 				s=parser.parString(ok,0);
  3097 				TreeItem *dst=findBySelectString (s);
  3098 				if (dst)
  3099 				{	
  3100 					if (dst->isBranchLikeType())
  3101 						relinkImage ( ((ImageItem*)selti),(BranchItem*)dst);
  3102 				} else	
  3103 					parser.setError (Aborted,"Destination is not a branch");
  3104 			}		
  3105 		} else
  3106 			parser.setError (Aborted,"Type of selection is not a floatimage or branch");
  3107 	/////////////////////////////////////////////////////////////////////
  3108 	} else if (com=="loadImage")
  3109 	{
  3110 		if (!selti)
  3111 		{
  3112 			parser.setError (Aborted,"Nothing selected");
  3113 		} else if (! selbi )
  3114 		{				  
  3115 			parser.setError (Aborted,"Type of selection is not a branch");
  3116 		} else if (parser.checkParCount(1))
  3117 		{
  3118 			s=parser.parString(ok,0);
  3119 			if (ok) loadFloatImageInt (selbi,s);
  3120 		}	
  3121 	/////////////////////////////////////////////////////////////////////
  3122 	} else if (com=="moveUp")
  3123 	{
  3124 		if (!selti )
  3125 		{
  3126 			parser.setError (Aborted,"Nothing selected");
  3127 		} else if (! selbi )
  3128 		{				  
  3129 			parser.setError (Aborted,"Type of selection is not a branch");
  3130 		} else if (parser.checkParCount(0))
  3131 		{
  3132 			moveUp();
  3133 		}	
  3134 	/////////////////////////////////////////////////////////////////////
  3135 	} else if (com=="moveDown")
  3136 	{
  3137 		if (!selti )
  3138 		{
  3139 			parser.setError (Aborted,"Nothing selected");
  3140 		} else if (! selbi )
  3141 		{				  
  3142 			parser.setError (Aborted,"Type of selection is not a branch");
  3143 		} else if (parser.checkParCount(0))
  3144 		{
  3145 			moveDown();
  3146 		}	
  3147 	/////////////////////////////////////////////////////////////////////
  3148 	} else if (com=="move")
  3149 	{
  3150 		if (!selti )
  3151 		{
  3152 			parser.setError (Aborted,"Nothing selected");
  3153 		} else if ( selectionType()!=TreeItem::Branch  && 
  3154 					selectionType()!=TreeItem::MapCenter  &&
  3155 					selectionType()!=TreeItem::Image )
  3156 		{				  
  3157 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3158 		} else if (parser.checkParCount(2))
  3159 		{	
  3160 			x=parser.parDouble (ok,0);
  3161 			if (ok)
  3162 			{
  3163 				y=parser.parDouble (ok,1);
  3164 				if (ok) move (x,y);
  3165 			}
  3166 		}	
  3167 	/////////////////////////////////////////////////////////////////////
  3168 	} else if (com=="moveRel")
  3169 	{
  3170 		if (!selti )
  3171 		{
  3172 			parser.setError (Aborted,"Nothing selected");
  3173 		} else if ( selectionType()!=TreeItem::Branch  && 
  3174 					selectionType()!=TreeItem::MapCenter  &&
  3175 					selectionType()!=TreeItem::Image )
  3176 		{				  
  3177 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3178 		} else if (parser.checkParCount(2))
  3179 		{	
  3180 			x=parser.parDouble (ok,0);
  3181 			if (ok)
  3182 			{
  3183 				y=parser.parDouble (ok,1);
  3184 				if (ok) moveRel (x,y);
  3185 			}
  3186 		}	
  3187 	/////////////////////////////////////////////////////////////////////
  3188 	} else if (com=="nop")
  3189 	{
  3190 	/////////////////////////////////////////////////////////////////////
  3191 	} else if (com=="paste")
  3192 	{
  3193 		if (!selti )
  3194 		{
  3195 			parser.setError (Aborted,"Nothing selected");
  3196 		} else if (! selbi )
  3197 		{				  
  3198 			parser.setError (Aborted,"Type of selection is not a branch");
  3199 		} else if (parser.checkParCount(1))
  3200 		{	
  3201 			n=parser.parInt (ok,0);
  3202 			if (ok) pasteNoSave(n);
  3203 		}	
  3204 	/////////////////////////////////////////////////////////////////////
  3205 	} else if (com=="qa")
  3206 	{
  3207 		if (!selti )
  3208 		{
  3209 			parser.setError (Aborted,"Nothing selected");
  3210 		} else if (! selbi )
  3211 		{				  
  3212 			parser.setError (Aborted,"Type of selection is not a branch");
  3213 		} else if (parser.checkParCount(4))
  3214 		{	
  3215 			QString c,u;
  3216 			c=parser.parString (ok,0);
  3217 			if (!ok)
  3218 			{
  3219 				parser.setError (Aborted,"No comment given");
  3220 			} else
  3221 			{
  3222 				s=parser.parString (ok,1);
  3223 				if (!ok)
  3224 				{
  3225 					parser.setError (Aborted,"First parameter is not a string");
  3226 				} else
  3227 				{
  3228 					t=parser.parString (ok,2);
  3229 					if (!ok)
  3230 					{
  3231 						parser.setError (Aborted,"Condition is not a string");
  3232 					} else
  3233 					{
  3234 						u=parser.parString (ok,3);
  3235 						if (!ok)
  3236 						{
  3237 							parser.setError (Aborted,"Third parameter is not a string");
  3238 						} else
  3239 						{
  3240 							if (s!="heading")
  3241 							{
  3242 								parser.setError (Aborted,"Unknown type: "+s);
  3243 							} else
  3244 							{
  3245 								if (! (t=="eq") ) 
  3246 								{
  3247 									parser.setError (Aborted,"Unknown operator: "+t);
  3248 								} else
  3249 								{
  3250 									if (! selbi    )
  3251 									{
  3252 										parser.setError (Aborted,"Type of selection is not a branch");
  3253 									} else
  3254 									{
  3255 										if (selbi->getHeading() == u)
  3256 										{
  3257 											cout << "PASSED: " << qPrintable (c)  << endl;
  3258 										} else
  3259 										{
  3260 											cout << "FAILED: " << qPrintable (c)  << endl;
  3261 										}
  3262 									}
  3263 								}
  3264 							}
  3265 						} 
  3266 					} 
  3267 				} 
  3268 			}
  3269 		}	
  3270 	/////////////////////////////////////////////////////////////////////
  3271 	} else if (com=="saveImage")
  3272 	{
  3273 		ImageItem *ii=getSelectedImageItem();
  3274 		if (!ii )
  3275 		{
  3276 			parser.setError (Aborted,"No image selected");
  3277 		} else if (parser.checkParCount(2))
  3278 		{
  3279 			s=parser.parString(ok,0);
  3280 			if (ok)
  3281 			{
  3282 				t=parser.parString(ok,1);
  3283 				if (ok) saveFloatImageInt (ii,t,s);
  3284 			}
  3285 		}	
  3286 	/////////////////////////////////////////////////////////////////////
  3287 	} else if (com=="scroll")
  3288 	{
  3289 		if (!selti)
  3290 		{
  3291 			parser.setError (Aborted,"Nothing selected");
  3292 		} else if (! selbi )
  3293 		{				  
  3294 			parser.setError (Aborted,"Type of selection is not a branch");
  3295 		} else if (parser.checkParCount(0))
  3296 		{	
  3297 			if (!scrollBranch (selbi))	
  3298 				parser.setError (Aborted,"Could not scroll branch");
  3299 		}	
  3300 	/////////////////////////////////////////////////////////////////////
  3301 	} else if (com=="select")
  3302 	{
  3303 		if (parser.checkParCount(1))
  3304 		{
  3305 			s=parser.parString(ok,0);
  3306 			if (ok) select (s);
  3307 		}	
  3308 	/////////////////////////////////////////////////////////////////////
  3309 	} else if (com=="selectLastBranch")
  3310 	{
  3311 		if (!selti )
  3312 		{
  3313 			parser.setError (Aborted,"Nothing selected");
  3314 		} else if (! selbi )
  3315 		{				  
  3316 			parser.setError (Aborted,"Type of selection is not a branch");
  3317 		} else if (parser.checkParCount(0))
  3318 		{	
  3319 			BranchItem *bi=selbi->getLastBranch();
  3320 			if (!bi)
  3321 				parser.setError (Aborted,"Could not select last branch");
  3322 			select (bi);		// FIXME-3 was selectInt
  3323 				
  3324 		}	
  3325 	/////////////////////////////////////////////////////////////////////
  3326 	} else /* FIXME-2 if (com=="selectLastImage")
  3327 	{
  3328 		if (!selti )
  3329 		{
  3330 			parser.setError (Aborted,"Nothing selected");
  3331 		} else if (! selbi )
  3332 		{				  
  3333 			parser.setError (Aborted,"Type of selection is not a branch");
  3334 		} else if (parser.checkParCount(0))
  3335 		{	
  3336 			FloatImageObj *fio=selb->getLastFloatImage();
  3337 			if (!fio)
  3338 				parser.setError (Aborted,"Could not select last image");
  3339 			select (fio);		// FIXME-3 was selectInt
  3340 				
  3341 		}	
  3342 	/////////////////////////////////////////////////////////////////////
  3343 	} else */ if (com=="selectLatestAdded")
  3344 	{
  3345 		if (!latestAddedItem)
  3346 		{
  3347 			parser.setError (Aborted,"No latest added object");
  3348 		} else
  3349 		{	
  3350 			if (!select (latestAddedItem))
  3351 				parser.setError (Aborted,"Could not select latest added object ");
  3352 		}	
  3353 	/////////////////////////////////////////////////////////////////////
  3354 	} else if (com=="setFrameType")
  3355 	{
  3356 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3357 		{
  3358 			parser.setError (Aborted,"Type of selection does not allow setting frame type");
  3359 		}
  3360 		else if (parser.checkParCount(1))
  3361 		{
  3362 			s=parser.parString(ok,0);
  3363 			if (ok) setFrameType (s);
  3364 		}	
  3365 	/////////////////////////////////////////////////////////////////////
  3366 	} else if (com=="setFramePenColor")
  3367 	{
  3368 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3369 		{
  3370 			parser.setError (Aborted,"Type of selection does not allow setting of pen color");
  3371 		}
  3372 		else if (parser.checkParCount(1))
  3373 		{
  3374 			QColor c=parser.parColor(ok,0);
  3375 			if (ok) setFramePenColor (c);
  3376 		}	
  3377 	/////////////////////////////////////////////////////////////////////
  3378 	} else if (com=="setFrameBrushColor")
  3379 	{
  3380 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3381 		{
  3382 			parser.setError (Aborted,"Type of selection does not allow setting brush color");
  3383 		}
  3384 		else if (parser.checkParCount(1))
  3385 		{
  3386 			QColor c=parser.parColor(ok,0);
  3387 			if (ok) setFrameBrushColor (c);
  3388 		}	
  3389 	/////////////////////////////////////////////////////////////////////
  3390 	} else if (com=="setFramePadding")
  3391 	{
  3392 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3393 		{
  3394 			parser.setError (Aborted,"Type of selection does not allow setting frame padding");
  3395 		}
  3396 		else if (parser.checkParCount(1))
  3397 		{
  3398 			n=parser.parInt(ok,0);
  3399 			if (ok) setFramePadding(n);
  3400 		}	
  3401 	/////////////////////////////////////////////////////////////////////
  3402 	} else if (com=="setFrameBorderWidth")
  3403 	{
  3404 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3405 		{
  3406 			parser.setError (Aborted,"Type of selection does not allow setting frame border width");
  3407 		}
  3408 		else if (parser.checkParCount(1))
  3409 		{
  3410 			n=parser.parInt(ok,0);
  3411 			if (ok) setFrameBorderWidth (n);
  3412 		}	
  3413 	/////////////////////////////////////////////////////////////////////
  3414 	} else if (com=="setMapAuthor")
  3415 	{
  3416 		if (parser.checkParCount(1))
  3417 		{
  3418 			s=parser.parString(ok,0);
  3419 			if (ok) setAuthor (s);
  3420 		}	
  3421 	/////////////////////////////////////////////////////////////////////
  3422 	} else if (com=="setMapComment")
  3423 	{
  3424 		if (parser.checkParCount(1))
  3425 		{
  3426 			s=parser.parString(ok,0);
  3427 			if (ok) setComment(s);
  3428 		}	
  3429 	/////////////////////////////////////////////////////////////////////
  3430 	} else if (com=="setMapBackgroundColor")
  3431 	{
  3432 		if (!selti )
  3433 		{
  3434 			parser.setError (Aborted,"Nothing selected");
  3435 		} else if (! selbi )
  3436 		{				  
  3437 			parser.setError (Aborted,"Type of selection is not a branch");
  3438 		} else if (parser.checkParCount(1))
  3439 		{
  3440 			QColor c=parser.parColor (ok,0);
  3441 			if (ok) setMapBackgroundColor (c);
  3442 		}	
  3443 	/////////////////////////////////////////////////////////////////////
  3444 	} else if (com=="setMapDefLinkColor")
  3445 	{
  3446 		if (!selti )
  3447 		{
  3448 			parser.setError (Aborted,"Nothing selected");
  3449 		} else if (! selbi )
  3450 		{				  
  3451 			parser.setError (Aborted,"Type of selection is not a branch");
  3452 		} else if (parser.checkParCount(1))
  3453 		{
  3454 			QColor c=parser.parColor (ok,0);
  3455 			if (ok) setMapDefLinkColor (c);
  3456 		}	
  3457 	/////////////////////////////////////////////////////////////////////
  3458 	} else if (com=="setMapLinkStyle")
  3459 	{
  3460 		if (parser.checkParCount(1))
  3461 		{
  3462 			s=parser.parString (ok,0);
  3463 			if (ok) setMapLinkStyle(s);
  3464 		}	
  3465 	/////////////////////////////////////////////////////////////////////
  3466 	} else if (com=="setHeading")
  3467 	{
  3468 		if (!selti )
  3469 		{
  3470 			parser.setError (Aborted,"Nothing selected");
  3471 		} else if (! selbi )
  3472 		{				  
  3473 			parser.setError (Aborted,"Type of selection is not a branch");
  3474 		} else if (parser.checkParCount(1))
  3475 		{
  3476 			s=parser.parString (ok,0);
  3477 			if (ok) 
  3478 				setHeading (s);
  3479 		}	
  3480 	/////////////////////////////////////////////////////////////////////
  3481 	} else if (com=="setHideExport")
  3482 	{
  3483 		if (!selti )
  3484 		{
  3485 			parser.setError (Aborted,"Nothing selected");
  3486 		} else if (selectionType()!=TreeItem::Branch && selectionType() != TreeItem::MapCenter &&selectionType()!=TreeItem::Image)
  3487 		{				  
  3488 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3489 		} else if (parser.checkParCount(1))
  3490 		{
  3491 			b=parser.parBool(ok,0);
  3492 			if (ok) setHideExport (b);
  3493 		}
  3494 	/////////////////////////////////////////////////////////////////////
  3495 	} else if (com=="setIncludeImagesHorizontally")
  3496 	{ 
  3497 		if (!selti )
  3498 		{
  3499 			parser.setError (Aborted,"Nothing selected");
  3500 		} else if (! selbi)
  3501 		{				  
  3502 			parser.setError (Aborted,"Type of selection is not a branch");
  3503 		} else if (parser.checkParCount(1))
  3504 		{
  3505 			b=parser.parBool(ok,0);
  3506 			if (ok) setIncludeImagesHor(b);
  3507 		}
  3508 	/////////////////////////////////////////////////////////////////////
  3509 	} else if (com=="setIncludeImagesVertically")
  3510 	{
  3511 		if (!selti )
  3512 		{
  3513 			parser.setError (Aborted,"Nothing selected");
  3514 		} else if (! selbi)
  3515 		{				  
  3516 			parser.setError (Aborted,"Type of selection is not a branch");
  3517 		} else if (parser.checkParCount(1))
  3518 		{
  3519 			b=parser.parBool(ok,0);
  3520 			if (ok) setIncludeImagesVer(b);
  3521 		}
  3522 	/////////////////////////////////////////////////////////////////////
  3523 	} else if (com=="setHideLinkUnselected")
  3524 	{
  3525 		if (!selti )
  3526 		{
  3527 			parser.setError (Aborted,"Nothing selected");
  3528 		} else if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3529 		{				  
  3530 			parser.setError (Aborted,"Type of selection does not allow hiding the link");
  3531 		} else if (parser.checkParCount(1))
  3532 		{
  3533 			b=parser.parBool(ok,0);
  3534 			if (ok) setHideLinkUnselected(b);
  3535 		}
  3536 	/////////////////////////////////////////////////////////////////////
  3537 	} else if (com=="setSelectionColor")
  3538 	{
  3539 		if (parser.checkParCount(1))
  3540 		{
  3541 			QColor c=parser.parColor (ok,0);
  3542 			if (ok) setSelectionColorInt (c);
  3543 		}	
  3544 	/////////////////////////////////////////////////////////////////////
  3545 	} else if (com=="setURL")
  3546 	{
  3547 		if (!selti )
  3548 		{
  3549 			parser.setError (Aborted,"Nothing selected");
  3550 		} else if (! selbi )
  3551 		{				  
  3552 			parser.setError (Aborted,"Type of selection is not a branch");
  3553 		} else if (parser.checkParCount(1))
  3554 		{
  3555 			s=parser.parString (ok,0);
  3556 			if (ok) setURL(s);
  3557 		}	
  3558 	/////////////////////////////////////////////////////////////////////
  3559 	} else if (com=="setVymLink")
  3560 	{
  3561 		if (!selti )
  3562 		{
  3563 			parser.setError (Aborted,"Nothing selected");
  3564 		} else if (! selbi )
  3565 		{				  
  3566 			parser.setError (Aborted,"Type of selection is not a branch");
  3567 		} else if (parser.checkParCount(1))
  3568 		{
  3569 			s=parser.parString (ok,0);
  3570 			if (ok) setVymLink(s);
  3571 		}	
  3572 	}
  3573 	/////////////////////////////////////////////////////////////////////
  3574 	else if (com=="setFlag")
  3575 	{
  3576 		if (!selti )
  3577 		{
  3578 			parser.setError (Aborted,"Nothing selected");
  3579 		} else if (! selbi )
  3580 		{				  
  3581 			parser.setError (Aborted,"Type of selection is not a branch");
  3582 		} else if (parser.checkParCount(1))
  3583 		{
  3584 			s=parser.parString(ok,0);
  3585 			if (ok) 
  3586 				selbi->activateStandardFlag(s);
  3587 		}
  3588 	/////////////////////////////////////////////////////////////////////
  3589 	} else /* FIXME-2 if (com=="setFrameType")
  3590 	{
  3591 		if (!selti )
  3592 		{
  3593 			parser.setError (Aborted,"Nothing selected");
  3594 		} else if (! selb )
  3595 		{				  
  3596 			parser.setError (Aborted,"Type of selection is not a branch");
  3597 		} else if (parser.checkParCount(1))
  3598 		{
  3599 			s=parser.parString(ok,0);
  3600 			if (ok) 
  3601 				setFrameType (s);
  3602 		}
  3603 	/////////////////////////////////////////////////////////////////////
  3604 	} else*/ if (com=="sortChildren")
  3605 	{
  3606 		if (!selti )
  3607 		{
  3608 			parser.setError (Aborted,"Nothing selected");
  3609 		} else if (! selbi )
  3610 		{				  
  3611 			parser.setError (Aborted,"Type of selection is not a branch");
  3612 		} else if (parser.checkParCount(0))
  3613 		{
  3614 			sortChildren();
  3615 		}
  3616 	/////////////////////////////////////////////////////////////////////
  3617 	} else if (com=="toggleFlag")
  3618 	{
  3619 		if (!selti )
  3620 		{
  3621 			parser.setError (Aborted,"Nothing selected");
  3622 		} else if (! selbi )
  3623 		{				  
  3624 			parser.setError (Aborted,"Type of selection is not a branch");
  3625 		} else if (parser.checkParCount(1))
  3626 		{
  3627 			s=parser.parString(ok,0);
  3628 			if (ok) 
  3629 				selbi->toggleStandardFlag(s);	
  3630 		}
  3631 	/////////////////////////////////////////////////////////////////////
  3632 	} else  if (com=="unscroll")
  3633 	{
  3634 		if (!selti)
  3635 		{
  3636 			parser.setError (Aborted,"Nothing selected");
  3637 		} else if (! selbi )
  3638 		{				  
  3639 			parser.setError (Aborted,"Type of selection is not a branch");
  3640 		} else if (parser.checkParCount(0))
  3641 		{	
  3642 			if (!unscrollBranch (selbi))	
  3643 				parser.setError (Aborted,"Could not unscroll branch");
  3644 		}	
  3645 	/////////////////////////////////////////////////////////////////////
  3646 	} else if (com=="unscrollChildren")
  3647 	{
  3648 		if (!selti)
  3649 		{
  3650 			parser.setError (Aborted,"Nothing selected");
  3651 		} else if (! selbi )
  3652 		{				  
  3653 			parser.setError (Aborted,"Type of selection is not a branch");
  3654 		} else if (parser.checkParCount(0))
  3655 		{	
  3656 			unscrollChildren ();
  3657 		}	
  3658 	/////////////////////////////////////////////////////////////////////
  3659 	} else if (com=="unsetFlag")
  3660 	{
  3661 		if (!selti)
  3662 		{
  3663 			parser.setError (Aborted,"Nothing selected");
  3664 		} else if (! selbi )
  3665 		{				  
  3666 			parser.setError (Aborted,"Type of selection is not a branch");
  3667 		} else if (parser.checkParCount(1))
  3668 		{
  3669 			s=parser.parString(ok,0);
  3670 			if (ok) 
  3671 				selbi->deactivateStandardFlag(s);
  3672 		}
  3673 	} else 
  3674 		parser.setError (Aborted,"Unknown command");
  3675 
  3676 	// Any errors?
  3677 	if (parser.errorLevel()==NoError)
  3678 	{
  3679 		// setChanged();  FIXME-2 should not be called e.g. for export?!
  3680 		reposition();
  3681 	}	
  3682 	else	
  3683 	{
  3684 		// TODO Error handling
  3685 		qWarning("VymModel::parseAtom: Error!");
  3686 		qWarning(parser.errorMessage());
  3687 	} 
  3688 }
  3689 
  3690 void VymModel::runScript (QString script)
  3691 {
  3692 	parser.setScript (script);
  3693 	parser.runScript();
  3694 	while (parser.next() ) 
  3695 		parseAtom(parser.getAtom());
  3696 }
  3697 
  3698 void VymModel::setExportMode (bool b)
  3699 {
  3700 	// should be called before and after exports
  3701 	// depending on the settings
  3702 	if (b && settings.value("/export/useHideExport","true")=="true")
  3703 		setHideTmpMode (TreeItem::HideExport);
  3704 	else	
  3705 		setHideTmpMode (TreeItem::HideNone);
  3706 }
  3707 
  3708 void VymModel::exportImage(QString fname, bool askName, QString format)
  3709 {
  3710 	if (fname=="")
  3711 	{
  3712 		fname=getMapName()+".png";
  3713 		format="PNG";
  3714 	} 	
  3715 
  3716 	if (askName)
  3717 	{
  3718 		QStringList fl;
  3719 		QFileDialog *fd=new QFileDialog (NULL);
  3720 		fd->setCaption (tr("Export map as image"));
  3721 		fd->setDirectory (lastImageDir);
  3722 		fd->setFileMode(QFileDialog::AnyFile);
  3723 		fd->setFilters  (imageIO.getFilters() );
  3724 		if (fd->exec())
  3725 		{
  3726 			fl=fd->selectedFiles();
  3727 			fname=fl.first();
  3728 			format=imageIO.getType(fd->selectedFilter());
  3729 		} 
  3730 	}
  3731 
  3732 	setExportMode (true);
  3733 	QPixmap pix (getPixmap());
  3734 	pix.save(fname, format);
  3735 	setExportMode (false);
  3736 }
  3737 
  3738 
  3739 void VymModel::exportXML(QString dir, bool askForName)
  3740 {
  3741 	if (askForName)
  3742 	{
  3743 		dir=browseDirectory(NULL,tr("Export XML to directory"));
  3744 		if (dir =="" && !reallyWriteDirectory(dir) )
  3745 		return;
  3746 	}
  3747 
  3748 	// Hide stuff during export, if settings want this
  3749 	setExportMode (true);
  3750 
  3751 	// Create subdirectories
  3752 	makeSubDirs (dir);
  3753 
  3754 	// write to directory
  3755 	QString saveFile=saveToDir (dir,mapName+"-",true,getTotalBBox().topLeft() ,NULL);
  3756 	QFile file;
  3757 
  3758 	file.setName ( dir + "/"+mapName+".xml");
  3759 	if ( !file.open( QIODevice::WriteOnly ) )
  3760 	{
  3761 		// This should neverever happen
  3762 		QMessageBox::critical (0,tr("Critical Export Error"),tr("VymModel::exportXML couldn't open %1").arg(file.name()));
  3763 		return;
  3764 	}	
  3765 
  3766 	// Write it finally, and write in UTF8, no matter what 
  3767 	QTextStream ts( &file );
  3768 	ts.setEncoding (QTextStream::UnicodeUTF8);
  3769 	ts << saveFile;
  3770 	file.close();
  3771 
  3772 	// Now write image, too
  3773 	exportImage (dir+"/images/"+mapName+".png",false,"PNG");
  3774 
  3775 	setExportMode (false);
  3776 }
  3777 
  3778 void VymModel::exportASCII(QString fname,bool askName)
  3779 {
  3780 	ExportASCII ex;
  3781 	ex.setModel (this);
  3782 	if (fname=="") 
  3783 		ex.setFile (mapName+".txt");	
  3784 	else
  3785 		ex.setFile (fname);
  3786 
  3787 	if (askName)
  3788 	{
  3789 		//ex.addFilter ("TXT (*.txt)");
  3790 		ex.setDir(lastImageDir);
  3791 		//ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
  3792 		ex.execDialog() ; 
  3793 	} 
  3794 	if (!ex.canceled())
  3795 	{
  3796 		setExportMode(true);
  3797 		ex.doExport();
  3798 		setExportMode(false);
  3799 	}
  3800 }
  3801 
  3802 void VymModel::exportXHTML (const QString &dir, bool askForName)
  3803 {
  3804 			ExportXHTMLDialog dia(NULL);
  3805 			dia.setFilePath (filePath );
  3806 			dia.setMapName (mapName );
  3807 			dia.readSettings();
  3808 			if (dir!="") dia.setDir (dir);
  3809 
  3810 			bool ok=true;
  3811 			
  3812 			if (askForName)
  3813 			{
  3814 				if (dia.exec()!=QDialog::Accepted) 
  3815 					ok=false;
  3816 				else	
  3817 				{
  3818 					QDir d (dia.getDir());
  3819 					// Check, if warnings should be used before overwriting
  3820 					// the output directory
  3821 					if (d.exists() && d.count()>0)
  3822 					{
  3823 						WarningDialog warn;
  3824 						warn.showCancelButton (true);
  3825 						warn.setText(QString(
  3826 							"The directory %1 is not empty.\n"
  3827 							"Do you risk to overwrite some of its contents?").arg(d.path() ));
  3828 						warn.setCaption("Warning: Directory not empty");
  3829 						warn.setShowAgainName("mainwindow/overwrite-dir-xhtml");
  3830 
  3831 						if (warn.exec()!=QDialog::Accepted) ok=false;
  3832 					}
  3833 				}	
  3834 			}
  3835 
  3836 			if (ok)
  3837 			{
  3838 				exportXML (dia.getDir(),false );
  3839 				dia.doExport(mapName );
  3840 				//if (dia.hasChanged()) setChanged();
  3841 			}
  3842 }
  3843 
  3844 void VymModel::exportOOPresentation(const QString &fn, const QString &cf)
  3845 {
  3846 	ExportOO ex;
  3847 	ex.setFile (fn);
  3848 	ex.setModel (this);
  3849 	if (ex.setConfigFile(cf)) 
  3850 	{
  3851 		setExportMode (true);
  3852 		ex.exportPresentation();
  3853 		setExportMode (false);
  3854 	}
  3855 }
  3856 
  3857 
  3858 
  3859 
  3860 //////////////////////////////////////////////
  3861 // View related
  3862 //////////////////////////////////////////////
  3863 
  3864 void VymModel::registerEditor(QWidget *me)
  3865 {
  3866 	mapEditor=(MapEditor*)me;
  3867 }
  3868 
  3869 void VymModel::unregisterEditor(QWidget *)
  3870 {
  3871 	mapEditor=NULL;
  3872 }
  3873 
  3874 void VymModel::setContextPos(QPointF p)
  3875 {
  3876 	contextPos=p;
  3877 }
  3878 
  3879 void VymModel::unsetContextPos()
  3880 {
  3881 	contextPos=QPointF();
  3882 }
  3883 
  3884 void VymModel::updateNoteFlag()
  3885 {
  3886 	setChanged();
  3887 	TreeItem *selti=getSelectedItem();
  3888 	if (selti)
  3889 	{
  3890 		if (textEditor->isEmpty()) 
  3891 			selti->clearNote();
  3892 		else
  3893 			selti->setNote (textEditor->getText());
  3894 		emitDataHasChanged(selti);		
  3895 		emitSelectionChanged();
  3896 
  3897 	}
  3898 }
  3899 
  3900 void VymModel::updateRelPositions()		//FIXME-3 VM should have no need to updateRelPos
  3901 {
  3902 	/* FIXME-3 ???
  3903 	for (int i=0; i<rootItem->branchCount(); i++)
  3904 		((MapCenterObj*)rootItem->getBranchObjNum(i))->updateRelPositions();
  3905 		*/
  3906 		/*
  3907 	void MapCenterObj::updateRelPositions()
  3908 	{
  3909 		if (repositionRequest) unsetAllRepositionRequests();
  3910 
  3911 		// update relative Positions of branches and floats
  3912 		for (int i=0; i<treeItem->branchCount(); ++i)
  3913 		{
  3914 			treeItem->getBranchObjNum(i)->setRelPos();
  3915 			treeItem->getBranchObjNum(i)->setOrientation();
  3916 		}
  3917 		
  3918 		for (int i=0; i<floatimage.size(); ++i)
  3919 			floatimage.at(i)->setRelPos();
  3920 
  3921 		if (repositionRequest) reposition();
  3922 	}
  3923 	*/
  3924 }
  3925 
  3926 void VymModel::reposition()	//FIXME-3 VM should have no need to reposition, this is done in views???
  3927 {
  3928 	//cout << "VM::reposition blocked="<<blockReposition<<endl;
  3929 	if (blockReposition) return;
  3930 
  3931 	for (int i=0;i<rootItem->branchCount(); i++)
  3932 		rootItem->getBranchObjNum(i)->reposition();	//	for positioning heading
  3933 }
  3934 
  3935 /*
  3936 QPolygonF VymModel::shape(BranchObj *bo)	//FIXME-4
  3937 {
  3938 	return QPolygonF ();
  3939 	// Creating (arbitrary) shapes
  3940 
  3941 	QPolygonF p;
  3942 	QRectF rb=bo->getBBox();
  3943 	if (bo->getDepth()==0)
  3944 	{
  3945 		// Just take BBox of this mapCenter
  3946 		p<<rb.topLeft()<<rb.topRight()<<rb.bottomRight()<<rb.bottomLeft();
  3947 		return p;
  3948 	}
  3949 
  3950 	// Take union of BBox and TotalBBox 
  3951 
  3952 	QRectF ra=bo->getTotalBBox();
  3953 	if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
  3954 		p   <<ra.bottomLeft()
  3955 			<<ra.topLeft()
  3956 			<<QPointF (rb.topLeft().x(), ra.topLeft().y() )
  3957 			<<rb.topRight()
  3958 			<<rb.bottomRight()
  3959 			<<QPointF (rb.bottomLeft().x(), ra.bottomLeft().y() ) ;
  3960 	else		
  3961 		p   <<ra.bottomRight()
  3962 			<<ra.topRight()
  3963 			<<QPointF (rb.topRight().x(), ra.topRight().y() )
  3964 			<<rb.topLeft()
  3965 			<<rb.bottomLeft()
  3966 			<<QPointF (rb.bottomRight().x(), ra.bottomRight().y() ) ;
  3967 	return p;		
  3968 }
  3969 */
  3970 
  3971 /*
  3972 void VymModel::moveAway(LinkableMapObj *lmo)	//FIXME-5
  3973 {
  3974 	// Autolayout:
  3975 	//
  3976 	// Move all branches and MapCenters away from lmo 
  3977 	// to avoid collisions 
  3978 
  3979 	QPolygonF pA;
  3980 	QPolygonF pB;
  3981 
  3982 	BranchObj *boA=(BranchObj*)lmo;
  3983 	BranchObj *boB;
  3984 	for (int i=0; i<rootItem->branchCount(); i++)
  3985 	{
  3986 		boB=rootItem->getBranchNum(i);
  3987 		pA=shape (boA);
  3988 		pB=shape (boB);
  3989 		PolygonCollisionResult r = PolygonCollision(pA, pB, QPoint(0,0));
  3990 		cout <<"------->"
  3991 			<<"="<<r.intersect
  3992 			<<"  ("<<qPrintable(boA->getHeading() )<<")"
  3993 			<<"  with ("<< qPrintable (boB->getHeading() )
  3994 			<<")  willIntersect"
  3995 			<<r.willIntersect 
  3996 			<<"  minT="<<r.minTranslation<<endl<<endl;
  3997 	}
  3998 }
  3999 */
  4000 
  4001 QPixmap VymModel::getPixmap()
  4002 {
  4003 	QRectF mapRect=getTotalBBox();
  4004 	QPixmap pix((int)mapRect.width()+2,(int)mapRect.height()+1);
  4005 	QPainter pp (&pix);
  4006 	
  4007 	pp.setRenderHints(mapEditor->renderHints());
  4008 
  4009 	// Don't print the visualisation of selection
  4010 	unselect();
  4011 
  4012 	mapScene->render (	&pp, 
  4013 		QRectF(0,0,mapRect.width()+2,mapRect.height()+2),
  4014 		QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
  4015 
  4016 	// Restore selection
  4017 	reselect();
  4018 	
  4019 	return pix;
  4020 }
  4021 
  4022 
  4023 void VymModel::setMapLinkStyle (const QString & s)
  4024 {
  4025 	QString snow;
  4026 	switch (linkstyle)
  4027 	{
  4028 		case LinkableMapObj::Line :
  4029 			snow="StyleLine";
  4030 			break;
  4031 		case LinkableMapObj::Parabel:
  4032 			snow="StyleParabel";
  4033 			break;
  4034 		case LinkableMapObj::PolyLine:
  4035 			snow="StylePolyLine";
  4036 			break;
  4037 		case LinkableMapObj::PolyParabel:
  4038 			snow="StylePolyParabel";
  4039 			break;
  4040 		default:	
  4041 			snow="UndefinedStyle";
  4042 			break;
  4043 	}
  4044 
  4045 	saveState (
  4046 		QString("setMapLinkStyle (\"%1\")").arg(s),
  4047 		QString("setMapLinkStyle (\"%1\")").arg(snow),
  4048 		QString("Set map link style (\"%1\")").arg(s)
  4049 	);	
  4050 
  4051 	if (s=="StyleLine")
  4052 		linkstyle=LinkableMapObj::Line;
  4053 	else if (s=="StyleParabel")
  4054 		linkstyle=LinkableMapObj::Parabel;
  4055 	else if (s=="StylePolyLine")
  4056 		linkstyle=LinkableMapObj::PolyLine;
  4057 	else if (s=="StylePolyParabel")	
  4058 		linkstyle=LinkableMapObj::PolyParabel;
  4059 	else
  4060 		linkstyle=LinkableMapObj::UndefinedStyle;
  4061 
  4062 	BranchItem *cur=NULL;
  4063 	BranchItem *prev=NULL;
  4064 	BranchObj *bo;
  4065 	next (cur,prev);
  4066 	while (cur) 
  4067 	{
  4068 		bo=(BranchObj*)(cur->getLMO() );
  4069 		bo->setLinkStyle(bo->getDefLinkStyle());
  4070 		cur=next(cur,prev);
  4071 	}
  4072 	reposition();
  4073 }
  4074 
  4075 LinkableMapObj::Style VymModel::getMapLinkStyle ()
  4076 {
  4077 	return linkstyle;
  4078 }	
  4079 
  4080 void VymModel::setMapDefLinkColor(QColor col)
  4081 {
  4082 	if ( !col.isValid() ) return;
  4083 	saveState (
  4084 		QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
  4085 		QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
  4086 		QString("Set map link color to %1").arg(col.name())
  4087 	);
  4088 
  4089 	defLinkColor=col;
  4090 	BranchItem *cur=NULL;
  4091 	BranchItem *prev=NULL;
  4092 	BranchObj *bo;
  4093 	cur=next(cur,prev);
  4094 	while (cur) 
  4095 	{
  4096 		bo=(BranchObj*)(cur->getLMO() );
  4097 		bo->setLinkColor();
  4098 		next(cur,prev);
  4099 	}
  4100 	updateActions();
  4101 }
  4102 
  4103 void VymModel::setMapLinkColorHintInt()
  4104 {
  4105 	// called from setMapLinkColorHint(lch) or at end of parse
  4106 	BranchItem *cur=NULL;
  4107 	BranchItem *prev=NULL;
  4108 	BranchObj *bo;
  4109 	cur=next(cur,prev);
  4110 	while (cur) 
  4111 	{
  4112 		bo=(BranchObj*)(cur->getLMO() );
  4113 		bo->setLinkColor();
  4114 		cur=next(cur,prev);
  4115 	}
  4116 }
  4117 
  4118 void VymModel::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
  4119 {
  4120 	linkcolorhint=lch;
  4121 	setMapLinkColorHintInt();
  4122 }
  4123 
  4124 void VymModel::toggleMapLinkColorHint()
  4125 {
  4126 	if (linkcolorhint==LinkableMapObj::HeadingColor)
  4127 		linkcolorhint=LinkableMapObj::DefaultColor;
  4128 	else	
  4129 		linkcolorhint=LinkableMapObj::HeadingColor;
  4130 	BranchItem *cur=NULL;
  4131 	BranchItem *prev=NULL;
  4132 	BranchObj *bo;
  4133 	cur=next(cur,prev);
  4134 	while (cur) 
  4135 	{
  4136 		bo=(BranchObj*)(cur->getLMO() );
  4137 		bo->setLinkColor();
  4138 		next(cur,prev);
  4139 	}
  4140 }
  4141 
  4142 void VymModel::selectMapBackgroundImage ()	// FIXME-2 move to ME
  4143 {
  4144 	Q3FileDialog *fd=new Q3FileDialog( NULL);
  4145 	fd->setMode (Q3FileDialog::ExistingFile);
  4146 	fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  4147 	ImagePreview *p =new ImagePreview (fd);
  4148 	fd->setContentsPreviewEnabled( TRUE );
  4149 	fd->setContentsPreview( p, p );
  4150 	fd->setPreviewMode( Q3FileDialog::Contents );
  4151 	fd->setCaption(vymName+" - " +tr("Load background image"));
  4152 	fd->setDir (lastImageDir);
  4153 	fd->show();
  4154 
  4155 	if ( fd->exec() == QDialog::Accepted )
  4156 	{
  4157 		// TODO selectMapBackgroundImg in QT4 use:	lastImageDir=fd->directory();
  4158 		lastImageDir=QDir (fd->dirPath());
  4159 		setMapBackgroundImage (fd->selectedFile());
  4160 	}
  4161 }	
  4162 
  4163 void VymModel::setMapBackgroundImage (const QString &fn)	//FIXME-2 missing savestate
  4164 {
  4165 	QColor oldcol=mapScene->backgroundBrush().color();
  4166 	/*
  4167 	saveState(
  4168 		selection,
  4169 		QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
  4170 		selection,
  4171 		QString ("setMapBackgroundImage (%1)").arg(col.name()),
  4172 		QString("Set background color of map to %1").arg(col.name()));
  4173 	*/	
  4174 	QBrush brush;
  4175 	brush.setTextureImage (QPixmap (fn));
  4176 	mapScene->setBackgroundBrush(brush);
  4177 }
  4178 
  4179 void VymModel::selectMapBackgroundColor()	// FIXME-3 move to ME
  4180 {
  4181 	QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), NULL);
  4182 	if ( !col.isValid() ) return;
  4183 	setMapBackgroundColor( col );
  4184 }
  4185 
  4186 
  4187 void VymModel::setMapBackgroundColor(QColor col)	// FIXME-3 move to ME
  4188 {
  4189 	QColor oldcol=mapScene->backgroundBrush().color();
  4190 	saveState(
  4191 		QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
  4192 		QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
  4193 		QString("Set background color of map to %1").arg(col.name()));
  4194 	mapScene->setBackgroundBrush(col);
  4195 }
  4196 
  4197 QColor VymModel::getMapBackgroundColor()	// FIXME-3 move to ME
  4198 {
  4199     return mapScene->backgroundBrush().color();
  4200 }
  4201 
  4202 
  4203 LinkableMapObj::ColorHint VymModel::getMapLinkColorHint()	// FIXME-3 move to ME
  4204 {
  4205 	return linkcolorhint;
  4206 }
  4207 
  4208 QColor VymModel::getMapDefLinkColor()	// FIXME-3 move to ME
  4209 {
  4210 	return defLinkColor;
  4211 }
  4212 
  4213 void VymModel::setMapDefXLinkColor(QColor col)	// FIXME-3 move to ME
  4214 {
  4215 	defXLinkColor=col;
  4216 }
  4217 
  4218 QColor VymModel::getMapDefXLinkColor()	// FIXME-3 move to ME
  4219 {
  4220 	return defXLinkColor;
  4221 }
  4222 
  4223 void VymModel::setMapDefXLinkWidth (int w)	// FIXME-3 move to ME
  4224 {
  4225 	defXLinkWidth=w;
  4226 }
  4227 
  4228 int VymModel::getMapDefXLinkWidth()	// FIXME-3 move to ME
  4229 {
  4230 	return defXLinkWidth;
  4231 }
  4232 
  4233 void VymModel::move(const double &x, const double &y)	// FIXME-3
  4234 {
  4235 	int i=x; i=y;
  4236 /*
  4237 	BranchObj *bo = getSelectedBranch();
  4238 	if (bo && 
  4239 		(selectionType()==TreeItem::Branch ||
  4240 		 selectionType()==TreeItem::MapCenter ||
  4241 		 selectionType()==TreeItem::Image
  4242 		))
  4243 	{
  4244         QPointF ap(bo->getAbsPos());
  4245         QPointF to(x, y);
  4246         if (ap != to)
  4247         {
  4248             QString ps=qpointfToString(ap);
  4249             QString s=getSelectString();
  4250             saveState(
  4251                 s, "move "+ps, 
  4252                 s, "move "+qpointfToString(to), 
  4253                 QString("Move %1 to %2").arg(getObjectName(bo)).arg(ps));
  4254             bo->move(x,y);
  4255             reposition();
  4256             emitSelectionChanged();
  4257         }
  4258 	}
  4259 */	
  4260 }
  4261 
  4262 void VymModel::moveRel (const double &x, const double &y)	// FIXME-3
  4263 {
  4264 	int i=x; i=y;
  4265 /*
  4266 	BranchObj *bo = getSelectedBranch();
  4267 	if (bo && 
  4268 		(selectionType()==TreeItem::Branch ||
  4269 		 selectionType()==TreeItem::MapCenter ||
  4270 		 selectionType()==TreeItem::Image
  4271 		))
  4272 	if (bo)
  4273 	{
  4274         QPointF rp(bo->getRelPos());
  4275         QPointF to(x, y);
  4276         if (rp != to)
  4277         {
  4278             QString ps=qpointfToString (bo->getRelPos());
  4279             QString s=getSelectString(bo);
  4280             saveState(
  4281                 s, "moveRel "+ps, 
  4282                 s, "moveRel "+qpointfToString(to), 
  4283                 QString("Move %1 to relative position %2").arg(getObjectName(bo)).arg(ps));
  4284             ((OrnamentedObj*)bo)->move2RelPos (x,y);
  4285             reposition();
  4286             bo->updateLink();
  4287             emitSelectionChanged();
  4288         }
  4289 	}
  4290 */	
  4291 }
  4292 
  4293 
  4294 void VymModel::animate()
  4295 {
  4296 	animationTimer->stop();
  4297 	BranchObj *bo;
  4298 	int i=0;
  4299 	while (i<animObjList.size() )
  4300 	{
  4301 		bo=(BranchObj*)animObjList.at(i);
  4302 		if (!bo->animate())
  4303 		{
  4304 			if (i>=0) 
  4305 			{	
  4306 				animObjList.removeAt(i);
  4307 				i--;
  4308 			}
  4309 		}
  4310 		bo->reposition();
  4311 		i++;
  4312 	} 
  4313 	QItemSelection sel=selModel->selection();
  4314 	emit (selectionChanged(sel,sel));
  4315 
  4316 	mapScene->update();
  4317 	if (!animObjList.isEmpty()) animationTimer->start();
  4318 }
  4319 
  4320 
  4321 void VymModel::startAnimation(BranchObj *bo, const QPointF &start, const QPointF &dest)
  4322 {
  4323 	if (bo && bo->getTreeItem()->depth()>0) 
  4324 	{
  4325 		AnimPoint ap;
  4326 		ap.setStart (start);
  4327 		ap.setDest  (dest);
  4328 		ap.setTicks (animationTicks);
  4329 		ap.setAnimated (true);
  4330 		bo->setAnimation (ap);
  4331 		animObjList.append( bo );
  4332 		animationTimer->setSingleShot (true);
  4333 		animationTimer->start(animationInterval);
  4334 	}
  4335 }
  4336 
  4337 void VymModel::stopAnimation (MapObj *mo)
  4338 {
  4339 	int i=animObjList.indexOf(mo);
  4340     if (i>=0)
  4341 		animObjList.removeAt (i);
  4342 }
  4343 
  4344 void VymModel::sendSelection()
  4345 {
  4346 	if (netstate!=Server) return;
  4347 	sendData (QString("select (\"%1\")").arg(getSelectString()) );
  4348 }
  4349 
  4350 void VymModel::newServer()
  4351 {
  4352 	port=54321;
  4353 	sendCounter=0;
  4354     tcpServer = new QTcpServer(this);
  4355     if (!tcpServer->listen(QHostAddress::Any,port)) {
  4356         QMessageBox::critical(NULL, "vym server",
  4357                               QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
  4358         //FIXME-3 needed? we are no widget any longer... close();
  4359         return;
  4360     }
  4361 	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
  4362 	netstate=Server;
  4363 	cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
  4364 }
  4365 
  4366 void VymModel::connectToServer()
  4367 {
  4368 	port=54321;
  4369 	server="salam.suse.de";
  4370 	server="localhost";
  4371 	clientSocket = new QTcpSocket (this);
  4372 	clientSocket->abort();
  4373     clientSocket->connectToHost(server ,port);
  4374 	connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
  4375     connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
  4376             this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
  4377 	netstate=Client;		
  4378 	cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
  4379 
  4380 	
  4381 }
  4382 
  4383 void VymModel::newClient()
  4384 {
  4385     QTcpSocket *newClient = tcpServer->nextPendingConnection();
  4386     connect(newClient, SIGNAL(disconnected()),
  4387             newClient, SLOT(deleteLater()));
  4388 
  4389 	cout <<"ME::newClient  at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
  4390 
  4391 	clientList.append (newClient);
  4392 }
  4393 
  4394 
  4395 void VymModel::sendData(const QString &s)
  4396 {
  4397 	if (clientList.size()==0) return;
  4398 
  4399 	// Create bytearray to send
  4400 	QByteArray block;
  4401     QDataStream out(&block, QIODevice::WriteOnly);
  4402     out.setVersion(QDataStream::Qt_4_0);
  4403 
  4404 	// Reserve some space for blocksize
  4405     out << (quint16)0;
  4406 
  4407 	// Write sendCounter
  4408     out << sendCounter++;
  4409 
  4410 	// Write data
  4411     out << s;
  4412 
  4413 	// Go back and write blocksize so far
  4414     out.device()->seek(0);
  4415     quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
  4416 	out << bs;
  4417 
  4418 	if (debug)
  4419 		cout << "ME::sendData  bs="<<bs<<"  counter="<<sendCounter<<"  s="<<qPrintable(s)<<endl;
  4420 
  4421 	for (int i=0; i<clientList.size(); ++i)
  4422 	{
  4423 		//cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
  4424 		clientList.at(i)->write (block);
  4425 	}
  4426 }
  4427 
  4428 void VymModel::readData ()
  4429 {
  4430 	while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
  4431 	{
  4432 		if (debug)
  4433 			cout <<"readData  bytesAvail="<<clientSocket->bytesAvailable();
  4434 		quint16 recCounter;
  4435 		quint16 blockSize;
  4436 
  4437 		QDataStream in(clientSocket);
  4438 		in.setVersion(QDataStream::Qt_4_0);
  4439 
  4440 		in >> blockSize;
  4441 		in >> recCounter;
  4442 		
  4443 		QString t;
  4444 		in >>t;
  4445 		if (debug)
  4446 			cout << "  t="<<qPrintable (t)<<endl;
  4447 		parseAtom (t);
  4448 	}
  4449 	return;
  4450 }
  4451 
  4452 void VymModel::displayNetworkError(QAbstractSocket::SocketError socketError)
  4453 {
  4454     switch (socketError) {
  4455     case QAbstractSocket::RemoteHostClosedError:
  4456         break;
  4457     case QAbstractSocket::HostNotFoundError:
  4458         QMessageBox::information(NULL, vymName +" Network client",
  4459                                  "The host was not found. Please check the "
  4460                                     "host name and port settings.");
  4461         break;
  4462     case QAbstractSocket::ConnectionRefusedError:
  4463         QMessageBox::information(NULL, vymName + " Network client",
  4464                                  "The connection was refused by the peer. "
  4465                                     "Make sure the fortune server is running, "
  4466                                     "and check that the host name and port "
  4467                                     "settings are correct.");
  4468         break;
  4469     default:
  4470         QMessageBox::information(NULL, vymName + " Network client",
  4471                                  QString("The following error occurred: %1.")
  4472                                  .arg(clientSocket->errorString()));
  4473     }
  4474 }
  4475 
  4476 
  4477 
  4478 
  4479 void VymModel::selectMapSelectionColor()
  4480 {
  4481 	QColor col = QColorDialog::getColor( defLinkColor, NULL);
  4482 	setSelectionColor (col);
  4483 }
  4484 
  4485 void VymModel::setSelectionColorInt (QColor col)
  4486 {
  4487 	if ( !col.isValid() ) return;
  4488 	saveState (
  4489 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4490 		QString("setSelectionColor (%1)").arg(col.name()),
  4491 		QString("Set color of selection box to %1").arg(col.name())
  4492 	);
  4493 
  4494 	mapEditor->setSelectionColor (col);
  4495 }
  4496 
  4497 /*
  4498 void VymModel::changeSelection (const QItemSelection &newsel,const QItemSelection &oldsel)
  4499 {
  4500 	cout << "VymModel::changeSelection (";
  4501 	if (!newsel.indexes().isEmpty() )
  4502 		cout << getItem(newsel.indexes().first() )->getHeading().toStdString();
  4503 	cout << ",";
  4504 	if (!oldsel.indexes().isEmpty() )
  4505 		cout << getItem(oldsel.indexes().first() )->getHeading().toStdString();
  4506 	cout << ")\n";
  4507 }
  4508 */
  4509 
  4510 void VymModel::updateSelection (const QItemSelection &newsel,const QItemSelection &oldsel)	//FIXME-4 connected but not used so far
  4511 {
  4512 }
  4513 
  4514 void VymModel::emitSelectionChanged(const QItemSelection &newsel)
  4515 {
  4516 	emit (selectionChanged(newsel,newsel));	// needed e.g. to update geometry in editor
  4517 	emitShowSelection();
  4518 	sendSelection();
  4519 }
  4520 
  4521 void VymModel::emitSelectionChanged()
  4522 {
  4523 	QItemSelection newsel=selModel->selection();
  4524 	emitSelectionChanged (newsel);
  4525 }
  4526 
  4527 void VymModel::setSelectionColor(QColor col)
  4528 {
  4529 	if ( !col.isValid() ) return;
  4530 	saveState (
  4531 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4532 		QString("setSelectionColor (%1)").arg(col.name()),
  4533 		QString("Set color of selection box to %1").arg(col.name())
  4534 	);
  4535 	setSelectionColorInt (col);
  4536 }
  4537 
  4538 QColor VymModel::getSelectionColor()
  4539 {
  4540 	return mapEditor->getSelectionColor();
  4541 }
  4542 
  4543 void VymModel::setHideTmpMode (TreeItem::HideTmpMode mode)
  4544 {
  4545 	hidemode=mode;
  4546 	for (int i=0;i<rootItem->childCount();i++)
  4547 		rootItem->child(i)->setHideTmp (mode);	
  4548 	reposition();
  4549 	// FIXME-3 needed? scene()->update();
  4550 }
  4551 
  4552 
  4553 QRectF VymModel::getTotalBBox()	//FIXME-2
  4554 {
  4555 	QRectF r;
  4556 /*
  4557 	for (int i=0;i<rootItem->branchCount(); i++)
  4558 		r=addBBox (rootItem->getBranchNum(i)->getTotalBBox(), r);
  4559 */ 
  4560 	return r;	
  4561 }
  4562 
  4563 //////////////////////////////////////////////
  4564 // Selection related
  4565 //////////////////////////////////////////////
  4566 
  4567 void VymModel::setSelectionModel (QItemSelectionModel *sm)
  4568 {
  4569 	selModel=sm;
  4570 }
  4571 
  4572 QItemSelectionModel* VymModel::getSelectionModel()
  4573 {
  4574 	return selModel;
  4575 }
  4576 
  4577 void VymModel::setSelectionBlocked (bool b)
  4578 {
  4579 	selectionBlocked=b;
  4580 }
  4581 
  4582 bool VymModel::isSelectionBlocked()
  4583 {
  4584 	return selectionBlocked;
  4585 }
  4586 
  4587 bool VymModel::select ()
  4588 {
  4589 	return select (selModel->selectedIndexes().first());	// TODO no multiselections yet
  4590 }
  4591 
  4592 bool VymModel::select (const QString &s)
  4593 {
  4594 	TreeItem *ti=findBySelectString(s);
  4595 	if (ti)
  4596 	{
  4597 		unselect();
  4598 		select (ti);
  4599 		return true;
  4600 	} 
  4601 	return false;
  4602 }
  4603 
  4604 bool VymModel::select (LinkableMapObj *lmo)
  4605 {
  4606 	QItemSelection oldsel=selModel->selection();
  4607 
  4608 	if (lmo)
  4609 		return select (lmo->getTreeItem() );
  4610 	else	
  4611 		return false;
  4612 }
  4613 
  4614 bool VymModel::select (TreeItem *ti)
  4615 {
  4616 	if (ti) return select (index(ti));
  4617 	return false;
  4618 }
  4619 
  4620 bool VymModel::select (const QModelIndex &index)
  4621 {
  4622 	if (index.isValid() )
  4623 	{
  4624 		selModel->select (index,QItemSelectionModel::ClearAndSelect  );
  4625 		getSelectedItem()->setLastSelectedBranch();
  4626 		return true;
  4627 	}
  4628 	return false;
  4629 }
  4630 
  4631 void VymModel::unselect()
  4632 {
  4633 	lastSelectString=getSelectString();
  4634 	selModel->clearSelection();
  4635 }	
  4636 
  4637 void VymModel::reselect()
  4638 {
  4639 	select (lastSelectString);
  4640 }	
  4641 
  4642 void VymModel::emitShowSelection()	
  4643 {
  4644 	if (!blockReposition)
  4645 		emit (showSelection() );
  4646 }
  4647 
  4648 void VymModel::emitNoteHasChanged (TreeItem *ti)
  4649 {
  4650 	QModelIndex ix=index(ti);
  4651 	emit (noteHasChanged (ix) );
  4652 }
  4653 
  4654 void VymModel::emitDataHasChanged (TreeItem *ti)
  4655 {
  4656 	QModelIndex ix=index(ti);
  4657 	emit (dataChanged (ix,ix) );
  4658 }
  4659 
  4660 
  4661 //void VymModel::selectInt (LinkableMapObj *lmo)	// FIXME-3 still needed?
  4662 /*
  4663 {
  4664 	if (selection.select(lmo))
  4665 	{
  4666 		//emitSelectionChanged();
  4667 	}
  4668 }
  4669 
  4670 void VymModel::selectInt (TreeItem *ti)	
  4671 {
  4672 	if (selection.select(lmo))
  4673 	{
  4674 		//emitSelectionChanged();
  4675 	}
  4676 }
  4677 */
  4678 
  4679 void VymModel::selectNextBranchInt()
  4680 {
  4681 	BranchItem *bi=getSelectedBranchItem();
  4682 	if (bi)
  4683 	{
  4684 		TreeItem *pi=bi->parent();
  4685 		if (bi!=rootItem)
  4686 		{
  4687 			int i=bi->num();
  4688 			if (i<pi->branchCount() )
  4689 			{
  4690 				// select previous branch with same parent
  4691 				i++;
  4692 				select (pi->getBranchNum(i));
  4693 				return;
  4694 			}
  4695 		}
  4696 		
  4697 	}
  4698 }
  4699 
  4700 void VymModel::selectPrevBranchInt()
  4701 {
  4702 
  4703 	BranchItem *bi=getSelectedBranchItem();
  4704 	if (bi)
  4705 	{
  4706 		BranchItem *pi=(BranchItem*)bi->parent();
  4707 		if (bi!=rootItem)
  4708 		{
  4709 			int i=bi->num();
  4710 			if (i>0)
  4711 			{
  4712 				// select previous branch with same parent
  4713 				bi=pi->getBranchNum(i-1);
  4714 				select (bi);
  4715 				return;
  4716 			}
  4717 			bi=pi;
  4718 			while (bi->branchCount() >0)
  4719 				bi=bi->getLastBranch();
  4720 			select (bi);	
  4721 
  4722 			// Try to select last branch in parent pi2 previous to own parent pi
  4723 			/*
  4724 			TreeItem *pi2=pi->parent();
  4725 			if (pi2)
  4726 			{
  4727 				int j=pi->num();
  4728 				if (pi2->)
  4729 			}
  4730 			*/
  4731 		}
  4732 	}
  4733 }
  4734 
  4735 void VymModel::selectAboveBranchInt()
  4736 {
  4737 	BranchItem *bi=getSelectedBranchItem();
  4738 	if (bi)
  4739 	{
  4740 		BranchItem *newbi=NULL;
  4741 		BranchItem *pi=(BranchItem*)bi->parent();
  4742 		int i=bi->num();
  4743 		if (i>0)
  4744 		{
  4745 			// goto previous branch with same parent
  4746 			newbi=pi->getBranchNum(i-1);
  4747 			while (newbi->branchCount() >0 )
  4748 				newbi=newbi->getLastBranch();
  4749 		}
  4750 		else
  4751 			newbi=pi;
  4752 		if (newbi==rootItem) 
  4753  			// already at top branch (resp. mapcenter)
  4754 			return;
  4755 		select (newbi);
  4756 	}
  4757 }
  4758 
  4759 void VymModel::selectBelowBranchInt()
  4760 {
  4761 	BranchItem *bi=getSelectedBranchItem();
  4762 	if (bi)
  4763 	{
  4764 		BranchItem *newbi=NULL;
  4765 
  4766 		if (bi->branchCount() >0)
  4767 			newbi=bi->getFirstBranch();
  4768 		else
  4769 		{
  4770 			BranchItem *pi;
  4771 			int i;
  4772 			while (!newbi)
  4773 			{
  4774 				pi=(BranchItem*)bi->parent();
  4775 				i=bi->num();
  4776 				if (pi->branchCount()-1 > i)
  4777 				{
  4778 					newbi=(BranchItem*)pi->getBranchNum(i+1);
  4779 					//done...
  4780 					break;
  4781 				}	
  4782 				else
  4783 					// look for siblings of myself 
  4784 					// or parent, or parent of parent...
  4785 					bi=pi;
  4786 				if (bi==rootItem)
  4787 					// already at end
  4788 					return;
  4789 			}	
  4790 		}
  4791 		select (newbi);
  4792 	}
  4793 }
  4794 
  4795 void VymModel::selectUpperBranch()
  4796 {
  4797 	BranchItem *bi=getSelectedBranchItem();
  4798 	if (bi && bi->isBranchLikeType())
  4799 		selectAboveBranchInt();
  4800 }
  4801 
  4802 void VymModel::selectLowerBranch()
  4803 {
  4804 	BranchItem *bi=getSelectedBranchItem();
  4805 	if (bi && bi->isBranchLikeType())
  4806 		selectBelowBranchInt();
  4807 }
  4808 
  4809 
  4810 void VymModel::selectLeftBranch()
  4811 {
  4812 	QItemSelection oldsel=selModel->selection();
  4813 
  4814 	BranchItem* par;
  4815 	BranchItem *selbi=getSelectedBranchItem();
  4816 	TreeItem::Type type=selbi->getType();
  4817 	if (selbi)
  4818 	{
  4819 		if (type == TreeItem::MapCenter)
  4820 		{
  4821 			QModelIndex ix=index(selbi);
  4822 			selModel->select (index (rowCount(ix)-1,0,ix),QItemSelectionModel::ClearAndSelect  );
  4823 		} else
  4824 		{
  4825 			par=(BranchItem*)selbi->parent();
  4826 			if (selbi->getBranchObj()->getOrientation()==LinkableMapObj::RightOfCenter)	//FIXME-3 check getBO...
  4827 			{
  4828 				// right of center
  4829 				if (type == TreeItem::Branch ||
  4830 					type == TreeItem::Image)
  4831 				{
  4832 					QModelIndex ix=index (selbi->parent());
  4833 					selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4834 				}
  4835 			} else
  4836 			{
  4837 				// left of center
  4838 				if (type == TreeItem::Branch )
  4839 				{
  4840 					selectLastSelectedBranch();
  4841 					return;
  4842 				}
  4843 			}
  4844 		}	
  4845 	}
  4846 }
  4847 
  4848 void VymModel::selectRightBranch()
  4849 {
  4850 	QItemSelection oldsel=selModel->selection();
  4851 
  4852 	BranchItem* par;
  4853 	BranchItem *selbi=getSelectedBranchItem();
  4854 	TreeItem::Type type=selbi->getType();
  4855 	if (selbi)
  4856 	{
  4857 		if (type==TreeItem::MapCenter)
  4858 		{
  4859 			QModelIndex ix=index(selbi);
  4860 			selModel->select (index (0,0,ix),QItemSelectionModel::ClearAndSelect  );
  4861 		} else
  4862 		{
  4863 			par=(BranchItem*)selbi->parent();
  4864 			if (selbi->getBranchObj()->getOrientation()==LinkableMapObj::RightOfCenter)	//FIXME-3 check getBO
  4865 			{
  4866 				// right of center
  4867 				if ( type== TreeItem::Branch )
  4868 				{
  4869 					selectLastSelectedBranch();
  4870 					return;
  4871 				}
  4872 			} else
  4873 			{
  4874 				// left of center
  4875 				if (type == TreeItem::Branch ||
  4876 					type == TreeItem::Image)
  4877 				{
  4878 					QModelIndex ix=index(selbi->parent());
  4879 					selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4880 				}
  4881 			}
  4882 		}	
  4883 	}
  4884 }
  4885 
  4886 void VymModel::selectFirstBranch()
  4887 {
  4888 	TreeItem *ti=getSelectedBranchItem();
  4889 	if (ti)
  4890 	{
  4891 		TreeItem *par=ti->parent();
  4892 		if (!par) return;
  4893 		TreeItem *ti2=par->getFirstBranch();
  4894 		if (ti2) {
  4895 			select(ti2);
  4896 			emitSelectionChanged();
  4897 		}
  4898 	}		
  4899 }
  4900 
  4901 void VymModel::selectLastBranch()
  4902 {
  4903 	TreeItem *ti=getSelectedBranchItem();
  4904 	if (ti)
  4905 	{
  4906 		TreeItem *par=ti->parent();
  4907 		if (!par) return;
  4908 		TreeItem *ti2=par->getLastBranch();
  4909 		if (ti2) {
  4910 			select(ti2);
  4911 			emitSelectionChanged();
  4912 		}
  4913 	}		
  4914 }
  4915 
  4916 void VymModel::selectLastSelectedBranch()
  4917 {
  4918 	TreeItem *ti=getSelectedBranchItem();
  4919 	if (ti)
  4920 	{
  4921 		ti=ti->getLastSelectedBranch();
  4922 		if (ti) select (ti);
  4923 	}		
  4924 }
  4925 
  4926 void VymModel::selectParent()
  4927 {
  4928 	TreeItem *ti=getSelectedItem();
  4929 	TreeItem *par;
  4930 	if (ti)
  4931 	{
  4932 		par=ti->parent();
  4933 		if (!par) return;
  4934 		select(par);
  4935 		emitSelectionChanged();
  4936 	}		
  4937 }
  4938 
  4939 TreeItem::Type VymModel::selectionType()
  4940 {
  4941 	QModelIndexList list=selModel->selectedIndexes();
  4942 	if (list.isEmpty()) return TreeItem::Undefined;	
  4943 	TreeItem *ti = getItem (list.first() );
  4944 	return ti->getType();
  4945 
  4946 }
  4947 
  4948 LinkableMapObj* VymModel::getSelectedLMO()
  4949 {
  4950 	QModelIndexList list=selModel->selectedIndexes();
  4951 	if (!list.isEmpty() )
  4952 	{
  4953 		TreeItem *ti = getItem (list.first() );
  4954 		TreeItem::Type type=ti->getType();
  4955 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter || type==TreeItem::Image)
  4956 		{
  4957 			return ti->getLMO();
  4958 		}	
  4959 	}
  4960 	return NULL;
  4961 }
  4962 
  4963 BranchObj* VymModel::getSelectedBranchObj()	// FIXME-3 this should not be needed in the end!!!
  4964 {
  4965 	TreeItem *ti = getSelectedBranchItem();
  4966 	if (ti)
  4967 		return (BranchObj*)(ti->getLMO());
  4968 	else	
  4969 		return NULL;
  4970 }
  4971 
  4972 BranchItem* VymModel::getSelectedBranchItem()
  4973 {
  4974 	QModelIndexList list=selModel->selectedIndexes();
  4975 	if (!list.isEmpty() )
  4976 	{
  4977 		TreeItem *ti = getItem (list.first() );
  4978 		TreeItem::Type type=ti->getType();
  4979 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter)
  4980 			return (BranchItem*)ti;
  4981 	}
  4982 	return NULL;
  4983 }
  4984 
  4985 TreeItem* VymModel::getSelectedItem()	
  4986 {
  4987 	QModelIndexList list=selModel->selectedIndexes();
  4988 	if (!list.isEmpty() )
  4989 		return getItem (list.first() );
  4990 	else	
  4991 		return NULL;
  4992 }
  4993 
  4994 QModelIndex VymModel::getSelectedIndex()
  4995 {
  4996 	QModelIndexList list=selModel->selectedIndexes();
  4997 	if (list.isEmpty() )
  4998 		return QModelIndex();
  4999 	else
  5000 		return list.first();
  5001 }
  5002 
  5003 ImageItem* VymModel::getSelectedImageItem()
  5004 {
  5005 	QModelIndexList list=selModel->selectedIndexes();
  5006 	if (!list.isEmpty())
  5007 	{
  5008 		TreeItem *ti=getItem (list.first());
  5009 		if (ti && ti->getType()==TreeItem::Image)
  5010 			return (ImageItem*)ti;
  5011 	}
  5012 	return NULL;
  5013 }
  5014 
  5015 QString VymModel::getSelectString ()
  5016 {
  5017 	return getSelectString (getSelectedItem());
  5018 }
  5019 
  5020 QString VymModel::getSelectString (LinkableMapObj *lmo)	// FIXME-2 VM needs to use TreeModel. Port all calls to this funtion to the one using TreeItem below...
  5021 {
  5022 	if (!lmo) return QString();
  5023 	return getSelectString (lmo->getTreeItem() );
  5024 }
  5025 
  5026 QString VymModel::getSelectString (TreeItem *ti) //FIXME-1 does not return "mc:"
  5027 {
  5028 	QString s;
  5029 	if (!ti) return s;
  5030 	switch (ti->getType())
  5031 	{
  5032 		case TreeItem::MapCenter: s="mc:"; break;
  5033 		case TreeItem::Branch: s="bo:";break;
  5034 		case TreeItem::Image: s="fi:";break;
  5035 		default:break;
  5036 	}
  5037 	s=  s + QString("%1").arg(ti->num());
  5038 	if (ti->depth() >0)
  5039 		// call myself recursively
  5040 		s= getSelectString(ti->parent()) +","+s;
  5041 			
  5042 	return s;
  5043 }
  5044