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