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