vymmodel.cpp
author insilmaril
Wed, 22 Jul 2009 11:48:23 +0000
changeset 781 6cbf3c9cbd21
parent 780 fe839bdfd10c
child 784 9db215a4ad53
permissions -rw-r--r--
Empty branches are always unscrolled after import, relinking to scrolled branch doesn't open branch, starting DBUS implementation
     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 	//new CarAdaptor(car);
   155     //connection.registerObject("/Car", car);
   156     dbusConnection.registerService("org.insilmaril.vym");
   157 
   158 
   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-2 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 
  1501 		reposition();
  1502 		emitSelectionChanged();
  1503 	}
  1504 }
  1505 
  1506 BranchItem* VymModel::findText (QString s, bool cs)   
  1507 {
  1508 	QTextDocument::FindFlags flags=0;
  1509 	if (cs) flags=QTextDocument::FindCaseSensitively;
  1510 
  1511 	if (!findCurrent) 
  1512 	{	// Nothing found or new find process
  1513 		if (EOFind)
  1514 			// nothing found, start again
  1515 			EOFind=false;
  1516 		findCurrent=NULL;	
  1517 		findPrevious=NULL;	
  1518 		next (findCurrent,findPrevious);
  1519 	}	
  1520 	bool searching=true;
  1521 	bool foundNote=false;
  1522 	while (searching && !EOFind)
  1523 	{
  1524 		if (findCurrent)
  1525 		{
  1526 			// Searching in Note
  1527 			if (findCurrent->getNote().contains(s,cs))
  1528 			{
  1529 				select (findCurrent);
  1530 				/*
  1531 				if (getSelectedBranch()!=itFind) 
  1532 				{
  1533 					select(itFind);
  1534 					emitShowSelection();
  1535 				}
  1536 				*/
  1537 				if (textEditor->findText(s,flags)) 
  1538 				{
  1539 					searching=false;
  1540 					foundNote=true;
  1541 				}	
  1542 			}
  1543 			// Searching in Heading
  1544 			if (searching && findCurrent->getHeading().contains (s,cs) ) 
  1545 			{
  1546 				select(findCurrent);
  1547 				searching=false;
  1548 			}
  1549 		}	
  1550 		if (!foundNote)
  1551 		{
  1552 			if (!next(findCurrent,findPrevious) )
  1553 				EOFind=true;
  1554 		}
  1555 	//cout <<"still searching...  "<<qPrintable( itFind->getHeading())<<endl;
  1556 	}	
  1557 	if (!searching)
  1558 		return getSelectedBranchItem();
  1559 	else
  1560 		return NULL;
  1561 }
  1562 
  1563 void VymModel::findReset()
  1564 {	// Necessary if text to find changes during a find process
  1565 	findCurrent=NULL;
  1566 	findPrevious=NULL;
  1567 	EOFind=false;
  1568 }
  1569 
  1570 void VymModel::setScene (QGraphicsScene *s)
  1571 {
  1572 	mapScene=s;	// FIXME-2 VM should not be necessary anymore, move all occurences to MapEditor
  1573     //init();	// Here we have a mapScene set, 
  1574 			// which is (still) needed to create MapCenters
  1575 }
  1576 
  1577 void VymModel::setURL(const QString &url) 
  1578 {
  1579 	TreeItem *selti=getSelectedItem();
  1580 	if (selti)
  1581 	{
  1582 		QString oldurl=selti->getURL();
  1583 		selti->setURL (url);
  1584 		saveState (
  1585 			selti,
  1586 			QString ("setURL (\"%1\")").arg(oldurl),
  1587 			selti,
  1588 			QString ("setURL (\"%1\")").arg(url),
  1589 			QString ("set URL of %1 to %2").arg(getObjectName(selti)).arg(url)
  1590 		);
  1591 		reposition();
  1592 		emitDataHasChanged (selti);
  1593 		emitShowSelection();
  1594 	}
  1595 }	
  1596 
  1597 QString VymModel::getURL()	
  1598 {
  1599 	TreeItem *selti=getSelectedItem();
  1600 	if (selti)
  1601 		return selti->getURL();
  1602 	else	
  1603 		return QString();
  1604 }
  1605 
  1606 QStringList VymModel::getURLs()	
  1607 {
  1608 	QStringList urls;
  1609 	BranchItem *selbi=getSelectedBranchItem();
  1610 	BranchItem *cur=selbi;
  1611 	BranchItem *prev=NULL;
  1612 	while (cur) 
  1613 	{
  1614 		if (!cur->getURL().isEmpty()) urls.append( cur->getURL());
  1615 		cur=next (cur,prev,selbi);
  1616 	}	
  1617 	return urls;
  1618 }
  1619 
  1620 
  1621 void VymModel::setFrameType(const FrameObj::FrameType &t)	//FIXME-4 not saved if there is no LMO
  1622 {
  1623 	BranchItem *bi=getSelectedBranchItem();
  1624 	if (bi)
  1625 	{
  1626 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1627 		if (bo)
  1628 		{
  1629 			QString s=bo->getFrameTypeName();
  1630 			bo->setFrameType (t);
  1631 			saveState (bi, QString("setFrameType (\"%1\")").arg(s),
  1632 				bi, QString ("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),QString ("set type of frame to %1").arg(s));
  1633 			reposition();
  1634 			bo->updateLinkGeometry();
  1635 		}
  1636 	}
  1637 }
  1638 
  1639 void VymModel::setFrameType(const QString &s)	//FIXME-4 not saved if there is no LMO
  1640 {
  1641 	BranchItem *bi=getSelectedBranchItem();
  1642 	if (bi)
  1643 	{
  1644 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1645 		if (bo)
  1646 		{
  1647 			saveState (bi, QString("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),
  1648 				bi, QString ("setFrameType (\"%1\")").arg(s),QString ("set type of frame to %1").arg(s));
  1649 			bo->setFrameType (s);
  1650 			reposition();
  1651 			bo->updateLinkGeometry();
  1652 		}
  1653 	}
  1654 }
  1655 
  1656 void VymModel::setFramePenColor(const QColor &c)	//FIXME-4 not saved if there is no LMO
  1657 
  1658 {
  1659 	BranchItem *bi=getSelectedBranchItem();
  1660 	if (bi)
  1661 	{
  1662 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1663 		if (bo)
  1664 		{
  1665 			saveState (bi, QString("setFramePenColor (\"%1\")").arg(bo->getFramePenColor().name() ),
  1666 				bi, QString ("setFramePenColor (\"%1\")").arg(c.name() ),QString ("set pen color of frame to %1").arg(c.name() ));
  1667 			bo->setFramePenColor (c);
  1668 		}	
  1669 	}	
  1670 }
  1671 
  1672 void VymModel::setFrameBrushColor(const QColor &c)	//FIXME-4 not saved if there is no LMO
  1673 {
  1674 	BranchItem *bi=getSelectedBranchItem();
  1675 	if (bi)
  1676 	{
  1677 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1678 		if (bo)
  1679 		{
  1680 			saveState (bi, QString("setFrameBrushColor (\"%1\")").arg(bo->getFrameBrushColor().name() ),
  1681 				bi, QString ("setFrameBrushColor (\"%1\")").arg(c.name() ),QString ("set brush color of frame to %1").arg(c.name() ));
  1682 			bo->setFrameBrushColor (c);
  1683 		}	
  1684 	}	
  1685 }
  1686 
  1687 void VymModel::setFramePadding (const int &i) //FIXME-4 not saved if there is no LMO
  1688 {
  1689 	BranchItem *bi=getSelectedBranchItem();
  1690 	if (bi)
  1691 	{
  1692 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1693 		if (bo)
  1694 		{
  1695 			saveState (bi, QString("setFramePadding (\"%1\")").arg(bo->getFramePadding() ),
  1696 				bi, QString ("setFramePadding (\"%1\")").arg(i),QString ("set brush color of frame to %1").arg(i));
  1697 			bo->setFramePadding (i);
  1698 			reposition();
  1699 			bo->updateLinkGeometry();
  1700 		}	
  1701 	}	
  1702 }
  1703 
  1704 void VymModel::setFrameBorderWidth(const int &i) //FIXME-4 not saved if there is no LMO
  1705 {
  1706 	BranchItem *bi=getSelectedBranchItem();
  1707 	if (bi)
  1708 	{
  1709 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1710 		if (bo)
  1711 		{
  1712 			saveState (bi, QString("setFrameBorderWidth (\"%1\")").arg(bo->getFrameBorderWidth() ),
  1713 				bi, QString ("setFrameBorderWidth (\"%1\")").arg(i),QString ("set border width of frame to %1").arg(i));
  1714 			bo->setFrameBorderWidth (i);
  1715 			reposition();
  1716 			bo->updateLinkGeometry();
  1717 		}	
  1718 	}	
  1719 }
  1720 
  1721 void VymModel::setIncludeImagesVer(bool b)	//FIXME-2
  1722 {
  1723 /*
  1724 	BranchItem *bi=getSelectedBranchItem();
  1725 	if (ti)
  1726 	{
  1727 		BranchObj *bo=bi->getLMO();
  1728 		if (bo)
  1729 		{
  1730 			QString u= b ? "false" : "true";
  1731 			QString r=!b ? "false" : "true";
  1732 			
  1733 			saveState(
  1734 				bo,
  1735 				QString("setIncludeImagesVertically (%1)").arg(u),
  1736 				bo, 
  1737 				QString("setIncludeImagesVertically (%1)").arg(r),
  1738 				QString("Include images vertically in %1").arg(getObjectName(bo))
  1739 			);	
  1740 			bo->setIncludeImagesVer(b);
  1741 			reposition();
  1742 		}	
  1743 	}	
  1744 */}
  1745 
  1746 void VymModel::setIncludeImagesHor(bool b)	//FIXME-2
  1747 {
  1748 /*
  1749 	TreeItem *bi=getSelectedBranchItem();
  1750 	if (ti)
  1751 	{
  1752 		BranchObj *bo=bi->getLMO();
  1753 		if (bo)
  1754 		{
  1755 			QString u= b ? "false" : "true";
  1756 			QString r=!b ? "false" : "true";
  1757 			
  1758 			saveState(
  1759 				bo,
  1760 				QString("setIncludeImagesHorizontally (%1)").arg(u),
  1761 				bo, 
  1762 				QString("setIncludeImagesHorizontally (%1)").arg(r),
  1763 				QString("Include images horizontally in %1").arg(getObjectName(bo))
  1764 			);	
  1765 			bo->setIncludeImagesHor(b);
  1766 			reposition();
  1767 		}	
  1768 	}	
  1769 	*/
  1770 }
  1771 
  1772 void VymModel::setHideLinkUnselected (bool b)//FIXME-2
  1773 {
  1774 	TreeItem *ti=getSelectedItem();
  1775 	if (ti && (ti->getType()==TreeItem::Image ||ti->isBranchLikeType()))
  1776 	{
  1777 		QString u= b ? "false" : "true";
  1778 		QString r=!b ? "false" : "true";
  1779 		
  1780 		saveState(
  1781 			ti,
  1782 			QString("setHideLinkUnselected (%1)").arg(u),
  1783 			ti, 
  1784 			QString("setHideLinkUnselected (%1)").arg(r),
  1785 			QString("Hide link of %1 if unselected").arg(getObjectName(ti))
  1786 		);	
  1787 		((MapItem*)ti)->setHideLinkUnselected(b);
  1788 	}
  1789 }
  1790 
  1791 void VymModel::setHideExport(bool b)
  1792 {
  1793 	TreeItem *ti=getSelectedItem();
  1794 	if (ti && 
  1795 		(ti->getType()==TreeItem::Image ||ti->isBranchLikeType()))
  1796 	{
  1797 		ti->setHideInExport (b);
  1798 		QString u= b ? "false" : "true";
  1799 		QString r=!b ? "false" : "true";
  1800 		
  1801 		saveState(
  1802 			ti,
  1803 			QString ("setHideExport (%1)").arg(u),
  1804 			ti,
  1805 			QString ("setHideExport (%1)").arg(r),
  1806 			QString ("Set HideExport flag of %1 to %2").arg(getObjectName(ti)).arg (r)
  1807 		);	
  1808 			emitDataHasChanged(ti);
  1809 			emitSelectionChanged();
  1810 		updateActions();
  1811 		reposition();
  1812 		// emitSelectionChanged();
  1813 		// FIXME-3 VM needed? scene()->update();
  1814 	}
  1815 }
  1816 
  1817 void VymModel::toggleHideExport()
  1818 {
  1819 	TreeItem *selti=getSelectedItem();
  1820 	if (selti)
  1821 		setHideExport ( !selti->hideInExport() );
  1822 }
  1823 
  1824 
  1825 void VymModel::copy()	
  1826 {
  1827 	TreeItem *selti=getSelectedItem();
  1828 	if (selti &&
  1829 		(selti->getType() == TreeItem::Branch || 
  1830 		selti->getType() == TreeItem::MapCenter  ||
  1831 		selti->getType() == TreeItem::Image ))
  1832 	{
  1833 		if (redosAvail == 0)
  1834 		{
  1835 			// Copy to history
  1836 			QString s=getSelectString(selti);
  1837 			saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",selti  );
  1838 			curClipboard=curStep;
  1839 		}
  1840 
  1841 		// Copy also to global clipboard, because we are at last step in history
  1842 		QString bakMapName(QString("history-%1").arg(curStep));
  1843 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1844 		copyDir (bakMapDir,clipboardDir );
  1845 
  1846 		clipboardEmpty=false;
  1847 		updateActions();
  1848 	}	    
  1849 }
  1850 
  1851 
  1852 void VymModel::pasteNoSave(const int &n)
  1853 {
  1854 	bool old=blockSaveState;
  1855 	blockSaveState=true;
  1856 	bool zippedOrg=zipped;
  1857 	if (redosAvail > 0 || n!=0)
  1858 	{
  1859 		// Use the "historical" buffer
  1860 		QString bakMapName(QString("history-%1").arg(n));
  1861 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1862 		load (bakMapDir+"/"+clipboardFile,ImportAdd, VymMap);
  1863 	} else
  1864 		// Use the global buffer
  1865 		load (clipboardDir+"/"+clipboardFile,ImportAdd, VymMap);
  1866 	zipped=zippedOrg;
  1867 	blockSaveState=old;
  1868 }
  1869 
  1870 void VymModel::paste()	
  1871 {   
  1872 	BranchItem *selbi=getSelectedBranchItem();
  1873 	if (selbi)
  1874 	{
  1875 		saveStateChangingPart(
  1876 			selbi,
  1877 			selbi,
  1878 			QString ("paste (%1)").arg(curClipboard),
  1879 			QString("Paste to %1").arg( getObjectName(selbi))
  1880 		);
  1881 		pasteNoSave(0);
  1882 		reposition();
  1883 	}
  1884 }
  1885 
  1886 void VymModel::cut()	
  1887 {
  1888 	TreeItem *selti=getSelectedItem();
  1889 	if ( selti && (selti->isBranchLikeType() ||selti->getType()==TreeItem::Image))
  1890 	{
  1891 		copy();
  1892 		deleteSelection();
  1893 		reposition();
  1894 	}
  1895 }
  1896 
  1897 void VymModel::moveUp()	
  1898 {
  1899 	BranchItem *selbi=getSelectedBranchItem();
  1900 	if (selbi)
  1901 	{
  1902 		if (!selbi->canMoveUp()) return;
  1903 		QString oldsel=getSelectString();
  1904 		if (relinkBranch (selbi,(BranchItem*)selbi->parent(),selbi->num()-1) )
  1905 
  1906 			saveState (getSelectString(),"moveDown ()",oldsel,"moveUp ()",QString("Move up %1").arg(getObjectName(selbi)));
  1907 	}
  1908 }
  1909 
  1910 void VymModel::moveDown()	
  1911 {
  1912 	BranchItem *selbi=getSelectedBranchItem();
  1913 	if (selbi)
  1914 	{
  1915 		if (!selbi->canMoveDown()) return;
  1916 		QString oldsel=getSelectString();
  1917 		if ( relinkBranch (selbi,(BranchItem*)selbi->parent(),selbi->num()+1) )
  1918 
  1919 			saveState (getSelectString(),"moveUp ()",oldsel,"moveDown ()",QString("Move down %1").arg(getObjectName(selbi)));
  1920 	}
  1921 }
  1922 
  1923 void VymModel::sortChildren()	// FIXME-2 not implemented yet
  1924 {
  1925 /*
  1926 	BranchObj* bo=getSelectedBranch();
  1927 	if (bo)
  1928 	{
  1929 		if(treeItem->branchCount()>1)
  1930 		{
  1931 			saveStateChangingPart(bo,bo, "sortChildren ()",QString("Sort children of %1").arg(getObjectName(bo)));
  1932 			bo->sortChildren();
  1933 			reposition();
  1934 			emitShowSelection();
  1935 		}
  1936 	}
  1937 */
  1938 }
  1939 
  1940 BranchItem* VymModel::createMapCenter()
  1941 {
  1942 	BranchItem *newbi=addMapCenter (QPointF (0,0) );
  1943 	return newbi;
  1944 }
  1945 
  1946 BranchItem* VymModel::createBranch(BranchItem *dst)	
  1947 {
  1948 	if (dst)
  1949 		return addNewBranchInt (dst,-2);
  1950 	else
  1951 		return NULL;
  1952 }
  1953 
  1954 ImageItem* VymModel::createImage(BranchItem *dst)
  1955 {
  1956 	if (dst)
  1957 	{
  1958 		QModelIndex parix;
  1959 		int n;
  1960 
  1961 		QList<QVariant> cData;
  1962 		cData << "new" << "undef"<<"undef";
  1963 
  1964 		ImageItem *newii=new ImageItem(cData) ;	
  1965 		//newii->setHeading (QApplication::translate("Heading of new image in map", "new image"));
  1966 
  1967 		emit (layoutAboutToBeChanged() );
  1968 
  1969 			parix=index(dst);
  1970 			n=dst->getRowNumAppend(newii);
  1971 			beginInsertRows (parix,n,n+1);
  1972 			dst->appendChild (newii);	
  1973 			endInsertRows ();
  1974 
  1975 		emit (layoutChanged() );
  1976 
  1977 		// save scroll state. If scrolled, automatically select
  1978 		// new branch in order to tmp unscroll parent...
  1979 		newii->createMapObj(mapScene);
  1980 		reposition();
  1981 		return newii;
  1982 	} 
  1983 	return NULL;
  1984 }
  1985 
  1986 BranchItem* VymModel::addMapCenter ()
  1987 {
  1988 	BranchItem *bi=addMapCenter (contextPos);
  1989 	updateActions();
  1990 	emitShowSelection();
  1991 	saveState (
  1992 		bi,
  1993 		"delete()",
  1994 		NULL,
  1995 		QString ("addMapCenter (%1,%2)").arg (contextPos.x()).arg(contextPos.y()),
  1996 		QString ("Adding MapCenter to (%1,%2)").arg (contextPos.x()).arg(contextPos.y())
  1997 	);	
  1998 	return bi;	
  1999 }
  2000 
  2001 BranchItem* VymModel::addMapCenter(QPointF absPos)	//FIXME-2 absPos not used in context menu?!
  2002 // createMapCenter could then probably be merged with createBranch
  2003 {
  2004 
  2005 	// Create TreeItem
  2006 	QModelIndex parix=index(rootItem);
  2007 
  2008 	int n=rootItem->branchCount();
  2009 
  2010 	emit (layoutAboutToBeChanged() );
  2011 	beginInsertRows (parix,n,n+1);
  2012 
  2013 	QList<QVariant> cData;
  2014 	cData << "VM:addMapCenter" << "undef"<<"undef";
  2015 	BranchItem *newbi=new BranchItem (cData);
  2016 	newbi->setHeading (QApplication::translate("Heading of mapcenter in new map", "New map"));
  2017 	rootItem->appendChild (newbi);
  2018 
  2019 	endInsertRows();
  2020 	emit (layoutChanged() );
  2021 
  2022 	// Create MapObj
  2023 	newbi->setPositionMode (MapItem::Absolute);
  2024 	newbi->createMapObj(mapScene);
  2025 		
  2026 	return newbi;
  2027 }
  2028 
  2029 BranchItem* VymModel::addNewBranchInt(BranchItem *dst,int num)	
  2030 {
  2031 	// Depending on pos:
  2032 	// -3		insert in children of parent  above selection 
  2033 	// -2		add branch to selection 
  2034 	// -1		insert in children of parent below selection 
  2035 	// 0..n		insert in children of parent at pos
  2036 
  2037 	// Create TreeItem
  2038 	QList<QVariant> cData;
  2039 	cData << "new" << "undef"<<"undef";
  2040 
  2041 	BranchItem *parbi;
  2042 	QModelIndex parix;
  2043 	int n;
  2044 	BranchItem *newbi=new BranchItem (cData);	
  2045 	newbi->setHeading (QApplication::translate("Heading of new branch in map", "new"));
  2046 
  2047 	emit (layoutAboutToBeChanged() );
  2048 
  2049 	if (num==-2)
  2050 	{
  2051 		parbi=dst;
  2052 		parix=index(parbi);
  2053 		n=parbi->getRowNumAppend (newbi);
  2054 		beginInsertRows (parix,n,n+1);	
  2055 		parbi->appendChild (newbi);	
  2056 		endInsertRows ();
  2057 	}else if (num==-1 || num==-3)
  2058 	{
  2059 		// insert below selection
  2060 		parbi=(BranchItem*)dst->parent();
  2061 		parix=index(parbi);  
  2062 		
  2063 		n=dst->childNumber() + (3+num)/2;	//-1 |-> 1;-3 |-> 0
  2064 		beginInsertRows (parix,n,n);	
  2065 		parbi->insertBranch(n,newbi);	
  2066 		endInsertRows ();
  2067 	}
  2068 	emit (layoutChanged() );
  2069 
  2070 	// save scroll state. If scrolled, automatically select
  2071 	// new branch in order to tmp unscroll parent...
  2072 	newbi->createMapObj(mapScene);
  2073 	reposition();
  2074 	return newbi;
  2075 }	
  2076 
  2077 BranchItem* VymModel::addNewBranch(int pos)
  2078 {
  2079 	// Different meaning than num in addNewBranchInt!
  2080 	// -1	add above
  2081 	//  0	add as child
  2082 	// +1	add below
  2083 	BranchItem *newbi=NULL;
  2084 	BranchItem *selbi=getSelectedBranchItem();
  2085 
  2086 	if (selbi)
  2087 	{
  2088 		// FIXME-3 setCursor (Qt::ArrowCursor);  //Still needed?
  2089 
  2090 		newbi=addNewBranchInt (selbi,pos-2);
  2091 
  2092 		if (newbi)
  2093 		{
  2094 			saveState(
  2095 				newbi,		
  2096 				"delete ()",
  2097 				selbi,
  2098 				QString ("addBranch (%1)").arg(pos),
  2099 				QString ("Add new branch to %1").arg(getObjectName(selbi)));	
  2100 
  2101 			reposition();
  2102 			// emitSelectionChanged(); FIXME-3
  2103 			latestAddedItem=newbi;
  2104 			// In Network mode, the client needs to know where the new branch is,
  2105 			// so we have to pass on this information via saveState.
  2106 			// TODO: Get rid of this positioning workaround
  2107 			/* FIXME-4  network problem:  QString ps=qpointfToString (newbo->getAbsPos());
  2108 			sendData ("selectLatestAdded ()");
  2109 			sendData (QString("move %1").arg(ps));
  2110 			sendSelection();
  2111 			*/
  2112 		}
  2113 	}	
  2114 	return newbi;
  2115 }
  2116 
  2117 
  2118 BranchItem* VymModel::addNewBranchBefore()	
  2119 {
  2120 	BranchItem *newbi=NULL;
  2121 	BranchItem *selbi=getSelectedBranchItem();
  2122 	if (selbi && selbi->getType()==TreeItem::Branch)
  2123 		 // We accept no MapCenter here, so we _have_ a parent
  2124 	{
  2125 		//QPointF p=bo->getRelPos();
  2126 
  2127 
  2128 		// add below selection
  2129 		newbi=addNewBranchInt (selbi,-1);
  2130 
  2131 		if (newbi)
  2132 		{
  2133 			//newbi->move2RelPos (p);
  2134 
  2135 			// Move selection to new branch
  2136 			relinkBranch (selbi,newbi,0);
  2137 
  2138 			saveState (newbi, "deleteKeepChildren ()", newbi, "addBranchBefore ()", 
  2139 				QString ("Add branch before %1").arg(getObjectName(selbi)));
  2140 
  2141 			// FIXME-3 needed? reposition();
  2142 			// emitSelectionChanged(); FIXME-3 
  2143 		}
  2144 	}	
  2145 	return newbi;
  2146 }
  2147 
  2148 bool VymModel::relinkBranch (BranchItem *branch, BranchItem *dst, int pos)
  2149 {
  2150 	if (branch && dst)
  2151 	{
  2152 		if (branch->depth()==0) 
  2153 		{
  2154 			cout <<"VM::relinkBranch  d=0 for "<<branch->getHeadingStd()<<endl;
  2155 		}
  2156 		emit (layoutAboutToBeChanged() );
  2157 		BranchItem *branchpi=(BranchItem*)branch->parent();
  2158 		// Remove at current position
  2159 		int n=branch->childNum();
  2160 		beginRemoveRows (index(branchpi),n,n);
  2161 		branchpi->removeChild (n);
  2162 		endRemoveRows();
  2163 
  2164 		if (pos<0 ||pos>dst->branchCount() ) pos=dst->branchCount();
  2165 
  2166 		// Append as last branch to dst
  2167 		if (dst->branchCount()==0)
  2168 			n=0;
  2169 		else	
  2170 			n=dst->getFirstBranch()->childNumber(); 
  2171 		beginInsertRows (index(dst),n+pos,n+pos);
  2172 		dst->insertBranch (pos,branch);
  2173 		endInsertRows();
  2174 
  2175 		// reset parObj, fonts, frame, etc in related LMO or other view-objects
  2176 		branch->updateStyles();
  2177 
  2178 		emit (layoutChanged() );
  2179 		reposition();	// both for moveUp/Down and relinking
  2180 		if (dst->isScrolled() )
  2181 		{
  2182 			select (dst);	
  2183 			branch->updateVisibility();
  2184 		}
  2185 		else	
  2186 			select (branch);
  2187 		return true;
  2188 	}
  2189 	return false;
  2190 }
  2191 
  2192 bool VymModel::relinkImage (ImageItem *image, BranchItem *dst)
  2193 {
  2194 	if (image && dst)
  2195 	{
  2196 		emit (layoutAboutToBeChanged() );
  2197 
  2198 		BranchItem *pi=(BranchItem*)(image->parent());
  2199 		QString oldParString=getSelectString (pi);
  2200 		// Remove at current position
  2201 		int n=image->childNum();
  2202 		beginRemoveRows (index(pi),n,n);
  2203 		pi->removeChild (n);
  2204 		endRemoveRows();
  2205 
  2206 		// Add at dst
  2207 		QModelIndex dstix=index(dst);
  2208 		n=dst->getRowNumAppend (image);
  2209 		beginInsertRows (dstix,n,n+1);	
  2210 		dst->appendChild (image);	
  2211 		endInsertRows ();
  2212 
  2213 		// Set new parent also for lmo
  2214 		if (image->getLMO() && dst->getLMO() )
  2215 			image->getLMO()->setParObj (dst->getLMO() );
  2216 
  2217 		emit (layoutChanged() );
  2218 		saveState(
  2219 			image,
  2220 			QString("relinkTo (\"%1\")").arg(oldParString), 
  2221 			image,
  2222 			QString ("relinkTo (\"%1\")").arg(getSelectString (dst)),
  2223 			QString ("Relink floatimage to %1").arg(getObjectName(dst)));
  2224 		return true;	
  2225 	}
  2226 	return false;
  2227 }
  2228 
  2229 void VymModel::deleteSelection()
  2230 {
  2231 	BranchItem *selbi=getSelectedBranchItem();
  2232 
  2233 	if (selbi && selbi->isBranchLikeType() )
  2234 	{
  2235 		unselect();
  2236 		saveStateRemovingPart (selbi, QString ("Delete %1").arg(getObjectName(selbi)));
  2237 
  2238 		TreeItem *pi=deleteItem (selbi);
  2239 		if (pi)
  2240 		{
  2241 			select (pi);
  2242 			emitShowSelection();
  2243 		}
  2244 		return;
  2245 	}
  2246 	ImageItem *ii=getSelectedImageItem();
  2247 	if (ii)
  2248 	{
  2249 		BranchItem *pi=(BranchItem*)(ii->parent());
  2250 		saveStateChangingPart(
  2251 			pi, 
  2252 			ii,
  2253 			"delete ()",
  2254 			QString("Delete %1").arg(getObjectName(ii))
  2255 		);
  2256 		unselect();
  2257 		deleteItem (ii);
  2258 		select (pi);
  2259 		reposition();
  2260 		emitShowSelection();
  2261 		return;
  2262 	}
  2263 }
  2264 
  2265 void VymModel::deleteKeepChildren()	//FIXME-2 does not work yet for mapcenters
  2266 
  2267 {
  2268 	BranchItem *selbi=getSelectedBranchItem();
  2269 	BranchItem *pi;
  2270 	if (selbi)
  2271 	{
  2272 		// Don't use this on mapcenter
  2273 		if (selbi->depth()<2) return;
  2274 
  2275 		pi=(BranchItem*)(selbi->parent());
  2276 		// Check if we have childs at all to keep
  2277 		if (selbi->branchCount()==0) 
  2278 		{
  2279 			deleteSelection();
  2280 			return;
  2281 		}
  2282 
  2283 		QPointF p;
  2284 		if (selbi->getLMO()) p=selbi->getLMO()->getRelPos();
  2285 		saveStateChangingPart(
  2286 			pi,
  2287 			selbi,
  2288 			"deleteKeepChildren ()",
  2289 			QString("Remove %1 and keep its children").arg(getObjectName(selbi))
  2290 		);
  2291 
  2292 		QString sel=getSelectString(selbi);
  2293 		unselect();
  2294 		int pos=selbi->num();
  2295 		BranchItem *bi=selbi->getFirstBranch();
  2296 		while (bi)
  2297 		{
  2298 			relinkBranch (bi,pi,pos);
  2299 			bi=selbi->getFirstBranch();
  2300 			pos++;
  2301 		}
  2302 		deleteItem (selbi);
  2303 		reposition();
  2304 		select (sel);
  2305 		BranchObj *bo=getSelectedBranchObj();
  2306 		if (bo) 
  2307 		{
  2308 			bo->move2RelPos (p);
  2309 			reposition();
  2310 		}
  2311 	}	
  2312 }
  2313 
  2314 void VymModel::deleteChildren()		
  2315 
  2316 {
  2317 	BranchItem *selbi=getSelectedBranchItem();
  2318 	if (selbi)
  2319 	{		
  2320 		saveStateChangingPart(
  2321 			selbi, 
  2322 			selbi,
  2323 			"deleteChildren ()",
  2324 			QString( "Remove children of branch %1").arg(getObjectName(selbi))
  2325 		);
  2326 		emit (layoutAboutToBeChanged() );
  2327 
  2328 		QModelIndex ix=index (selbi);
  2329 		int n=selbi->branchCount()-1;
  2330 		beginRemoveRows (ix,0,n);
  2331 		removeRows (0,n+1,ix);
  2332 		endRemoveRows();
  2333 		if (selbi->isScrolled()) selbi->unScroll();
  2334 		emit (layoutChanged() );
  2335 		reposition();
  2336 	}	
  2337 }
  2338 
  2339 TreeItem* VymModel::deleteItem (TreeItem *ti)
  2340 {
  2341 	if (ti)
  2342 	{
  2343 		TreeItem *pi=ti->parent();
  2344 		QModelIndex parentIndex=index(pi);
  2345 
  2346 		emit (layoutAboutToBeChanged() );
  2347 
  2348 		int n=ti->childNum();
  2349 		beginRemoveRows (parentIndex,n,n);
  2350 		removeRows (n,1,parentIndex);
  2351 		endRemoveRows();
  2352 		reposition();
  2353 
  2354 		emit (layoutChanged() );
  2355 		if (pi->depth()>0) return pi;
  2356 	}	
  2357 	return NULL;
  2358 }
  2359 
  2360 bool VymModel::scrollBranch(BranchItem *bi)
  2361 {
  2362 	if (bi)	
  2363 	{
  2364 		if (bi->isScrolled()) return false;
  2365 		if (bi->branchCount()==0) return false;
  2366 		if (bi->depth()==0) return false;
  2367 		if (bi->toggleScroll())
  2368 		{
  2369 			QString u,r;
  2370 			r="scroll";
  2371 			u="unscroll";
  2372 			saveState(
  2373 				bi,
  2374 				QString ("%1 ()").arg(u),
  2375 				bi,
  2376 				QString ("%1 ()").arg(r),
  2377 				QString ("%1 %2").arg(r).arg(getObjectName(bi))
  2378 			);
  2379 			emitDataHasChanged(bi);
  2380 			emitSelectionChanged();
  2381 			mapScene->update(); //Needed for _quick_ update,  even in 1.13.x //FIXME-3 force update via signal...
  2382 			return true;
  2383 		}
  2384 	}	
  2385 	return false;
  2386 }
  2387 
  2388 bool VymModel::unscrollBranch(BranchItem *bi)
  2389 {
  2390 	if (bi)
  2391 	{
  2392 		if (!bi->isScrolled()) return false;
  2393 		if (bi->branchCount()==0) return false;
  2394 		if (bi->depth()==0) return false;
  2395 
  2396 		QString u,r;
  2397 		u="scroll";
  2398 		r="unscroll";
  2399 		saveState(
  2400 			bi,
  2401 			QString ("%1 ()").arg(u),
  2402 			bi,
  2403 			QString ("%1 ()").arg(r),
  2404 			QString ("%1 %2").arg(r).arg(getObjectName(bi))
  2405 		);
  2406 		bi->toggleScroll();
  2407 		emitDataHasChanged(bi);
  2408 		emitSelectionChanged();
  2409 
  2410 		mapScene->update(); //Needed for _quick_ update,  even in 1.13.x //FIXME-3 force update via signal...
  2411 		return true;
  2412 	}	
  2413 	return false;
  2414 }
  2415 
  2416 void VymModel::toggleScroll()	
  2417 {
  2418 	BranchItem *bi=(BranchItem*)getSelectedBranchItem();
  2419 	if (bi && bi->isBranchLikeType() )
  2420 	{
  2421 		if (bi->isScrolled())
  2422 			unscrollBranch (bi);
  2423 		else
  2424 			scrollBranch (bi);
  2425 	}
  2426 	// saveState is called in above functions
  2427 }
  2428 
  2429 void VymModel::unscrollChildren() 	// FIXME-2	first, next moved to vymmodel
  2430 
  2431 {
  2432 /*
  2433 	BranchObj *bo=getSelectedBranch();
  2434 	if (bo)
  2435 	{
  2436 		bo->first();
  2437 		while (bo) 
  2438 		{
  2439 			if (bo->isScrolled()) unscrollBranch (bo);
  2440 			bo=bo->next();
  2441 		}
  2442 	}	
  2443 */	
  2444 }
  2445 
  2446 void VymModel::emitExpandAll()
  2447 {
  2448 	emit (expandAll() );
  2449 }
  2450 
  2451 void VymModel::toggleStandardFlag (const QString &name, FlagRow *master)
  2452 {
  2453 	BranchItem *bi=getSelectedBranchItem();
  2454 	if (bi) 
  2455 	{
  2456 		QString u,r;
  2457 		if (bi->isActiveStandardFlag(name))
  2458 		{
  2459 			r="unsetFlag";
  2460 			u="setFlag";
  2461 		}	
  2462 		else
  2463 		{
  2464 			u="unsetFlag";
  2465 			r="setFlag";
  2466 		}	
  2467 		saveState(
  2468 			bi,
  2469 			QString("%1 (\"%2\")").arg(u).arg(name), 
  2470 			bi,
  2471 			QString("%1 (\"%2\")").arg(r).arg(name),
  2472 			QString("Toggling standard flag \"%1\" of %2").arg(name).arg(getObjectName(bi)));
  2473 			bi->toggleStandardFlag (name, master);
  2474 		reposition();
  2475 		emitSelectionChanged();	
  2476 	}
  2477 }
  2478 
  2479 void VymModel::addFloatImage (const QPixmap &img) //FIXME-2 drag & drop
  2480 {
  2481 /*
  2482 	BranchObj *bo=getSelectedBranch();
  2483 	if (bo)
  2484   {
  2485 	FloatImageObj *fio=bo->addFloatImage();
  2486     fio->load(img);
  2487     fio->setOriginalFilename("No original filename (image added by dropevent)");	
  2488 	QString s=getSelectString(bo);
  2489 	saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",fio  );
  2490 	saveState (fio,"delete ()", bo,QString("paste(%1)").arg(curStep),"Pasting dropped image");
  2491     reposition();
  2492     // FIXME-3 VM needed? scene()->update();
  2493   }
  2494 */
  2495 }
  2496 
  2497 
  2498 void VymModel::colorBranch (QColor c)	
  2499 {
  2500 	BranchItem *selbi=getSelectedBranchItem();
  2501 	if (selbi)
  2502 	{
  2503 		saveState(
  2504 			selbi, 
  2505 			QString ("colorBranch (\"%1\")").arg(selbi->getHeadingColor().name()),
  2506 			selbi,
  2507 			QString ("colorBranch (\"%1\")").arg(c.name()),
  2508 			QString("Set color of %1 to %2").arg(getObjectName(selbi)).arg(c.name())
  2509 		);	
  2510 		selbi->setHeadingColor(c); // color branch
  2511 	}
  2512 }
  2513 
  2514 void VymModel::colorSubtree (QColor c) 
  2515 {
  2516 	BranchItem *selbi=getSelectedBranchItem();
  2517 	if (selbi)
  2518 	{
  2519 		saveStateChangingPart(
  2520 			selbi,
  2521 			selbi,
  2522 			QString ("colorSubtree (\"%1\")").arg(c.name()),
  2523 			QString ("Set color of %1 and children to %2").arg(getObjectName(selbi)).arg(c.name())
  2524 		);	
  2525 		BranchItem *prev=NULL;
  2526 		BranchItem *cur=selbi;
  2527 		while (cur) 
  2528 		{
  2529 			cur->setHeadingColor(c); // color links, color children
  2530 			cur=next (cur,prev,selbi);
  2531 		}	
  2532 
  2533 	}
  2534 }
  2535 
  2536 QColor VymModel::getCurrentHeadingColor()	
  2537 {
  2538 	BranchItem *selbi=getSelectedBranchItem();
  2539 	if (selbi)	return selbi->getHeadingColor();
  2540 		
  2541 	QMessageBox::warning(0,"Warning","Can't get color of heading,\nthere's no branch selected");
  2542 	return Qt::black;
  2543 }
  2544 
  2545 
  2546 
  2547 void VymModel::editURL()	
  2548 {
  2549 	TreeItem *selti=getSelectedItem();
  2550 	if (selti)
  2551 	{		
  2552 		bool ok;
  2553 		QString text = QInputDialog::getText(
  2554 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2555 				selti->getURL(), &ok, NULL);
  2556 		if ( ok) 
  2557 			// user entered something and pressed OK
  2558 			setURL(text);
  2559 	}
  2560 }
  2561 
  2562 void VymModel::editLocalURL()
  2563 {
  2564 	TreeItem *selti=getSelectedItem();
  2565 	if (selti)
  2566 	{		
  2567 		QStringList filters;
  2568 		filters <<"All files (*)";
  2569 		filters << tr("Text","Filedialog") + " (*.txt)";
  2570 		filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
  2571 		filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
  2572 		filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
  2573 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Set URL to a local file"));
  2574 		fd->setFilters (filters);
  2575 		fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
  2576 		fd->setDirectory (lastFileDir);
  2577 		if (! selti->getVymLink().isEmpty() )
  2578 			fd->selectFile( selti->getURL() );
  2579 		fd->show();
  2580 
  2581 		if ( fd->exec() == QDialog::Accepted )
  2582 		{
  2583 			lastFileDir=QDir (fd->directory().path());
  2584 			setURL (fd->selectedFile() );
  2585 		}
  2586 	}
  2587 }
  2588 
  2589 
  2590 void VymModel::editHeading2URL() 
  2591 {
  2592 	TreeItem *selti=getSelectedItem();
  2593 	if (selti)
  2594 		setURL (selti->getHeading());
  2595 }	
  2596 
  2597 void VymModel::editBugzilla2URL()	
  2598 {
  2599 	TreeItem *selti=getSelectedItem();
  2600 	if (selti)
  2601 	{		
  2602 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+selti->getHeading();
  2603 		setURL (url);
  2604 	}
  2605 }	
  2606 
  2607 void VymModel::editFATE2URL()
  2608 {
  2609 	TreeItem *selti=getSelectedItem();
  2610 	if (selti)
  2611 	{		
  2612 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+selti->getHeading();
  2613 		saveState(
  2614 			selti,
  2615 			"setURL (\""+selti->getURL()+"\")",
  2616 			selti,
  2617 			"setURL (\""+url+"\")",
  2618 			QString("Use heading of %1 as link to FATE").arg(getObjectName(selti))
  2619 		);	
  2620 		selti->setURL (url);
  2621 		// FIXME-4 updateActions();
  2622 	}
  2623 }	
  2624 
  2625 void VymModel::editVymLink()
  2626 {
  2627 	BranchItem *bi=getSelectedBranchItem();
  2628 	if (bi)
  2629 	{		
  2630 		QStringList filters;
  2631 		filters <<"VYM map (*.vym)";
  2632 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Link to another map"));
  2633 		fd->setFilters (filters);
  2634 		fd->setCaption(vymName+" - " +tr("Link to another map"));
  2635 		fd->setDirectory (lastFileDir);
  2636 		if (! bi->getVymLink().isEmpty() )
  2637 			fd->selectFile( bi->getVymLink() );
  2638 		fd->show();
  2639 
  2640 		QString fn;
  2641 		if ( fd->exec() == QDialog::Accepted )
  2642 		{
  2643 			lastFileDir=QDir (fd->directory().path());
  2644 			saveState(
  2645 				bi,
  2646 				"setVymLink (\""+bi->getVymLink()+"\")",
  2647 				bi,
  2648 				"setVymLink (\""+fd->selectedFile()+"\")",
  2649 				QString("Set vymlink of %1 to %2").arg(getObjectName(bi)).arg(fd->selectedFile())
  2650 			);	
  2651 			setVymLink (fd->selectedFile() );	// FIXME-2 ok?
  2652 		}
  2653 	}
  2654 }
  2655 
  2656 void VymModel::setVymLink (const QString &s)	// FIXME-3 no savestate?
  2657 {
  2658 	// Internal function, no saveState needed
  2659 	TreeItem *selti=getSelectedItem();
  2660 	if (selti)
  2661 	{
  2662 		selti->setVymLink(s);
  2663 		reposition();
  2664 		emitDataHasChanged (selti);
  2665 		emitShowSelection();
  2666 	}
  2667 }
  2668 
  2669 void VymModel::deleteVymLink()
  2670 {
  2671 	BranchItem *bi=getSelectedBranchItem();
  2672 	if (bi)
  2673 	{		
  2674 		saveState(
  2675 			bi,
  2676 			"setVymLink (\""+bi->getVymLink()+"\")", 
  2677 			bi,
  2678 			"setVymLink (\"\")",
  2679 			QString("Unset vymlink of %1").arg(getObjectName(bi))
  2680 		);	
  2681 		bi->setVymLink ("" );
  2682 		updateActions();
  2683 		reposition();
  2684 	}
  2685 }
  2686 
  2687 QString VymModel::getVymLink()
  2688 {
  2689 	BranchItem *bi=getSelectedBranchItem();
  2690 	if (bi)
  2691 		return bi->getVymLink();
  2692 	else	
  2693 		return "";
  2694 	
  2695 }
  2696 
  2697 QStringList VymModel::getVymLinks()	
  2698 {
  2699 	QStringList links;
  2700 	BranchItem *selbi=getSelectedBranchItem();
  2701 	BranchItem *cur=selbi;
  2702 	BranchItem *prev=NULL;
  2703 	while (cur) 
  2704 	{
  2705 		if (!cur->getVymLink().isEmpty()) links.append( cur->getVymLink());
  2706 		cur=next (cur,prev,selbi);
  2707 	}	
  2708 	return links;
  2709 }
  2710 
  2711 
  2712 void VymModel::followXLink(int i)	// FIXME-2
  2713 {
  2714 	i=0;
  2715 	/*
  2716 	BranchObj *bo=getSelectedBranch();
  2717 	if (bo)
  2718 	{
  2719 		bo=bo->XLinkTargetAt(i);
  2720 		if (bo) 
  2721 		{
  2722 			selection.select(bo);
  2723 			emitShowSelection();
  2724 		}
  2725 	}
  2726 	*/
  2727 }
  2728 
  2729 void VymModel::editXLink(int i)	// FIXME-2 VM missing saveState
  2730 {
  2731 	i=0;
  2732 	/*
  2733 	BranchObj *bo=getSelectedBranch();
  2734 	if (bo)
  2735 	{
  2736 		XLinkObj *xlo=bo->XLinkAt(i);
  2737 		if (xlo) 
  2738 		{
  2739 			EditXLinkDialog dia;
  2740 			dia.setXLink (xlo);
  2741 			dia.setSelection(bo);
  2742 			if (dia.exec() == QDialog::Accepted)
  2743 			{
  2744 				if (dia.useSettingsGlobal() )
  2745 				{
  2746 					setMapDefXLinkColor (xlo->getColor() );
  2747 					setMapDefXLinkWidth (xlo->getWidth() );
  2748 				}
  2749 				if (dia.deleteXLink())
  2750 					bo->deleteXLinkAt(i);
  2751 			}
  2752 		}	
  2753 	}
  2754 */	
  2755 }
  2756 
  2757 
  2758 
  2759 
  2760 
  2761 //////////////////////////////////////////////
  2762 // Scripting
  2763 //////////////////////////////////////////////
  2764 
  2765 void VymModel::parseAtom(const QString &atom)
  2766 {
  2767 	TreeItem* selti=getSelectedItem();
  2768 	BranchItem *selbi=getSelectedBranchItem();
  2769 	QString s,t;
  2770 	double x,y;
  2771 	int n;
  2772 	bool b,ok;
  2773 
  2774 	// Split string s into command and parameters
  2775 	parser.parseAtom (atom);
  2776 	QString com=parser.getCommand();
  2777 	
  2778 	// External commands
  2779 	/////////////////////////////////////////////////////////////////////
  2780 	if (com=="addBranch")
  2781 	{
  2782 		if (!selti)
  2783 		{
  2784 			parser.setError (Aborted,"Nothing selected");
  2785 		} else if (! selbi )
  2786 		{				  
  2787 			parser.setError (Aborted,"Type of selection is not a branch");
  2788 		} else 
  2789 		{	
  2790 			QList <int> pl;
  2791 			pl << 0 <<1;
  2792 			if (parser.checkParCount(pl))
  2793 			{
  2794 				if (parser.parCount()==0)
  2795 					addNewBranch (0);
  2796 				else
  2797 				{
  2798 					n=parser.parInt (ok,0);
  2799 					if (ok ) addNewBranch (n);
  2800 				}
  2801 			}
  2802 		}
  2803 	/////////////////////////////////////////////////////////////////////
  2804 	} else if (com=="addBranchBefore")
  2805 	{
  2806 		if (!selti)
  2807 		{
  2808 			parser.setError (Aborted,"Nothing selected");
  2809 		} else if (! selbi )
  2810 		{				  
  2811 			parser.setError (Aborted,"Type of selection is not a branch");
  2812 		} else 
  2813 		{	
  2814 			if (parser.parCount()==0)
  2815 			{
  2816 				addNewBranchBefore ();
  2817 			}	
  2818 		}
  2819 	/////////////////////////////////////////////////////////////////////
  2820 	} else if (com==QString("addMapCenter"))
  2821 	{
  2822 		if (parser.checkParCount(2))
  2823 		{
  2824 			x=parser.parDouble (ok,0);
  2825 			if (ok)
  2826 			{
  2827 				y=parser.parDouble (ok,1);
  2828 				if (ok) addMapCenter (QPointF(x,y));
  2829 			}
  2830 		}	
  2831 	/////////////////////////////////////////////////////////////////////
  2832 	} else if (com==QString("addMapReplace"))
  2833 	{
  2834 		if (!selti)
  2835 		{
  2836 			parser.setError (Aborted,"Nothing selected");
  2837 		} else if (! selbi )
  2838 		{				  
  2839 			parser.setError (Aborted,"Type of selection is not a branch");
  2840 		} else if (parser.checkParCount(1))
  2841 		{
  2842 			//s=parser.parString (ok,0);	// selection
  2843 			t=parser.parString (ok,0);	// path to map
  2844 			if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2845 			addMapReplaceInt(getSelectString(selbi),t);	
  2846 		}
  2847 	/////////////////////////////////////////////////////////////////////
  2848 	} else if (com==QString("addMapInsert"))
  2849 	{
  2850 		if (!selti)
  2851 		{
  2852 			parser.setError (Aborted,"Nothing selected");
  2853 		} else if (! selbi )
  2854 		{				  
  2855 			parser.setError (Aborted,"Type of selection is not a branch");
  2856 		} else 
  2857 		{	
  2858 			if (parser.checkParCount(2))
  2859 			{
  2860 				t=parser.parString (ok,0);	// path to map
  2861 				n=parser.parInt(ok,1);		// position
  2862 				if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2863 				addMapInsertInt(t,n);	
  2864 			}
  2865 		}
  2866 	/////////////////////////////////////////////////////////////////////
  2867 	} else if (com=="clearFlags")	
  2868 	{
  2869 		if (!selti )
  2870 		{
  2871 			parser.setError (Aborted,"Nothing selected");
  2872 		} else if (! selbi )
  2873 		{				  
  2874 			parser.setError (Aborted,"Type of selection is not a branch");
  2875 		} else if (parser.checkParCount(0))
  2876 		{
  2877 			selbi->deactivateAllStandardFlags();	
  2878 		}
  2879 	/////////////////////////////////////////////////////////////////////
  2880 	} else if (com=="colorBranch")
  2881 	{
  2882 		if (!selti)
  2883 		{
  2884 			parser.setError (Aborted,"Nothing selected");
  2885 		} else if (! selbi )
  2886 		{				  
  2887 			parser.setError (Aborted,"Type of selection is not a branch");
  2888 		} else if (parser.checkParCount(1))
  2889 		{	
  2890 			QColor c=parser.parColor (ok,0);
  2891 			if (ok) colorBranch (c);
  2892 		}	
  2893 	/////////////////////////////////////////////////////////////////////
  2894 	} else if (com=="colorSubtree")
  2895 	{
  2896 		if (!selti)
  2897 		{
  2898 			parser.setError (Aborted,"Nothing selected");
  2899 		} else if (! selbi )
  2900 		{				  
  2901 			parser.setError (Aborted,"Type of selection is not a branch");
  2902 		} else if (parser.checkParCount(1))
  2903 		{	
  2904 			QColor c=parser.parColor (ok,0);
  2905 			if (ok) colorSubtree (c);
  2906 		}	
  2907 	/////////////////////////////////////////////////////////////////////
  2908 	} else if (com=="copy")
  2909 	{
  2910 		if (!selti)
  2911 		{
  2912 			parser.setError (Aborted,"Nothing selected");
  2913 		} else if ( selectionType()!=TreeItem::Branch  && 
  2914 					selectionType()!=TreeItem::MapCenter  &&
  2915 					selectionType()!=TreeItem::Image )
  2916 		{				  
  2917 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  2918 		} else if (parser.checkParCount(0))
  2919 		{	
  2920 			copy();
  2921 		}	
  2922 	/////////////////////////////////////////////////////////////////////
  2923 	} else if (com=="cut")
  2924 	{
  2925 		if (!selti)
  2926 		{
  2927 			parser.setError (Aborted,"Nothing selected");
  2928 		} else if ( selectionType()!=TreeItem::Branch  && 
  2929 					selectionType()!=TreeItem::MapCenter  &&
  2930 					selectionType()!=TreeItem::Image )
  2931 		{				  
  2932 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  2933 		} else if (parser.checkParCount(0))
  2934 		{	
  2935 			cut();
  2936 		}	
  2937 	/////////////////////////////////////////////////////////////////////
  2938 	} else if (com=="delete")
  2939 	{
  2940 		if (!selti)
  2941 		{
  2942 			parser.setError (Aborted,"Nothing selected");
  2943 		} 
  2944 		/*else if (selectionType() != TreeItem::Branch && selectionType() != TreeItem::Image )
  2945 		{
  2946 			parser.setError (Aborted,"Type of selection is wrong.");
  2947 		} 
  2948 		*/
  2949 		else if (parser.checkParCount(0))
  2950 		{	
  2951 			deleteSelection();
  2952 		}	
  2953 	/////////////////////////////////////////////////////////////////////
  2954 	} else if (com=="deleteKeepChildren")
  2955 	{
  2956 		if (!selti)
  2957 		{
  2958 			parser.setError (Aborted,"Nothing selected");
  2959 		} else if (! selbi )
  2960 		{
  2961 			parser.setError (Aborted,"Type of selection is not a branch");
  2962 		} else if (parser.checkParCount(0))
  2963 		{	
  2964 			deleteKeepChildren();
  2965 		}	
  2966 	/////////////////////////////////////////////////////////////////////
  2967 	} else if (com=="deleteChildren")
  2968 	{
  2969 		if (!selti)
  2970 		{
  2971 			parser.setError (Aborted,"Nothing selected");
  2972 		} else if (! selbi)
  2973 		{
  2974 			parser.setError (Aborted,"Type of selection is not a branch");
  2975 		} else if (parser.checkParCount(0))
  2976 		{	
  2977 			deleteChildren();
  2978 		}	
  2979 	/////////////////////////////////////////////////////////////////////
  2980 	} else if (com=="exportASCII")
  2981 	{
  2982 		QString fname="";
  2983 		ok=true;
  2984 		if (parser.parCount()>=1)
  2985 			// Hey, we even have a filename
  2986 			fname=parser.parString(ok,0); 
  2987 		if (!ok)
  2988 		{
  2989 			parser.setError (Aborted,"Could not read filename");
  2990 		} else
  2991 		{
  2992 				exportASCII (fname,false);
  2993 		}
  2994 	/////////////////////////////////////////////////////////////////////
  2995 	} else if (com=="exportImage")
  2996 	{
  2997 		QString fname="";
  2998 		ok=true;
  2999 		if (parser.parCount()>=2)
  3000 			// Hey, we even have a filename
  3001 			fname=parser.parString(ok,0); 
  3002 		if (!ok)
  3003 		{
  3004 			parser.setError (Aborted,"Could not read filename");
  3005 		} else
  3006 		{
  3007 			QString format="PNG";
  3008 			if (parser.parCount()>=2)
  3009 			{
  3010 				format=parser.parString(ok,1);
  3011 			}
  3012 			exportImage (fname,false,format);
  3013 		}
  3014 	/////////////////////////////////////////////////////////////////////
  3015 	} else if (com=="exportXHTML")
  3016 	{
  3017 		QString fname="";
  3018 		ok=true;
  3019 		if (parser.parCount()>=2)
  3020 			// Hey, we even have a filename
  3021 			fname=parser.parString(ok,1); 
  3022 		if (!ok)
  3023 		{
  3024 			parser.setError (Aborted,"Could not read filename");
  3025 		} else
  3026 		{
  3027 			exportXHTML (fname,false);
  3028 		}
  3029 	/////////////////////////////////////////////////////////////////////
  3030 	} else if (com=="exportXML")
  3031 	{
  3032 		QString fname="";
  3033 		ok=true;
  3034 		if (parser.parCount()>=2)
  3035 			// Hey, we even have a filename
  3036 			fname=parser.parString(ok,1); 
  3037 		if (!ok)
  3038 		{
  3039 			parser.setError (Aborted,"Could not read filename");
  3040 		} else
  3041 		{
  3042 			exportXML (fname,false);
  3043 		}
  3044 	/////////////////////////////////////////////////////////////////////
  3045 	} else if (com=="importDir")
  3046 	{
  3047 		if (!selti)
  3048 		{
  3049 			parser.setError (Aborted,"Nothing selected");
  3050 		} else if (! selbi )
  3051 		{				  
  3052 			parser.setError (Aborted,"Type of selection is not a branch");
  3053 		} else if (parser.checkParCount(1))
  3054 		{
  3055 			s=parser.parString(ok,0);
  3056 			if (ok) importDirInt(s);
  3057 		}	
  3058 	/////////////////////////////////////////////////////////////////////
  3059 	} else if (com=="relinkTo")
  3060 	{
  3061 		if (!selti)
  3062 		{
  3063 			parser.setError (Aborted,"Nothing selected");
  3064 		} else if ( selbi)
  3065 		{
  3066 			if (parser.checkParCount(4))
  3067 			{
  3068 				// 0	selectstring of parent
  3069 				// 1	num in parent (for branches)
  3070 				// 2,3	x,y of mainbranch or mapcenter
  3071 				s=parser.parString(ok,0);
  3072 				TreeItem *dst=findBySelectString (s);
  3073 				if (dst)
  3074 				{	
  3075 					if (dst->getType()==TreeItem::Branch) 
  3076 					{
  3077 						// Get number in parent
  3078 						n=parser.parInt (ok,1);
  3079 						if (ok)
  3080 						{
  3081 							relinkBranch (selbi,(BranchItem*)dst,n);
  3082 							emitSelectionChanged();
  3083 						}	
  3084 					} else if (dst->getType()==TreeItem::MapCenter) 
  3085 					{
  3086 						relinkBranch (selbi,(BranchItem*)dst);
  3087 						// Get coordinates of mainbranch
  3088 						x=parser.parDouble(ok,2);
  3089 						if (ok)
  3090 						{
  3091 							y=parser.parDouble(ok,3);
  3092 							if (ok) 
  3093 							{
  3094 								if (selbi->getLMO()) selbi->getLMO()->move (x,y);
  3095 								emitSelectionChanged();
  3096 							}
  3097 						}
  3098 					}	
  3099 				}	
  3100 			}	
  3101 		} else if ( selti->getType() == TreeItem::Image) 
  3102 		{
  3103 			if (parser.checkParCount(1))
  3104 			{
  3105 				// 0	selectstring of parent
  3106 				s=parser.parString(ok,0);
  3107 				TreeItem *dst=findBySelectString (s);
  3108 				if (dst)
  3109 				{	
  3110 					if (dst->isBranchLikeType())
  3111 						relinkImage ( ((ImageItem*)selti),(BranchItem*)dst);
  3112 				} else	
  3113 					parser.setError (Aborted,"Destination is not a branch");
  3114 			}		
  3115 		} else
  3116 			parser.setError (Aborted,"Type of selection is not a floatimage or branch");
  3117 	/////////////////////////////////////////////////////////////////////
  3118 	} else if (com=="loadImage")
  3119 	{
  3120 		if (!selti)
  3121 		{
  3122 			parser.setError (Aborted,"Nothing selected");
  3123 		} else if (! selbi )
  3124 		{				  
  3125 			parser.setError (Aborted,"Type of selection is not a branch");
  3126 		} else if (parser.checkParCount(1))
  3127 		{
  3128 			s=parser.parString(ok,0);
  3129 			if (ok) loadFloatImageInt (selbi,s);
  3130 		}	
  3131 	/////////////////////////////////////////////////////////////////////
  3132 	} else if (com=="moveUp")
  3133 	{
  3134 		if (!selti )
  3135 		{
  3136 			parser.setError (Aborted,"Nothing selected");
  3137 		} else if (! selbi )
  3138 		{				  
  3139 			parser.setError (Aborted,"Type of selection is not a branch");
  3140 		} else if (parser.checkParCount(0))
  3141 		{
  3142 			moveUp();
  3143 		}	
  3144 	/////////////////////////////////////////////////////////////////////
  3145 	} else if (com=="moveDown")
  3146 	{
  3147 		if (!selti )
  3148 		{
  3149 			parser.setError (Aborted,"Nothing selected");
  3150 		} else if (! selbi )
  3151 		{				  
  3152 			parser.setError (Aborted,"Type of selection is not a branch");
  3153 		} else if (parser.checkParCount(0))
  3154 		{
  3155 			moveDown();
  3156 		}	
  3157 	/////////////////////////////////////////////////////////////////////
  3158 	} else if (com=="move")
  3159 	{
  3160 		if (!selti )
  3161 		{
  3162 			parser.setError (Aborted,"Nothing selected");
  3163 		} else if ( selectionType()!=TreeItem::Branch  && 
  3164 					selectionType()!=TreeItem::MapCenter  &&
  3165 					selectionType()!=TreeItem::Image )
  3166 		{				  
  3167 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3168 		} else if (parser.checkParCount(2))
  3169 		{	
  3170 			x=parser.parDouble (ok,0);
  3171 			if (ok)
  3172 			{
  3173 				y=parser.parDouble (ok,1);
  3174 				if (ok) move (x,y);
  3175 			}
  3176 		}	
  3177 	/////////////////////////////////////////////////////////////////////
  3178 	} else if (com=="moveRel")
  3179 	{
  3180 		if (!selti )
  3181 		{
  3182 			parser.setError (Aborted,"Nothing selected");
  3183 		} else if ( selectionType()!=TreeItem::Branch  && 
  3184 					selectionType()!=TreeItem::MapCenter  &&
  3185 					selectionType()!=TreeItem::Image )
  3186 		{				  
  3187 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3188 		} else if (parser.checkParCount(2))
  3189 		{	
  3190 			x=parser.parDouble (ok,0);
  3191 			if (ok)
  3192 			{
  3193 				y=parser.parDouble (ok,1);
  3194 				if (ok) moveRel (x,y);
  3195 			}
  3196 		}	
  3197 	/////////////////////////////////////////////////////////////////////
  3198 	} else if (com=="nop")
  3199 	{
  3200 	/////////////////////////////////////////////////////////////////////
  3201 	} else if (com=="paste")
  3202 	{
  3203 		if (!selti )
  3204 		{
  3205 			parser.setError (Aborted,"Nothing selected");
  3206 		} else if (! selbi )
  3207 		{				  
  3208 			parser.setError (Aborted,"Type of selection is not a branch");
  3209 		} else if (parser.checkParCount(1))
  3210 		{	
  3211 			n=parser.parInt (ok,0);
  3212 			if (ok) pasteNoSave(n);
  3213 		}	
  3214 	/////////////////////////////////////////////////////////////////////
  3215 	} else if (com=="qa")
  3216 	{
  3217 		if (!selti )
  3218 		{
  3219 			parser.setError (Aborted,"Nothing selected");
  3220 		} else if (! selbi )
  3221 		{				  
  3222 			parser.setError (Aborted,"Type of selection is not a branch");
  3223 		} else if (parser.checkParCount(4))
  3224 		{	
  3225 			QString c,u;
  3226 			c=parser.parString (ok,0);
  3227 			if (!ok)
  3228 			{
  3229 				parser.setError (Aborted,"No comment given");
  3230 			} else
  3231 			{
  3232 				s=parser.parString (ok,1);
  3233 				if (!ok)
  3234 				{
  3235 					parser.setError (Aborted,"First parameter is not a string");
  3236 				} else
  3237 				{
  3238 					t=parser.parString (ok,2);
  3239 					if (!ok)
  3240 					{
  3241 						parser.setError (Aborted,"Condition is not a string");
  3242 					} else
  3243 					{
  3244 						u=parser.parString (ok,3);
  3245 						if (!ok)
  3246 						{
  3247 							parser.setError (Aborted,"Third parameter is not a string");
  3248 						} else
  3249 						{
  3250 							if (s!="heading")
  3251 							{
  3252 								parser.setError (Aborted,"Unknown type: "+s);
  3253 							} else
  3254 							{
  3255 								if (! (t=="eq") ) 
  3256 								{
  3257 									parser.setError (Aborted,"Unknown operator: "+t);
  3258 								} else
  3259 								{
  3260 									if (! selbi    )
  3261 									{
  3262 										parser.setError (Aborted,"Type of selection is not a branch");
  3263 									} else
  3264 									{
  3265 										if (selbi->getHeading() == u)
  3266 										{
  3267 											cout << "PASSED: " << qPrintable (c)  << endl;
  3268 										} else
  3269 										{
  3270 											cout << "FAILED: " << qPrintable (c)  << endl;
  3271 										}
  3272 									}
  3273 								}
  3274 							}
  3275 						} 
  3276 					} 
  3277 				} 
  3278 			}
  3279 		}	
  3280 	/////////////////////////////////////////////////////////////////////
  3281 	} else if (com=="saveImage")
  3282 	{
  3283 		ImageItem *ii=getSelectedImageItem();
  3284 		if (!ii )
  3285 		{
  3286 			parser.setError (Aborted,"No image selected");
  3287 		} else if (parser.checkParCount(2))
  3288 		{
  3289 			s=parser.parString(ok,0);
  3290 			if (ok)
  3291 			{
  3292 				t=parser.parString(ok,1);
  3293 				if (ok) saveFloatImageInt (ii,t,s);
  3294 			}
  3295 		}	
  3296 	/////////////////////////////////////////////////////////////////////
  3297 	} else if (com=="scroll")
  3298 	{
  3299 		if (!selti)
  3300 		{
  3301 			parser.setError (Aborted,"Nothing selected");
  3302 		} else if (! selbi )
  3303 		{				  
  3304 			parser.setError (Aborted,"Type of selection is not a branch");
  3305 		} else if (parser.checkParCount(0))
  3306 		{	
  3307 			if (!scrollBranch (selbi))	
  3308 				parser.setError (Aborted,"Could not scroll branch");
  3309 		}	
  3310 	/////////////////////////////////////////////////////////////////////
  3311 	} else if (com=="select")
  3312 	{
  3313 		if (parser.checkParCount(1))
  3314 		{
  3315 			s=parser.parString(ok,0);
  3316 			if (ok) select (s);
  3317 		}	
  3318 	/////////////////////////////////////////////////////////////////////
  3319 	} else if (com=="selectLastBranch")
  3320 	{
  3321 		if (!selti )
  3322 		{
  3323 			parser.setError (Aborted,"Nothing selected");
  3324 		} else if (! selbi )
  3325 		{				  
  3326 			parser.setError (Aborted,"Type of selection is not a branch");
  3327 		} else if (parser.checkParCount(0))
  3328 		{	
  3329 			BranchItem *bi=selbi->getLastBranch();
  3330 			if (!bi)
  3331 				parser.setError (Aborted,"Could not select last branch");
  3332 			select (bi);		// FIXME-3 was selectInt
  3333 				
  3334 		}	
  3335 	/////////////////////////////////////////////////////////////////////
  3336 	} else /* FIXME-2 if (com=="selectLastImage")
  3337 	{
  3338 		if (!selti )
  3339 		{
  3340 			parser.setError (Aborted,"Nothing selected");
  3341 		} else if (! selbi )
  3342 		{				  
  3343 			parser.setError (Aborted,"Type of selection is not a branch");
  3344 		} else if (parser.checkParCount(0))
  3345 		{	
  3346 			FloatImageObj *fio=selb->getLastFloatImage();
  3347 			if (!fio)
  3348 				parser.setError (Aborted,"Could not select last image");
  3349 			select (fio);		// FIXME-3 was selectInt
  3350 				
  3351 		}	
  3352 	/////////////////////////////////////////////////////////////////////
  3353 	} else */ if (com=="selectLatestAdded")
  3354 	{
  3355 		if (!latestAddedItem)
  3356 		{
  3357 			parser.setError (Aborted,"No latest added object");
  3358 		} else
  3359 		{	
  3360 			if (!select (latestAddedItem))
  3361 				parser.setError (Aborted,"Could not select latest added object ");
  3362 		}	
  3363 	/////////////////////////////////////////////////////////////////////
  3364 	} else if (com=="setFrameType")
  3365 	{
  3366 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3367 		{
  3368 			parser.setError (Aborted,"Type of selection does not allow setting frame type");
  3369 		}
  3370 		else if (parser.checkParCount(1))
  3371 		{
  3372 			s=parser.parString(ok,0);
  3373 			if (ok) setFrameType (s);
  3374 		}	
  3375 	/////////////////////////////////////////////////////////////////////
  3376 	} else if (com=="setFramePenColor")
  3377 	{
  3378 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3379 		{
  3380 			parser.setError (Aborted,"Type of selection does not allow setting of pen color");
  3381 		}
  3382 		else if (parser.checkParCount(1))
  3383 		{
  3384 			QColor c=parser.parColor(ok,0);
  3385 			if (ok) setFramePenColor (c);
  3386 		}	
  3387 	/////////////////////////////////////////////////////////////////////
  3388 	} else if (com=="setFrameBrushColor")
  3389 	{
  3390 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3391 		{
  3392 			parser.setError (Aborted,"Type of selection does not allow setting brush color");
  3393 		}
  3394 		else if (parser.checkParCount(1))
  3395 		{
  3396 			QColor c=parser.parColor(ok,0);
  3397 			if (ok) setFrameBrushColor (c);
  3398 		}	
  3399 	/////////////////////////////////////////////////////////////////////
  3400 	} else if (com=="setFramePadding")
  3401 	{
  3402 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3403 		{
  3404 			parser.setError (Aborted,"Type of selection does not allow setting frame padding");
  3405 		}
  3406 		else if (parser.checkParCount(1))
  3407 		{
  3408 			n=parser.parInt(ok,0);
  3409 			if (ok) setFramePadding(n);
  3410 		}	
  3411 	/////////////////////////////////////////////////////////////////////
  3412 	} else if (com=="setFrameBorderWidth")
  3413 	{
  3414 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3415 		{
  3416 			parser.setError (Aborted,"Type of selection does not allow setting frame border width");
  3417 		}
  3418 		else if (parser.checkParCount(1))
  3419 		{
  3420 			n=parser.parInt(ok,0);
  3421 			if (ok) setFrameBorderWidth (n);
  3422 		}	
  3423 	/////////////////////////////////////////////////////////////////////
  3424 	} else if (com=="setMapAuthor")
  3425 	{
  3426 		if (parser.checkParCount(1))
  3427 		{
  3428 			s=parser.parString(ok,0);
  3429 			if (ok) setAuthor (s);
  3430 		}	
  3431 	/////////////////////////////////////////////////////////////////////
  3432 	} else if (com=="setMapComment")
  3433 	{
  3434 		if (parser.checkParCount(1))
  3435 		{
  3436 			s=parser.parString(ok,0);
  3437 			if (ok) setComment(s);
  3438 		}	
  3439 	/////////////////////////////////////////////////////////////////////
  3440 	} else if (com=="setMapBackgroundColor")
  3441 	{
  3442 		if (!selti )
  3443 		{
  3444 			parser.setError (Aborted,"Nothing selected");
  3445 		} else if (! selbi )
  3446 		{				  
  3447 			parser.setError (Aborted,"Type of selection is not a branch");
  3448 		} else if (parser.checkParCount(1))
  3449 		{
  3450 			QColor c=parser.parColor (ok,0);
  3451 			if (ok) setMapBackgroundColor (c);
  3452 		}	
  3453 	/////////////////////////////////////////////////////////////////////
  3454 	} else if (com=="setMapDefLinkColor")
  3455 	{
  3456 		if (!selti )
  3457 		{
  3458 			parser.setError (Aborted,"Nothing selected");
  3459 		} else if (! selbi )
  3460 		{				  
  3461 			parser.setError (Aborted,"Type of selection is not a branch");
  3462 		} else if (parser.checkParCount(1))
  3463 		{
  3464 			QColor c=parser.parColor (ok,0);
  3465 			if (ok) setMapDefLinkColor (c);
  3466 		}	
  3467 	/////////////////////////////////////////////////////////////////////
  3468 	} else if (com=="setMapLinkStyle")
  3469 	{
  3470 		if (parser.checkParCount(1))
  3471 		{
  3472 			s=parser.parString (ok,0);
  3473 			if (ok) setMapLinkStyle(s);
  3474 		}	
  3475 	/////////////////////////////////////////////////////////////////////
  3476 	} else if (com=="setHeading")
  3477 	{
  3478 		if (!selti )
  3479 		{
  3480 			parser.setError (Aborted,"Nothing selected");
  3481 		} else if (! selbi )
  3482 		{				  
  3483 			parser.setError (Aborted,"Type of selection is not a branch");
  3484 		} else if (parser.checkParCount(1))
  3485 		{
  3486 			s=parser.parString (ok,0);
  3487 			if (ok) 
  3488 				setHeading (s);
  3489 		}	
  3490 	/////////////////////////////////////////////////////////////////////
  3491 	} else if (com=="setHideExport")
  3492 	{
  3493 		if (!selti )
  3494 		{
  3495 			parser.setError (Aborted,"Nothing selected");
  3496 		} else if (selectionType()!=TreeItem::Branch && selectionType() != TreeItem::MapCenter &&selectionType()!=TreeItem::Image)
  3497 		{				  
  3498 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3499 		} else if (parser.checkParCount(1))
  3500 		{
  3501 			b=parser.parBool(ok,0);
  3502 			if (ok) setHideExport (b);
  3503 		}
  3504 	/////////////////////////////////////////////////////////////////////
  3505 	} else if (com=="setIncludeImagesHorizontally")
  3506 	{ 
  3507 		if (!selti )
  3508 		{
  3509 			parser.setError (Aborted,"Nothing selected");
  3510 		} else if (! selbi)
  3511 		{				  
  3512 			parser.setError (Aborted,"Type of selection is not a branch");
  3513 		} else if (parser.checkParCount(1))
  3514 		{
  3515 			b=parser.parBool(ok,0);
  3516 			if (ok) setIncludeImagesHor(b);
  3517 		}
  3518 	/////////////////////////////////////////////////////////////////////
  3519 	} else if (com=="setIncludeImagesVertically")
  3520 	{
  3521 		if (!selti )
  3522 		{
  3523 			parser.setError (Aborted,"Nothing selected");
  3524 		} else if (! selbi)
  3525 		{				  
  3526 			parser.setError (Aborted,"Type of selection is not a branch");
  3527 		} else if (parser.checkParCount(1))
  3528 		{
  3529 			b=parser.parBool(ok,0);
  3530 			if (ok) setIncludeImagesVer(b);
  3531 		}
  3532 	/////////////////////////////////////////////////////////////////////
  3533 	} else if (com=="setHideLinkUnselected")
  3534 	{
  3535 		if (!selti )
  3536 		{
  3537 			parser.setError (Aborted,"Nothing selected");
  3538 		} else if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3539 		{				  
  3540 			parser.setError (Aborted,"Type of selection does not allow hiding the link");
  3541 		} else if (parser.checkParCount(1))
  3542 		{
  3543 			b=parser.parBool(ok,0);
  3544 			if (ok) setHideLinkUnselected(b);
  3545 		}
  3546 	/////////////////////////////////////////////////////////////////////
  3547 	} else if (com=="setSelectionColor")
  3548 	{
  3549 		if (parser.checkParCount(1))
  3550 		{
  3551 			QColor c=parser.parColor (ok,0);
  3552 			if (ok) setSelectionColorInt (c);
  3553 		}	
  3554 	/////////////////////////////////////////////////////////////////////
  3555 	} else if (com=="setURL")
  3556 	{
  3557 		if (!selti )
  3558 		{
  3559 			parser.setError (Aborted,"Nothing selected");
  3560 		} else if (! selbi )
  3561 		{				  
  3562 			parser.setError (Aborted,"Type of selection is not a branch");
  3563 		} else if (parser.checkParCount(1))
  3564 		{
  3565 			s=parser.parString (ok,0);
  3566 			if (ok) setURL(s);
  3567 		}	
  3568 	/////////////////////////////////////////////////////////////////////
  3569 	} else if (com=="setVymLink")
  3570 	{
  3571 		if (!selti )
  3572 		{
  3573 			parser.setError (Aborted,"Nothing selected");
  3574 		} else if (! selbi )
  3575 		{				  
  3576 			parser.setError (Aborted,"Type of selection is not a branch");
  3577 		} else if (parser.checkParCount(1))
  3578 		{
  3579 			s=parser.parString (ok,0);
  3580 			if (ok) setVymLink(s);
  3581 		}	
  3582 	}
  3583 	/////////////////////////////////////////////////////////////////////
  3584 	else if (com=="setFlag")
  3585 	{
  3586 		if (!selti )
  3587 		{
  3588 			parser.setError (Aborted,"Nothing selected");
  3589 		} else if (! selbi )
  3590 		{				  
  3591 			parser.setError (Aborted,"Type of selection is not a branch");
  3592 		} else if (parser.checkParCount(1))
  3593 		{
  3594 			s=parser.parString(ok,0);
  3595 			if (ok) 
  3596 				selbi->activateStandardFlag(s);
  3597 		}
  3598 	/////////////////////////////////////////////////////////////////////
  3599 	} else /* FIXME-2 if (com=="setFrameType")
  3600 	{
  3601 		if (!selti )
  3602 		{
  3603 			parser.setError (Aborted,"Nothing selected");
  3604 		} else if (! selb )
  3605 		{				  
  3606 			parser.setError (Aborted,"Type of selection is not a branch");
  3607 		} else if (parser.checkParCount(1))
  3608 		{
  3609 			s=parser.parString(ok,0);
  3610 			if (ok) 
  3611 				setFrameType (s);
  3612 		}
  3613 	/////////////////////////////////////////////////////////////////////
  3614 	} else*/ if (com=="sortChildren")
  3615 	{
  3616 		if (!selti )
  3617 		{
  3618 			parser.setError (Aborted,"Nothing selected");
  3619 		} else if (! selbi )
  3620 		{				  
  3621 			parser.setError (Aborted,"Type of selection is not a branch");
  3622 		} else if (parser.checkParCount(0))
  3623 		{
  3624 			sortChildren();
  3625 		}
  3626 	/////////////////////////////////////////////////////////////////////
  3627 	} else if (com=="toggleFlag")
  3628 	{
  3629 		if (!selti )
  3630 		{
  3631 			parser.setError (Aborted,"Nothing selected");
  3632 		} else if (! selbi )
  3633 		{				  
  3634 			parser.setError (Aborted,"Type of selection is not a branch");
  3635 		} else if (parser.checkParCount(1))
  3636 		{
  3637 			s=parser.parString(ok,0);
  3638 			if (ok) 
  3639 				selbi->toggleStandardFlag(s);	
  3640 		}
  3641 	/////////////////////////////////////////////////////////////////////
  3642 	} else  if (com=="unscroll")
  3643 	{
  3644 		if (!selti)
  3645 		{
  3646 			parser.setError (Aborted,"Nothing selected");
  3647 		} else if (! selbi )
  3648 		{				  
  3649 			parser.setError (Aborted,"Type of selection is not a branch");
  3650 		} else if (parser.checkParCount(0))
  3651 		{	
  3652 			if (!unscrollBranch (selbi))	
  3653 				parser.setError (Aborted,"Could not unscroll branch");
  3654 		}	
  3655 	/////////////////////////////////////////////////////////////////////
  3656 	} else if (com=="unscrollChildren")
  3657 	{
  3658 		if (!selti)
  3659 		{
  3660 			parser.setError (Aborted,"Nothing selected");
  3661 		} else if (! selbi )
  3662 		{				  
  3663 			parser.setError (Aborted,"Type of selection is not a branch");
  3664 		} else if (parser.checkParCount(0))
  3665 		{	
  3666 			unscrollChildren ();
  3667 		}	
  3668 	/////////////////////////////////////////////////////////////////////
  3669 	} else if (com=="unsetFlag")
  3670 	{
  3671 		if (!selti)
  3672 		{
  3673 			parser.setError (Aborted,"Nothing selected");
  3674 		} else if (! selbi )
  3675 		{				  
  3676 			parser.setError (Aborted,"Type of selection is not a branch");
  3677 		} else if (parser.checkParCount(1))
  3678 		{
  3679 			s=parser.parString(ok,0);
  3680 			if (ok) 
  3681 				selbi->deactivateStandardFlag(s);
  3682 		}
  3683 	} else 
  3684 		parser.setError (Aborted,"Unknown command");
  3685 
  3686 	// Any errors?
  3687 	if (parser.errorLevel()==NoError)
  3688 	{
  3689 		// setChanged();  FIXME-2 should not be called e.g. for export?!
  3690 		reposition();
  3691 	}	
  3692 	else	
  3693 	{
  3694 		// TODO Error handling
  3695 		qWarning("VymModel::parseAtom: Error!");
  3696 		qWarning(parser.errorMessage());
  3697 	} 
  3698 }
  3699 
  3700 void VymModel::runScript (QString script)
  3701 {
  3702 	parser.setScript (script);
  3703 	parser.runScript();
  3704 	while (parser.next() ) 
  3705 		parseAtom(parser.getAtom());
  3706 }
  3707 
  3708 void VymModel::setExportMode (bool b)
  3709 {
  3710 	// should be called before and after exports
  3711 	// depending on the settings
  3712 	if (b && settings.value("/export/useHideExport","true")=="true")
  3713 		setHideTmpMode (TreeItem::HideExport);
  3714 	else	
  3715 		setHideTmpMode (TreeItem::HideNone);
  3716 }
  3717 
  3718 void VymModel::exportImage(QString fname, bool askName, QString format)
  3719 {
  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 (getPixmap());
  3744 	pix.save(fname, format);
  3745 	setExportMode (false);
  3746 }
  3747 
  3748 
  3749 void VymModel::exportXML(QString dir, bool askForName)
  3750 {
  3751 	if (askForName)
  3752 	{
  3753 		dir=browseDirectory(NULL,tr("Export XML to directory"));
  3754 		if (dir =="" && !reallyWriteDirectory(dir) )
  3755 		return;
  3756 	}
  3757 
  3758 	// Hide stuff during export, if settings want this
  3759 	setExportMode (true);
  3760 
  3761 	// Create subdirectories
  3762 	makeSubDirs (dir);
  3763 
  3764 	// write to directory
  3765 	QString saveFile=saveToDir (dir,mapName+"-",true,getTotalBBox().topLeft() ,NULL);
  3766 	QFile file;
  3767 
  3768 	file.setName ( dir + "/"+mapName+".xml");
  3769 	if ( !file.open( QIODevice::WriteOnly ) )
  3770 	{
  3771 		// This should neverever happen
  3772 		QMessageBox::critical (0,tr("Critical Export Error"),tr("VymModel::exportXML couldn't open %1").arg(file.name()));
  3773 		return;
  3774 	}	
  3775 
  3776 	// Write it finally, and write in UTF8, no matter what 
  3777 	QTextStream ts( &file );
  3778 	ts.setEncoding (QTextStream::UnicodeUTF8);
  3779 	ts << saveFile;
  3780 	file.close();
  3781 
  3782 	// Now write image, too
  3783 	exportImage (dir+"/images/"+mapName+".png",false,"PNG");
  3784 
  3785 	setExportMode (false);
  3786 }
  3787 
  3788 void VymModel::exportASCII(QString fname,bool askName)
  3789 {
  3790 	ExportASCII ex;
  3791 	ex.setModel (this);
  3792 	if (fname=="") 
  3793 		ex.setFile (mapName+".txt");	
  3794 	else
  3795 		ex.setFile (fname);
  3796 
  3797 	if (askName)
  3798 	{
  3799 		//ex.addFilter ("TXT (*.txt)");
  3800 		ex.setDir(lastImageDir);
  3801 		//ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
  3802 		ex.execDialog() ; 
  3803 	} 
  3804 	if (!ex.canceled())
  3805 	{
  3806 		setExportMode(true);
  3807 		ex.doExport();
  3808 		setExportMode(false);
  3809 	}
  3810 }
  3811 
  3812 void VymModel::exportXHTML (const QString &dir, bool askForName)
  3813 {
  3814 			ExportXHTMLDialog dia(NULL);
  3815 			dia.setFilePath (filePath );
  3816 			dia.setMapName (mapName );
  3817 			dia.readSettings();
  3818 			if (dir!="") dia.setDir (dir);
  3819 
  3820 			bool ok=true;
  3821 			
  3822 			if (askForName)
  3823 			{
  3824 				if (dia.exec()!=QDialog::Accepted) 
  3825 					ok=false;
  3826 				else	
  3827 				{
  3828 					QDir d (dia.getDir());
  3829 					// Check, if warnings should be used before overwriting
  3830 					// the output directory
  3831 					if (d.exists() && d.count()>0)
  3832 					{
  3833 						WarningDialog warn;
  3834 						warn.showCancelButton (true);
  3835 						warn.setText(QString(
  3836 							"The directory %1 is not empty.\n"
  3837 							"Do you risk to overwrite some of its contents?").arg(d.path() ));
  3838 						warn.setCaption("Warning: Directory not empty");
  3839 						warn.setShowAgainName("mainwindow/overwrite-dir-xhtml");
  3840 
  3841 						if (warn.exec()!=QDialog::Accepted) ok=false;
  3842 					}
  3843 				}	
  3844 			}
  3845 
  3846 			if (ok)
  3847 			{
  3848 				exportXML (dia.getDir(),false );
  3849 				dia.doExport(mapName );
  3850 				//if (dia.hasChanged()) setChanged();
  3851 			}
  3852 }
  3853 
  3854 void VymModel::exportOOPresentation(const QString &fn, const QString &cf)
  3855 {
  3856 	ExportOO ex;
  3857 	ex.setFile (fn);
  3858 	ex.setModel (this);
  3859 	if (ex.setConfigFile(cf)) 
  3860 	{
  3861 		setExportMode (true);
  3862 		ex.exportPresentation();
  3863 		setExportMode (false);
  3864 	}
  3865 }
  3866 
  3867 
  3868 
  3869 
  3870 //////////////////////////////////////////////
  3871 // View related
  3872 //////////////////////////////////////////////
  3873 
  3874 void VymModel::registerEditor(QWidget *me)
  3875 {
  3876 	mapEditor=(MapEditor*)me;
  3877 }
  3878 
  3879 void VymModel::unregisterEditor(QWidget *)
  3880 {
  3881 	mapEditor=NULL;
  3882 }
  3883 
  3884 void VymModel::setContextPos(QPointF p)
  3885 {
  3886 	contextPos=p;
  3887 }
  3888 
  3889 void VymModel::unsetContextPos()
  3890 {
  3891 	contextPos=QPointF();
  3892 }
  3893 
  3894 void VymModel::updateNoteFlag()
  3895 {
  3896 	setChanged();
  3897 	TreeItem *selti=getSelectedItem();
  3898 	if (selti)
  3899 	{
  3900 		if (textEditor->isEmpty()) 
  3901 			selti->clearNote();
  3902 		else
  3903 			selti->setNote (textEditor->getText());
  3904 		emitDataHasChanged(selti);		
  3905 		emitSelectionChanged();
  3906 
  3907 	}
  3908 }
  3909 
  3910 void VymModel::updateRelPositions()		//FIXME-3 VM should have no need to updateRelPos
  3911 {
  3912 	/* FIXME-3 ???
  3913 	for (int i=0; i<rootItem->branchCount(); i++)
  3914 		((MapCenterObj*)rootItem->getBranchObjNum(i))->updateRelPositions();
  3915 		*/
  3916 		/*
  3917 	void MapCenterObj::updateRelPositions()
  3918 	{
  3919 		if (repositionRequest) unsetAllRepositionRequests();
  3920 
  3921 		// update relative Positions of branches and floats
  3922 		for (int i=0; i<treeItem->branchCount(); ++i)
  3923 		{
  3924 			treeItem->getBranchObjNum(i)->setRelPos();
  3925 			treeItem->getBranchObjNum(i)->setOrientation();
  3926 		}
  3927 		
  3928 		for (int i=0; i<floatimage.size(); ++i)
  3929 			floatimage.at(i)->setRelPos();
  3930 
  3931 		if (repositionRequest) reposition();
  3932 	}
  3933 	*/
  3934 }
  3935 
  3936 void VymModel::reposition()	//FIXME-3 VM should have no need to reposition, this is done in views???
  3937 {
  3938 	//cout << "VM::reposition blocked="<<blockReposition<<endl;
  3939 	if (blockReposition) return;
  3940 
  3941 	for (int i=0;i<rootItem->branchCount(); i++)
  3942 		rootItem->getBranchObjNum(i)->reposition();	//	for positioning heading
  3943 }
  3944 
  3945 /*
  3946 QPolygonF VymModel::shape(BranchObj *bo)	//FIXME-4
  3947 {
  3948 	return QPolygonF ();
  3949 	// Creating (arbitrary) shapes
  3950 
  3951 	QPolygonF p;
  3952 	QRectF rb=bo->getBBox();
  3953 	if (bo->getDepth()==0)
  3954 	{
  3955 		// Just take BBox of this mapCenter
  3956 		p<<rb.topLeft()<<rb.topRight()<<rb.bottomRight()<<rb.bottomLeft();
  3957 		return p;
  3958 	}
  3959 
  3960 	// Take union of BBox and TotalBBox 
  3961 
  3962 	QRectF ra=bo->getTotalBBox();
  3963 	if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
  3964 		p   <<ra.bottomLeft()
  3965 			<<ra.topLeft()
  3966 			<<QPointF (rb.topLeft().x(), ra.topLeft().y() )
  3967 			<<rb.topRight()
  3968 			<<rb.bottomRight()
  3969 			<<QPointF (rb.bottomLeft().x(), ra.bottomLeft().y() ) ;
  3970 	else		
  3971 		p   <<ra.bottomRight()
  3972 			<<ra.topRight()
  3973 			<<QPointF (rb.topRight().x(), ra.topRight().y() )
  3974 			<<rb.topLeft()
  3975 			<<rb.bottomLeft()
  3976 			<<QPointF (rb.bottomRight().x(), ra.bottomRight().y() ) ;
  3977 	return p;		
  3978 }
  3979 */
  3980 
  3981 /*
  3982 void VymModel::moveAway(LinkableMapObj *lmo)	//FIXME-5
  3983 {
  3984 	// Autolayout:
  3985 	//
  3986 	// Move all branches and MapCenters away from lmo 
  3987 	// to avoid collisions 
  3988 
  3989 	QPolygonF pA;
  3990 	QPolygonF pB;
  3991 
  3992 	BranchObj *boA=(BranchObj*)lmo;
  3993 	BranchObj *boB;
  3994 	for (int i=0; i<rootItem->branchCount(); i++)
  3995 	{
  3996 		boB=rootItem->getBranchNum(i);
  3997 		pA=shape (boA);
  3998 		pB=shape (boB);
  3999 		PolygonCollisionResult r = PolygonCollision(pA, pB, QPoint(0,0));
  4000 		cout <<"------->"
  4001 			<<"="<<r.intersect
  4002 			<<"  ("<<qPrintable(boA->getHeading() )<<")"
  4003 			<<"  with ("<< qPrintable (boB->getHeading() )
  4004 			<<")  willIntersect"
  4005 			<<r.willIntersect 
  4006 			<<"  minT="<<r.minTranslation<<endl<<endl;
  4007 	}
  4008 }
  4009 */
  4010 
  4011 QPixmap VymModel::getPixmap()
  4012 {
  4013 	QRectF mapRect=getTotalBBox();
  4014 	QPixmap pix((int)mapRect.width()+2,(int)mapRect.height()+1);
  4015 	QPainter pp (&pix);
  4016 	
  4017 	pp.setRenderHints(mapEditor->renderHints());
  4018 
  4019 	// Don't print the visualisation of selection
  4020 	unselect();
  4021 
  4022 	mapScene->render (	&pp, 
  4023 		QRectF(0,0,mapRect.width()+2,mapRect.height()+2),
  4024 		QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
  4025 
  4026 	// Restore selection
  4027 	reselect();
  4028 	
  4029 	return pix;
  4030 }
  4031 
  4032 
  4033 void VymModel::setMapLinkStyle (const QString & s)
  4034 {
  4035 	QString snow;
  4036 	switch (linkstyle)
  4037 	{
  4038 		case LinkableMapObj::Line :
  4039 			snow="StyleLine";
  4040 			break;
  4041 		case LinkableMapObj::Parabel:
  4042 			snow="StyleParabel";
  4043 			break;
  4044 		case LinkableMapObj::PolyLine:
  4045 			snow="StylePolyLine";
  4046 			break;
  4047 		case LinkableMapObj::PolyParabel:
  4048 			snow="StylePolyParabel";
  4049 			break;
  4050 		default:	
  4051 			snow="UndefinedStyle";
  4052 			break;
  4053 	}
  4054 
  4055 	saveState (
  4056 		QString("setMapLinkStyle (\"%1\")").arg(s),
  4057 		QString("setMapLinkStyle (\"%1\")").arg(snow),
  4058 		QString("Set map link style (\"%1\")").arg(s)
  4059 	);	
  4060 
  4061 	if (s=="StyleLine")
  4062 		linkstyle=LinkableMapObj::Line;
  4063 	else if (s=="StyleParabel")
  4064 		linkstyle=LinkableMapObj::Parabel;
  4065 	else if (s=="StylePolyLine")
  4066 		linkstyle=LinkableMapObj::PolyLine;
  4067 	else if (s=="StylePolyParabel")	
  4068 		linkstyle=LinkableMapObj::PolyParabel;
  4069 	else
  4070 		linkstyle=LinkableMapObj::UndefinedStyle;
  4071 
  4072 	BranchItem *cur=NULL;
  4073 	BranchItem *prev=NULL;
  4074 	BranchObj *bo;
  4075 	next (cur,prev);
  4076 	while (cur) 
  4077 	{
  4078 		bo=(BranchObj*)(cur->getLMO() );
  4079 		bo->setLinkStyle(bo->getDefLinkStyle());
  4080 		cur=next(cur,prev);
  4081 	}
  4082 	reposition();
  4083 }
  4084 
  4085 LinkableMapObj::Style VymModel::getMapLinkStyle ()
  4086 {
  4087 	return linkstyle;
  4088 }	
  4089 
  4090 void VymModel::setMapDefLinkColor(QColor col)
  4091 {
  4092 	if ( !col.isValid() ) return;
  4093 	saveState (
  4094 		QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
  4095 		QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
  4096 		QString("Set map link color to %1").arg(col.name())
  4097 	);
  4098 
  4099 	defLinkColor=col;
  4100 	BranchItem *cur=NULL;
  4101 	BranchItem *prev=NULL;
  4102 	BranchObj *bo;
  4103 	cur=next(cur,prev);
  4104 	while (cur) 
  4105 	{
  4106 		bo=(BranchObj*)(cur->getLMO() );
  4107 		bo->setLinkColor();
  4108 		next(cur,prev);
  4109 	}
  4110 	updateActions();
  4111 }
  4112 
  4113 void VymModel::setMapLinkColorHintInt()
  4114 {
  4115 	// called from setMapLinkColorHint(lch) or at end of parse
  4116 	BranchItem *cur=NULL;
  4117 	BranchItem *prev=NULL;
  4118 	BranchObj *bo;
  4119 	cur=next(cur,prev);
  4120 	while (cur) 
  4121 	{
  4122 		bo=(BranchObj*)(cur->getLMO() );
  4123 		bo->setLinkColor();
  4124 		cur=next(cur,prev);
  4125 	}
  4126 }
  4127 
  4128 void VymModel::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
  4129 {
  4130 	linkcolorhint=lch;
  4131 	setMapLinkColorHintInt();
  4132 }
  4133 
  4134 void VymModel::toggleMapLinkColorHint()
  4135 {
  4136 	if (linkcolorhint==LinkableMapObj::HeadingColor)
  4137 		linkcolorhint=LinkableMapObj::DefaultColor;
  4138 	else	
  4139 		linkcolorhint=LinkableMapObj::HeadingColor;
  4140 	BranchItem *cur=NULL;
  4141 	BranchItem *prev=NULL;
  4142 	BranchObj *bo;
  4143 	cur=next(cur,prev);
  4144 	while (cur) 
  4145 	{
  4146 		bo=(BranchObj*)(cur->getLMO() );
  4147 		bo->setLinkColor();
  4148 		next(cur,prev);
  4149 	}
  4150 }
  4151 
  4152 void VymModel::selectMapBackgroundImage ()	// FIXME-2 move to ME
  4153 {
  4154 	Q3FileDialog *fd=new Q3FileDialog( NULL);
  4155 	fd->setMode (Q3FileDialog::ExistingFile);
  4156 	fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  4157 	ImagePreview *p =new ImagePreview (fd);
  4158 	fd->setContentsPreviewEnabled( TRUE );
  4159 	fd->setContentsPreview( p, p );
  4160 	fd->setPreviewMode( Q3FileDialog::Contents );
  4161 	fd->setCaption(vymName+" - " +tr("Load background image"));
  4162 	fd->setDir (lastImageDir);
  4163 	fd->show();
  4164 
  4165 	if ( fd->exec() == QDialog::Accepted )
  4166 	{
  4167 		// TODO selectMapBackgroundImg in QT4 use:	lastImageDir=fd->directory();
  4168 		lastImageDir=QDir (fd->dirPath());
  4169 		setMapBackgroundImage (fd->selectedFile());
  4170 	}
  4171 }	
  4172 
  4173 void VymModel::setMapBackgroundImage (const QString &fn)	//FIXME-2 missing savestate
  4174 {
  4175 	QColor oldcol=mapScene->backgroundBrush().color();
  4176 	/*
  4177 	saveState(
  4178 		selection,
  4179 		QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
  4180 		selection,
  4181 		QString ("setMapBackgroundImage (%1)").arg(col.name()),
  4182 		QString("Set background color of map to %1").arg(col.name()));
  4183 	*/	
  4184 	QBrush brush;
  4185 	brush.setTextureImage (QPixmap (fn));
  4186 	mapScene->setBackgroundBrush(brush);
  4187 }
  4188 
  4189 void VymModel::selectMapBackgroundColor()	// FIXME-3 move to ME
  4190 {
  4191 	QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), NULL);
  4192 	if ( !col.isValid() ) return;
  4193 	setMapBackgroundColor( col );
  4194 }
  4195 
  4196 
  4197 void VymModel::setMapBackgroundColor(QColor col)	// FIXME-3 move to ME
  4198 {
  4199 	QColor oldcol=mapScene->backgroundBrush().color();
  4200 	saveState(
  4201 		QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
  4202 		QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
  4203 		QString("Set background color of map to %1").arg(col.name()));
  4204 	mapScene->setBackgroundBrush(col);
  4205 }
  4206 
  4207 QColor VymModel::getMapBackgroundColor()	// FIXME-3 move to ME
  4208 {
  4209     return mapScene->backgroundBrush().color();
  4210 }
  4211 
  4212 
  4213 LinkableMapObj::ColorHint VymModel::getMapLinkColorHint()	// FIXME-3 move to ME
  4214 {
  4215 	return linkcolorhint;
  4216 }
  4217 
  4218 QColor VymModel::getMapDefLinkColor()	// FIXME-3 move to ME
  4219 {
  4220 	return defLinkColor;
  4221 }
  4222 
  4223 void VymModel::setMapDefXLinkColor(QColor col)	// FIXME-3 move to ME
  4224 {
  4225 	defXLinkColor=col;
  4226 }
  4227 
  4228 QColor VymModel::getMapDefXLinkColor()	// FIXME-3 move to ME
  4229 {
  4230 	return defXLinkColor;
  4231 }
  4232 
  4233 void VymModel::setMapDefXLinkWidth (int w)	// FIXME-3 move to ME
  4234 {
  4235 	defXLinkWidth=w;
  4236 }
  4237 
  4238 int VymModel::getMapDefXLinkWidth()	// FIXME-3 move to ME
  4239 {
  4240 	return defXLinkWidth;
  4241 }
  4242 
  4243 void VymModel::move(const double &x, const double &y)	// FIXME-3
  4244 {
  4245 	int i=x; i=y;
  4246 /*
  4247 	BranchObj *bo = getSelectedBranch();
  4248 	if (bo && 
  4249 		(selectionType()==TreeItem::Branch ||
  4250 		 selectionType()==TreeItem::MapCenter ||
  4251 		 selectionType()==TreeItem::Image
  4252 		))
  4253 	{
  4254         QPointF ap(bo->getAbsPos());
  4255         QPointF to(x, y);
  4256         if (ap != to)
  4257         {
  4258             QString ps=qpointfToString(ap);
  4259             QString s=getSelectString();
  4260             saveState(
  4261                 s, "move "+ps, 
  4262                 s, "move "+qpointfToString(to), 
  4263                 QString("Move %1 to %2").arg(getObjectName(bo)).arg(ps));
  4264             bo->move(x,y);
  4265             reposition();
  4266             emitSelectionChanged();
  4267         }
  4268 	}
  4269 */	
  4270 }
  4271 
  4272 void VymModel::moveRel (const double &x, const double &y)	// FIXME-3
  4273 {
  4274 	int i=x; i=y;
  4275 /*
  4276 	BranchObj *bo = getSelectedBranch();
  4277 	if (bo && 
  4278 		(selectionType()==TreeItem::Branch ||
  4279 		 selectionType()==TreeItem::MapCenter ||
  4280 		 selectionType()==TreeItem::Image
  4281 		))
  4282 	if (bo)
  4283 	{
  4284         QPointF rp(bo->getRelPos());
  4285         QPointF to(x, y);
  4286         if (rp != to)
  4287         {
  4288             QString ps=qpointfToString (bo->getRelPos());
  4289             QString s=getSelectString(bo);
  4290             saveState(
  4291                 s, "moveRel "+ps, 
  4292                 s, "moveRel "+qpointfToString(to), 
  4293                 QString("Move %1 to relative position %2").arg(getObjectName(bo)).arg(ps));
  4294             ((OrnamentedObj*)bo)->move2RelPos (x,y);
  4295             reposition();
  4296             bo->updateLinkGeometry();
  4297             emitSelectionChanged();
  4298         }
  4299 	}
  4300 */	
  4301 }
  4302 
  4303 
  4304 void VymModel::animate()
  4305 {
  4306 	animationTimer->stop();
  4307 	BranchObj *bo;
  4308 	int i=0;
  4309 	while (i<animObjList.size() )
  4310 	{
  4311 		bo=(BranchObj*)animObjList.at(i);
  4312 		if (!bo->animate())
  4313 		{
  4314 			if (i>=0) 
  4315 			{	
  4316 				animObjList.removeAt(i);
  4317 				i--;
  4318 			}
  4319 		}
  4320 		bo->reposition();
  4321 		i++;
  4322 	} 
  4323 	QItemSelection sel=selModel->selection();
  4324 	emit (selectionChanged(sel,sel));
  4325 
  4326 	mapScene->update();
  4327 	if (!animObjList.isEmpty()) animationTimer->start();
  4328 }
  4329 
  4330 
  4331 void VymModel::startAnimation(BranchObj *bo, const QPointF &start, const QPointF &dest)
  4332 {
  4333 	if (bo && bo->getTreeItem()->depth()>0) 
  4334 	{
  4335 		AnimPoint ap;
  4336 		ap.setStart (start);
  4337 		ap.setDest  (dest);
  4338 		ap.setTicks (animationTicks);
  4339 		ap.setAnimated (true);
  4340 		bo->setAnimation (ap);
  4341 		animObjList.append( bo );
  4342 		animationTimer->setSingleShot (true);
  4343 		animationTimer->start(animationInterval);
  4344 	}
  4345 }
  4346 
  4347 void VymModel::stopAnimation (MapObj *mo)
  4348 {
  4349 	int i=animObjList.indexOf(mo);
  4350     if (i>=0)
  4351 		animObjList.removeAt (i);
  4352 }
  4353 
  4354 void VymModel::sendSelection()
  4355 {
  4356 	if (netstate!=Server) return;
  4357 	sendData (QString("select (\"%1\")").arg(getSelectString()) );
  4358 }
  4359 
  4360 void VymModel::newServer()
  4361 {
  4362 	port=54321;
  4363 	sendCounter=0;
  4364     tcpServer = new QTcpServer(this);
  4365     if (!tcpServer->listen(QHostAddress::Any,port)) {
  4366         QMessageBox::critical(NULL, "vym server",
  4367                               QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
  4368         //FIXME-3 needed? we are no widget any longer... close();
  4369         return;
  4370     }
  4371 	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
  4372 	netstate=Server;
  4373 	cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
  4374 }
  4375 
  4376 void VymModel::connectToServer()
  4377 {
  4378 	port=54321;
  4379 	server="salam.suse.de";
  4380 	server="localhost";
  4381 	clientSocket = new QTcpSocket (this);
  4382 	clientSocket->abort();
  4383     clientSocket->connectToHost(server ,port);
  4384 	connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
  4385     connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
  4386             this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
  4387 	netstate=Client;		
  4388 	cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
  4389 
  4390 	
  4391 }
  4392 
  4393 void VymModel::newClient()
  4394 {
  4395     QTcpSocket *newClient = tcpServer->nextPendingConnection();
  4396     connect(newClient, SIGNAL(disconnected()),
  4397             newClient, SLOT(deleteLater()));
  4398 
  4399 	cout <<"ME::newClient  at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
  4400 
  4401 	clientList.append (newClient);
  4402 }
  4403 
  4404 
  4405 void VymModel::sendData(const QString &s)
  4406 {
  4407 	if (clientList.size()==0) return;
  4408 
  4409 	// Create bytearray to send
  4410 	QByteArray block;
  4411     QDataStream out(&block, QIODevice::WriteOnly);
  4412     out.setVersion(QDataStream::Qt_4_0);
  4413 
  4414 	// Reserve some space for blocksize
  4415     out << (quint16)0;
  4416 
  4417 	// Write sendCounter
  4418     out << sendCounter++;
  4419 
  4420 	// Write data
  4421     out << s;
  4422 
  4423 	// Go back and write blocksize so far
  4424     out.device()->seek(0);
  4425     quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
  4426 	out << bs;
  4427 
  4428 	if (debug)
  4429 		cout << "ME::sendData  bs="<<bs<<"  counter="<<sendCounter<<"  s="<<qPrintable(s)<<endl;
  4430 
  4431 	for (int i=0; i<clientList.size(); ++i)
  4432 	{
  4433 		//cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
  4434 		clientList.at(i)->write (block);
  4435 	}
  4436 }
  4437 
  4438 void VymModel::readData ()
  4439 {
  4440 	while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
  4441 	{
  4442 		if (debug)
  4443 			cout <<"readData  bytesAvail="<<clientSocket->bytesAvailable();
  4444 		quint16 recCounter;
  4445 		quint16 blockSize;
  4446 
  4447 		QDataStream in(clientSocket);
  4448 		in.setVersion(QDataStream::Qt_4_0);
  4449 
  4450 		in >> blockSize;
  4451 		in >> recCounter;
  4452 		
  4453 		QString t;
  4454 		in >>t;
  4455 		if (debug)
  4456 			cout << "  t="<<qPrintable (t)<<endl;
  4457 		parseAtom (t);
  4458 	}
  4459 	return;
  4460 }
  4461 
  4462 void VymModel::displayNetworkError(QAbstractSocket::SocketError socketError)
  4463 {
  4464     switch (socketError) {
  4465     case QAbstractSocket::RemoteHostClosedError:
  4466         break;
  4467     case QAbstractSocket::HostNotFoundError:
  4468         QMessageBox::information(NULL, vymName +" Network client",
  4469                                  "The host was not found. Please check the "
  4470                                     "host name and port settings.");
  4471         break;
  4472     case QAbstractSocket::ConnectionRefusedError:
  4473         QMessageBox::information(NULL, vymName + " Network client",
  4474                                  "The connection was refused by the peer. "
  4475                                     "Make sure the fortune server is running, "
  4476                                     "and check that the host name and port "
  4477                                     "settings are correct.");
  4478         break;
  4479     default:
  4480         QMessageBox::information(NULL, vymName + " Network client",
  4481                                  QString("The following error occurred: %1.")
  4482                                  .arg(clientSocket->errorString()));
  4483     }
  4484 }
  4485 
  4486 
  4487 
  4488 
  4489 void VymModel::selectMapSelectionColor()
  4490 {
  4491 	QColor col = QColorDialog::getColor( defLinkColor, NULL);
  4492 	setSelectionColor (col);
  4493 }
  4494 
  4495 void VymModel::setSelectionColorInt (QColor col)
  4496 {
  4497 	if ( !col.isValid() ) return;
  4498 	saveState (
  4499 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4500 		QString("setSelectionColor (%1)").arg(col.name()),
  4501 		QString("Set color of selection box to %1").arg(col.name())
  4502 	);
  4503 
  4504 	mapEditor->setSelectionColor (col);
  4505 }
  4506 
  4507 /*
  4508 void VymModel::changeSelection (const QItemSelection &newsel,const QItemSelection &oldsel)
  4509 {
  4510 	cout << "VymModel::changeSelection (";
  4511 	if (!newsel.indexes().isEmpty() )
  4512 		cout << getItem(newsel.indexes().first() )->getHeading().toStdString();
  4513 	cout << ",";
  4514 	if (!oldsel.indexes().isEmpty() )
  4515 		cout << getItem(oldsel.indexes().first() )->getHeading().toStdString();
  4516 	cout << ")\n";
  4517 }
  4518 */
  4519 
  4520 void VymModel::updateSelection (const QItemSelection &newsel,const QItemSelection &oldsel)	//FIXME-4 connected but not used so far
  4521 {
  4522 }
  4523 
  4524 void VymModel::emitSelectionChanged(const QItemSelection &newsel)
  4525 {
  4526 	emit (selectionChanged(newsel,newsel));	// needed e.g. to update geometry in editor
  4527 	emitShowSelection();
  4528 	sendSelection();
  4529 }
  4530 
  4531 void VymModel::emitSelectionChanged()
  4532 {
  4533 	QItemSelection newsel=selModel->selection();
  4534 	emitSelectionChanged (newsel);
  4535 }
  4536 
  4537 void VymModel::setSelectionColor(QColor col)
  4538 {
  4539 	if ( !col.isValid() ) return;
  4540 	saveState (
  4541 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4542 		QString("setSelectionColor (%1)").arg(col.name()),
  4543 		QString("Set color of selection box to %1").arg(col.name())
  4544 	);
  4545 	setSelectionColorInt (col);
  4546 }
  4547 
  4548 QColor VymModel::getSelectionColor()
  4549 {
  4550 	return mapEditor->getSelectionColor();
  4551 }
  4552 
  4553 void VymModel::setHideTmpMode (TreeItem::HideTmpMode mode)
  4554 {
  4555 	hidemode=mode;
  4556 	for (int i=0;i<rootItem->childCount();i++)
  4557 		rootItem->child(i)->setHideTmp (mode);	
  4558 	reposition();
  4559 	// FIXME-3 needed? scene()->update();
  4560 }
  4561 
  4562 
  4563 QRectF VymModel::getTotalBBox()	//FIXME-2
  4564 {
  4565 	QRectF r;
  4566 /*
  4567 	for (int i=0;i<rootItem->branchCount(); i++)
  4568 		r=addBBox (rootItem->getBranchNum(i)->getTotalBBox(), r);
  4569 */ 
  4570 	return r;	
  4571 }
  4572 
  4573 //////////////////////////////////////////////
  4574 // Selection related
  4575 //////////////////////////////////////////////
  4576 
  4577 void VymModel::setSelectionModel (QItemSelectionModel *sm)
  4578 {
  4579 	selModel=sm;
  4580 }
  4581 
  4582 QItemSelectionModel* VymModel::getSelectionModel()
  4583 {
  4584 	return selModel;
  4585 }
  4586 
  4587 void VymModel::setSelectionBlocked (bool b)
  4588 {
  4589 	selectionBlocked=b;
  4590 }
  4591 
  4592 bool VymModel::isSelectionBlocked()
  4593 {
  4594 	return selectionBlocked;
  4595 }
  4596 
  4597 bool VymModel::select ()
  4598 {
  4599 	return select (selModel->selectedIndexes().first());	// TODO no multiselections yet
  4600 }
  4601 
  4602 bool VymModel::select (const QString &s)
  4603 {
  4604 	TreeItem *ti=findBySelectString(s);
  4605 	if (ti)
  4606 	{
  4607 		unselect();
  4608 		select (ti);
  4609 		return true;
  4610 	} 
  4611 	return false;
  4612 }
  4613 
  4614 bool VymModel::select (LinkableMapObj *lmo)
  4615 {
  4616 	QItemSelection oldsel=selModel->selection();
  4617 
  4618 	if (lmo)
  4619 		return select (lmo->getTreeItem() );
  4620 	else	
  4621 		return false;
  4622 }
  4623 
  4624 bool VymModel::select (TreeItem *ti)
  4625 {
  4626 	if (ti) return select (index(ti));
  4627 	return false;
  4628 }
  4629 
  4630 bool VymModel::select (const QModelIndex &index)
  4631 {
  4632 	if (index.isValid() )
  4633 	{
  4634 		selModel->select (index,QItemSelectionModel::ClearAndSelect  );
  4635 		getSelectedItem()->setLastSelectedBranch();
  4636 		return true;
  4637 	}
  4638 	return false;
  4639 }
  4640 
  4641 void VymModel::unselect()
  4642 {
  4643 	lastSelectString=getSelectString();
  4644 	selModel->clearSelection();
  4645 }	
  4646 
  4647 void VymModel::reselect()
  4648 {
  4649 	select (lastSelectString);
  4650 }	
  4651 
  4652 void VymModel::emitShowSelection()	
  4653 {
  4654 	if (!blockReposition)
  4655 		emit (showSelection() );
  4656 }
  4657 
  4658 void VymModel::emitNoteHasChanged (TreeItem *ti)
  4659 {
  4660 	QModelIndex ix=index(ti);
  4661 	emit (noteHasChanged (ix) );
  4662 }
  4663 
  4664 void VymModel::emitDataHasChanged (TreeItem *ti)
  4665 {
  4666 	QModelIndex ix=index(ti);
  4667 	emit (dataChanged (ix,ix) );
  4668 }
  4669 
  4670 
  4671 //void VymModel::selectInt (LinkableMapObj *lmo)	// FIXME-3 still needed?
  4672 /*
  4673 {
  4674 	if (selection.select(lmo))
  4675 	{
  4676 		//emitSelectionChanged();
  4677 	}
  4678 }
  4679 
  4680 void VymModel::selectInt (TreeItem *ti)	
  4681 {
  4682 	if (selection.select(lmo))
  4683 	{
  4684 		//emitSelectionChanged();
  4685 	}
  4686 }
  4687 */
  4688 
  4689 void VymModel::selectNextBranchInt()
  4690 {
  4691 	BranchItem *bi=getSelectedBranchItem();
  4692 	if (bi)
  4693 	{
  4694 		TreeItem *pi=bi->parent();
  4695 		if (bi!=rootItem)
  4696 		{
  4697 			int i=bi->num();
  4698 			if (i<pi->branchCount() )
  4699 			{
  4700 				// select previous branch with same parent
  4701 				i++;
  4702 				select (pi->getBranchNum(i));
  4703 				return;
  4704 			}
  4705 		}
  4706 		
  4707 	}
  4708 }
  4709 
  4710 void VymModel::selectPrevBranchInt()
  4711 {
  4712 
  4713 	BranchItem *bi=getSelectedBranchItem();
  4714 	if (bi)
  4715 	{
  4716 		BranchItem *pi=(BranchItem*)bi->parent();
  4717 		if (bi!=rootItem)
  4718 		{
  4719 			int i=bi->num();
  4720 			if (i>0)
  4721 			{
  4722 				// select previous branch with same parent
  4723 				bi=pi->getBranchNum(i-1);
  4724 				select (bi);
  4725 				return;
  4726 			}
  4727 			bi=pi;
  4728 			while (bi->branchCount() >0)
  4729 				bi=bi->getLastBranch();
  4730 			select (bi);	
  4731 
  4732 			// Try to select last branch in parent pi2 previous to own parent pi
  4733 			/*
  4734 			TreeItem *pi2=pi->parent();
  4735 			if (pi2)
  4736 			{
  4737 				int j=pi->num();
  4738 				if (pi2->)
  4739 			}
  4740 			*/
  4741 		}
  4742 	}
  4743 }
  4744 
  4745 void VymModel::selectAboveBranchInt()
  4746 {
  4747 	BranchItem *bi=getSelectedBranchItem();
  4748 	if (bi)
  4749 	{
  4750 		BranchItem *newbi=NULL;
  4751 		BranchItem *pi=(BranchItem*)bi->parent();
  4752 		int i=bi->num();
  4753 		if (i>0)
  4754 		{
  4755 			// goto previous branch with same parent
  4756 			newbi=pi->getBranchNum(i-1);
  4757 			while (newbi->branchCount() >0 )
  4758 				newbi=newbi->getLastBranch();
  4759 		}
  4760 		else
  4761 			newbi=pi;
  4762 		if (newbi==rootItem) 
  4763  			// already at top branch (resp. mapcenter)
  4764 			return;
  4765 		select (newbi);
  4766 	}
  4767 }
  4768 
  4769 void VymModel::selectBelowBranchInt()
  4770 {
  4771 	BranchItem *bi=getSelectedBranchItem();
  4772 	if (bi)
  4773 	{
  4774 		BranchItem *newbi=NULL;
  4775 
  4776 		if (bi->branchCount() >0)
  4777 			newbi=bi->getFirstBranch();
  4778 		else
  4779 		{
  4780 			BranchItem *pi;
  4781 			int i;
  4782 			while (!newbi)
  4783 			{
  4784 				pi=(BranchItem*)bi->parent();
  4785 				i=bi->num();
  4786 				if (pi->branchCount()-1 > i)
  4787 				{
  4788 					newbi=(BranchItem*)pi->getBranchNum(i+1);
  4789 					//done...
  4790 					break;
  4791 				}	
  4792 				else
  4793 					// look for siblings of myself 
  4794 					// or parent, or parent of parent...
  4795 					bi=pi;
  4796 				if (bi==rootItem)
  4797 					// already at end
  4798 					return;
  4799 			}	
  4800 		}
  4801 		select (newbi);
  4802 	}
  4803 }
  4804 
  4805 void VymModel::selectUpperBranch()
  4806 {
  4807 	BranchItem *bi=getSelectedBranchItem();
  4808 	if (bi && bi->isBranchLikeType())
  4809 		selectAboveBranchInt();
  4810 }
  4811 
  4812 void VymModel::selectLowerBranch()
  4813 {
  4814 	BranchItem *bi=getSelectedBranchItem();
  4815 	if (bi && bi->isBranchLikeType())
  4816 		selectBelowBranchInt();
  4817 }
  4818 
  4819 
  4820 void VymModel::selectLeftBranch()
  4821 {
  4822 	QItemSelection oldsel=selModel->selection();
  4823 
  4824 	BranchItem* par;
  4825 	BranchItem *selbi=getSelectedBranchItem();
  4826 	TreeItem::Type type=selbi->getType();
  4827 	if (selbi)
  4828 	{
  4829 		if (type == TreeItem::MapCenter)
  4830 		{
  4831 			QModelIndex ix=index(selbi);
  4832 			selModel->select (index (rowCount(ix)-1,0,ix),QItemSelectionModel::ClearAndSelect  );
  4833 		} else
  4834 		{
  4835 			par=(BranchItem*)selbi->parent();
  4836 			if (selbi->getBranchObj()->getOrientation()==LinkableMapObj::RightOfCenter)	//FIXME-3 check getBO...
  4837 			{
  4838 				// right of center
  4839 				if (type == TreeItem::Branch ||
  4840 					type == TreeItem::Image)
  4841 				{
  4842 					QModelIndex ix=index (selbi->parent());
  4843 					selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4844 				}
  4845 			} else
  4846 			{
  4847 				// left of center
  4848 				if (type == TreeItem::Branch )
  4849 				{
  4850 					selectLastSelectedBranch();
  4851 					return;
  4852 				}
  4853 			}
  4854 		}	
  4855 	}
  4856 }
  4857 
  4858 void VymModel::selectRightBranch()
  4859 {
  4860 	QItemSelection oldsel=selModel->selection();
  4861 
  4862 	BranchItem* par;
  4863 	BranchItem *selbi=getSelectedBranchItem();
  4864 	TreeItem::Type type=selbi->getType();
  4865 	if (selbi)
  4866 	{
  4867 		if (type==TreeItem::MapCenter)
  4868 		{
  4869 			QModelIndex ix=index(selbi);
  4870 			selModel->select (index (0,0,ix),QItemSelectionModel::ClearAndSelect  );
  4871 		} else
  4872 		{
  4873 			par=(BranchItem*)selbi->parent();
  4874 			if (selbi->getBranchObj()->getOrientation()==LinkableMapObj::RightOfCenter)	//FIXME-3 check getBO
  4875 			{
  4876 				// right of center
  4877 				if ( type== TreeItem::Branch )
  4878 				{
  4879 					selectLastSelectedBranch();
  4880 					return;
  4881 				}
  4882 			} else
  4883 			{
  4884 				// left of center
  4885 				if (type == TreeItem::Branch ||
  4886 					type == TreeItem::Image)
  4887 				{
  4888 					QModelIndex ix=index(selbi->parent());
  4889 					selModel->select (ix,QItemSelectionModel::ClearAndSelect  );
  4890 				}
  4891 			}
  4892 		}	
  4893 	}
  4894 }
  4895 
  4896 void VymModel::selectFirstBranch()
  4897 {
  4898 	TreeItem *ti=getSelectedBranchItem();
  4899 	if (ti)
  4900 	{
  4901 		TreeItem *par=ti->parent();
  4902 		if (!par) return;
  4903 		TreeItem *ti2=par->getFirstBranch();
  4904 		if (ti2) {
  4905 			select(ti2);
  4906 			emitSelectionChanged();
  4907 		}
  4908 	}		
  4909 }
  4910 
  4911 void VymModel::selectLastBranch()
  4912 {
  4913 	TreeItem *ti=getSelectedBranchItem();
  4914 	if (ti)
  4915 	{
  4916 		TreeItem *par=ti->parent();
  4917 		if (!par) return;
  4918 		TreeItem *ti2=par->getLastBranch();
  4919 		if (ti2) {
  4920 			select(ti2);
  4921 			emitSelectionChanged();
  4922 		}
  4923 	}		
  4924 }
  4925 
  4926 void VymModel::selectLastSelectedBranch()
  4927 {
  4928 	TreeItem *ti=getSelectedBranchItem();
  4929 	if (ti)
  4930 	{
  4931 		ti=ti->getLastSelectedBranch();
  4932 		if (ti) select (ti);
  4933 	}		
  4934 }
  4935 
  4936 void VymModel::selectParent()
  4937 {
  4938 	TreeItem *ti=getSelectedItem();
  4939 	TreeItem *par;
  4940 	if (ti)
  4941 	{
  4942 		par=ti->parent();
  4943 		if (!par) return;
  4944 		select(par);
  4945 		emitSelectionChanged();
  4946 	}		
  4947 }
  4948 
  4949 TreeItem::Type VymModel::selectionType()
  4950 {
  4951 	QModelIndexList list=selModel->selectedIndexes();
  4952 	if (list.isEmpty()) return TreeItem::Undefined;	
  4953 	TreeItem *ti = getItem (list.first() );
  4954 	return ti->getType();
  4955 
  4956 }
  4957 
  4958 LinkableMapObj* VymModel::getSelectedLMO()
  4959 {
  4960 	QModelIndexList list=selModel->selectedIndexes();
  4961 	if (!list.isEmpty() )
  4962 	{
  4963 		TreeItem *ti = getItem (list.first() );
  4964 		TreeItem::Type type=ti->getType();
  4965 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter || type==TreeItem::Image)
  4966 			return ((MapItem*)ti)->getLMO();
  4967 	}
  4968 	return NULL;
  4969 }
  4970 
  4971 BranchObj* VymModel::getSelectedBranchObj()	// FIXME-3 this should not be needed in the end!!!
  4972 {
  4973 	TreeItem *ti = getSelectedBranchItem();
  4974 	if (ti)
  4975 		return (BranchObj*)(  ((MapItem*)ti)->getLMO());
  4976 	else	
  4977 		return NULL;
  4978 }
  4979 
  4980 BranchItem* VymModel::getSelectedBranchItem()
  4981 {
  4982 	QModelIndexList list=selModel->selectedIndexes();
  4983 	if (!list.isEmpty() )
  4984 	{
  4985 		TreeItem *ti = getItem (list.first() );
  4986 		TreeItem::Type type=ti->getType();
  4987 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter)
  4988 			return (BranchItem*)ti;
  4989 	}
  4990 	return NULL;
  4991 }
  4992 
  4993 TreeItem* VymModel::getSelectedItem()	
  4994 {
  4995 	QModelIndexList list=selModel->selectedIndexes();
  4996 	if (!list.isEmpty() )
  4997 		return getItem (list.first() );
  4998 	else	
  4999 		return NULL;
  5000 }
  5001 
  5002 QModelIndex VymModel::getSelectedIndex()
  5003 {
  5004 	QModelIndexList list=selModel->selectedIndexes();
  5005 	if (list.isEmpty() )
  5006 		return QModelIndex();
  5007 	else
  5008 		return list.first();
  5009 }
  5010 
  5011 ImageItem* VymModel::getSelectedImageItem()
  5012 {
  5013 	QModelIndexList list=selModel->selectedIndexes();
  5014 	if (!list.isEmpty())
  5015 	{
  5016 		TreeItem *ti=getItem (list.first());
  5017 		if (ti && ti->getType()==TreeItem::Image)
  5018 			return (ImageItem*)ti;
  5019 	}
  5020 	return NULL;
  5021 }
  5022 
  5023 QString VymModel::getSelectString ()
  5024 {
  5025 	return getSelectString (getSelectedItem());
  5026 }
  5027 
  5028 QString VymModel::getSelectString (LinkableMapObj *lmo)	// FIXME-2 VM needs to use TreeModel. Port all calls to this funtion to the one using TreeItem below...
  5029 {
  5030 	if (!lmo) return QString();
  5031 	return getSelectString (lmo->getTreeItem() );
  5032 }
  5033 
  5034 QString VymModel::getSelectString (TreeItem *ti) //FIXME-1 does not return "mc:"
  5035 {
  5036 	QString s;
  5037 	if (!ti) return s;
  5038 	switch (ti->getType())
  5039 	{
  5040 		case TreeItem::MapCenter: s="mc:"; break;
  5041 		case TreeItem::Branch: s="bo:";break;
  5042 		case TreeItem::Image: s="fi:";break;
  5043 		default:break;
  5044 	}
  5045 	s=  s + QString("%1").arg(ti->num());
  5046 	if (ti->depth() >0)
  5047 		// call myself recursively
  5048 		s= getSelectString(ti->parent()) +","+s;
  5049 			
  5050 	return s;
  5051 }
  5052