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