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