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