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