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