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