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