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