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