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