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