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