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