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