vymmodel.cpp
author insilmaril
Thu, 17 Sep 2009 09:41:09 +0000
changeset 795 6b0a5f4923d3
parent 794 d922fb6ea482
child 796 cf634bbf9e04
permissions -rw-r--r--
Fixed sort children and addMapReplaceInt
     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)	
   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 
  1081 	blockSaveState=blockSaveStateOrg;
  1082 
  1083 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1084 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1085 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1086 	undoSet.writeSettings(histPath);
  1087 
  1088 	mainWindow->updateHistory (undoSet);
  1089 	updateActions();
  1090 
  1091 	/* TODO remove testing
  1092 	cout << "ME::redo() end\n";
  1093 	cout << "    undosAvail="<<undosAvail<<endl;
  1094 	cout << "    redosAvail="<<redosAvail<<endl;
  1095 	cout << "       curStep="<<curStep<<endl;
  1096 	cout << "    ---------------------------"<<endl<<endl;
  1097 	*/
  1098 
  1099 
  1100 }
  1101 
  1102 bool VymModel::isRedoAvailable()
  1103 {
  1104 	if (undoSet.readNumEntry("/history/redosAvail",0)>0)
  1105 		return true;
  1106 	else	
  1107 		return false;
  1108 }
  1109 
  1110 void VymModel::undo()
  1111 {
  1112 	// Can we undo at all?
  1113 	if (undosAvail<1) return;
  1114 
  1115 	mainWindow->statusMessage (tr("Autosave disabled during undo."));
  1116 
  1117 	bool blockSaveStateOrg=blockSaveState;
  1118 	blockSaveState=true;
  1119 	
  1120 	QString undoCommand=  undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
  1121 	QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
  1122 	QString redoCommand=  undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
  1123 	QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
  1124 	QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
  1125 	QString version=undoSet.readEntry ("/history/version");
  1126 
  1127 	/* TODO Maybe check for version, if we save the history
  1128 	if (!checkVersion(version))
  1129 		QMessageBox::warning(0,tr("Warning"),
  1130 			tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
  1131 	*/
  1132 
  1133 	// Find out current undo directory
  1134 	QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
  1135 
  1136 	// select  object before undo
  1137 	if (!select (undoSelection))
  1138 	{
  1139 		qWarning ("VymModel::undo()  Could not select object for undo");
  1140 		return;
  1141 	}
  1142 
  1143 	if (debug)
  1144 	{
  1145 		cout << "VymModel::undo() begin\n";
  1146 		cout << "    undosAvail="<<undosAvail<<endl;
  1147 		cout << "    redosAvail="<<redosAvail<<endl;
  1148 		cout << "       curStep="<<curStep<<endl;
  1149 		cout << "    ---------------------------"<<endl;
  1150 		cout << "    comment="<<comment.toStdString()<<endl;
  1151 		cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  1152 		cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  1153 		cout << "    redoCom="<<redoCommand.toStdString()<<endl;
  1154 		cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  1155 		cout << "    ---------------------------"<<endl<<endl;
  1156 	}	
  1157 	parseAtom (undoCommand);
  1158 
  1159 	undosAvail--;
  1160 	curStep--; 
  1161 	if (curStep<1) curStep=stepsTotal;
  1162 
  1163 	redosAvail++;
  1164 
  1165 	blockSaveState=blockSaveStateOrg;
  1166 /* testing only
  1167 	cout << "VymModel::undo() end\n";
  1168 	cout << "    undosAvail="<<undosAvail<<endl;
  1169 	cout << "    redosAvail="<<redosAvail<<endl;
  1170 	cout << "       curStep="<<curStep<<endl;
  1171 	cout << "    ---------------------------"<<endl<<endl;
  1172 */
  1173 
  1174 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1175 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1176 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1177 	undoSet.writeSettings(histPath);
  1178 
  1179 	mainWindow->updateHistory (undoSet);
  1180 	updateActions();
  1181 	//emitSelectionChanged();
  1182 }
  1183 
  1184 bool VymModel::isUndoAvailable()
  1185 {
  1186 	if (undoSet.readNumEntry("/history/undosAvail",0)>0)
  1187 		return true;
  1188 	else	
  1189 		return false;
  1190 }
  1191 
  1192 void VymModel::gotoHistoryStep (int i)
  1193 {
  1194 	// Restore variables
  1195 	int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
  1196 	int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
  1197 
  1198 	if (i<0) i=undosAvail+redosAvail;
  1199 
  1200 	// Clicking above current step makes us undo things
  1201 	if (i<undosAvail) 
  1202 	{	
  1203 		for (int j=0; j<undosAvail-i; j++) undo();
  1204 		return;
  1205 	}	
  1206 	// Clicking below current step makes us redo things
  1207 	if (i>undosAvail) 
  1208 		for (int j=undosAvail; j<i; j++) 
  1209 		{
  1210 			if (debug) cout << "VymModel::gotoHistoryStep redo "<<j<<"/"<<undosAvail<<" i="<<i<<endl;
  1211 			redo();
  1212 		}
  1213 
  1214 	// And ignore clicking the current row ;-)	
  1215 }
  1216 
  1217 
  1218 QString VymModel::getHistoryPath()
  1219 {
  1220 	QString histName(QString("history-%1").arg(curStep));
  1221 	return (tmpMapDir+"/"+histName);
  1222 }
  1223 
  1224 void VymModel::saveState(const SaveMode &savemode, const QString &undoSelection, const QString &undoCom, const QString &redoSelection, const QString &redoCom, const QString &comment, TreeItem *saveSel)
  1225 {
  1226 	sendData(redoCom);	//FIXME-3 testing
  1227 
  1228 	// Main saveState
  1229 
  1230 
  1231 	if (blockSaveState) return;
  1232 
  1233 	if (debug) cout << "VM::saveState() for  "<<qPrintable (mapName)<<endl;
  1234 	
  1235 	// Find out current undo directory
  1236 	if (undosAvail<stepsTotal) undosAvail++;
  1237 	curStep++;
  1238 	if (curStep>stepsTotal) curStep=1;
  1239 	
  1240 	QString backupXML="";
  1241 	QString histDir=getHistoryPath();
  1242 	QString bakMapPath=histDir+"/map.xml";
  1243 
  1244 	// Create histDir if not available
  1245 	QDir d(histDir);
  1246 	if (!d.exists()) 
  1247 		makeSubDirs (histDir);
  1248 
  1249 	// Save depending on how much needs to be saved	
  1250 	if (saveSel)
  1251 		backupXML=saveToDir (histDir,mapName+"-",false, QPointF (),saveSel);
  1252 		
  1253 	QString undoCommand="";
  1254 	if (savemode==UndoCommand)
  1255 	{
  1256 		undoCommand=undoCom;
  1257 	}	
  1258 	else if (savemode==PartOfMap )
  1259 	{
  1260 		undoCommand=undoCom;
  1261 		undoCommand.replace ("PATH",bakMapPath);
  1262 	}
  1263 
  1264 
  1265 	if (!backupXML.isEmpty())
  1266 		// Write XML Data to disk
  1267 		saveStringToDisk (bakMapPath,backupXML);
  1268 
  1269 	// We would have to save all actions in a tree, to keep track of 
  1270 	// possible redos after a action. Possible, but we are too lazy: forget about redos.
  1271 	redosAvail=0;
  1272 
  1273 	// Write the current state to disk
  1274 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1275 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1276 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1277 	undoSet.setEntry (QString("/history/step-%1/undoCommand").arg(curStep),undoCommand);
  1278 	undoSet.setEntry (QString("/history/step-%1/undoSelection").arg(curStep),undoSelection);
  1279 	undoSet.setEntry (QString("/history/step-%1/redoCommand").arg(curStep),redoCom);
  1280 	undoSet.setEntry (QString("/history/step-%1/redoSelection").arg(curStep),redoSelection);
  1281 	undoSet.setEntry (QString("/history/step-%1/comment").arg(curStep),comment);
  1282 	undoSet.setEntry (QString("/history/version"),vymVersion);
  1283 	undoSet.writeSettings(histPath);
  1284 
  1285 	if (debug)
  1286 	{
  1287 		// TODO remove after testing
  1288 		//cout << "          into="<< histPath.toStdString()<<endl;
  1289 		cout << "    stepsTotal="<<stepsTotal<<
  1290 		", undosAvail="<<undosAvail<<
  1291 		", redosAvail="<<redosAvail<<
  1292 		", curStep="<<curStep<<endl;
  1293 		cout << "    ---------------------------"<<endl;
  1294 		cout << "    comment="<<comment.toStdString()<<endl;
  1295 		cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  1296 		cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  1297 		cout << "    redoCom="<<redoCom.toStdString()<<endl;
  1298 		cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  1299 		if (saveSel) cout << "    saveSel="<<qPrintable (getSelectString(saveSel))<<endl;
  1300 		cout << "    ---------------------------"<<endl;
  1301 	}
  1302 
  1303 	mainWindow->updateHistory (undoSet);
  1304 	setChanged();
  1305 	updateActions();
  1306 }
  1307 
  1308 
  1309 void VymModel::saveStateChangingPart(TreeItem *undoSel, TreeItem* redoSel, const QString &rc, const QString &comment)
  1310 {
  1311 	// save the selected part of the map, Undo will replace part of map 
  1312 	QString undoSelection="";
  1313 	if (undoSel)
  1314 		undoSelection=getSelectString(undoSel);
  1315 	else
  1316 		qWarning ("VymModel::saveStateChangingPart  no undoSel given!");
  1317 	QString redoSelection="";
  1318 	if (redoSel)
  1319 		redoSelection=getSelectString(undoSel);
  1320 	else
  1321 		qWarning ("VymModel::saveStateChangingPart  no redoSel given!");
  1322 		
  1323 
  1324 	saveState (PartOfMap,
  1325 		undoSelection, "addMapReplace (\"PATH\")",
  1326 		redoSelection, rc, 
  1327 		comment, 
  1328 		undoSel);
  1329 }
  1330 
  1331 void VymModel::saveStateRemovingPart(TreeItem* redoSel, const QString &comment)
  1332 {
  1333 	if (!redoSel)
  1334 	{
  1335 		qWarning ("VymModel::saveStateRemovingPart  no redoSel given!");
  1336 		return;
  1337 	}
  1338 	QString undoSelection;
  1339 	QString redoSelection=getSelectString(redoSel);
  1340 	if (redoSel->getType()==TreeItem::Branch) 
  1341 	{
  1342 		undoSelection=getSelectString (redoSel->parent());
  1343 		// save the selected branch of the map, Undo will insert part of map 
  1344 		saveState (PartOfMap,
  1345 			undoSelection, QString("addMapInsert (\"PATH\",%1)").arg(redoSel->num()),
  1346 			redoSelection, "delete ()", 
  1347 			comment, 
  1348 			redoSel);
  1349 	}
  1350 	if (redoSel->getType()==TreeItem::MapCenter) 
  1351 	{
  1352 		// save the selected branch of the map, Undo will insert part of map 
  1353 		saveState (PartOfMap,
  1354 			undoSelection, QString("addMapInsert (\"PATH\")"),
  1355 			redoSelection, "delete ()", 
  1356 			comment, 
  1357 			redoSel);
  1358 	}
  1359 }
  1360 
  1361 
  1362 void VymModel::saveState(TreeItem *undoSel, const QString &uc, TreeItem *redoSel, const QString &rc, const QString &comment) 
  1363 {
  1364 	// "Normal" savestate: save commands, selections and comment
  1365 	// so just save commands for undo and redo
  1366 	// and use current selection
  1367 
  1368 	QString redoSelection="";
  1369 	if (redoSel) redoSelection=getSelectString(redoSel);
  1370 	QString undoSelection="";
  1371 	if (undoSel) undoSelection=getSelectString(undoSel);
  1372 
  1373 	saveState (UndoCommand,
  1374 		undoSelection, uc,
  1375 		redoSelection, rc, 
  1376 		comment, 
  1377 		NULL);
  1378 }
  1379 
  1380 void VymModel::saveState(const QString &undoSel, const QString &uc, const QString &redoSel, const QString &rc, const QString &comment) 
  1381 {
  1382 	// "Normal" savestate: save commands, selections and comment
  1383 	// so just save commands for undo and redo
  1384 	// and use current selection
  1385 	saveState (UndoCommand,
  1386 		undoSel, uc,
  1387 		redoSel, rc, 
  1388 		comment, 
  1389 		NULL);
  1390 }
  1391 
  1392 void VymModel::saveState(const QString &uc, const QString &rc, const QString &comment) 
  1393 {
  1394 	// "Normal" savestate applied to model (no selection needed): 
  1395 	// save commands  and comment
  1396 	saveState (UndoCommand,
  1397 		NULL, uc,
  1398 		NULL, rc, 
  1399 		comment, 
  1400 		NULL);
  1401 }
  1402 
  1403 
  1404 QGraphicsScene* VymModel::getScene ()
  1405 {
  1406 	return mapScene;
  1407 }
  1408 
  1409 TreeItem* VymModel::findBySelectString(QString s)
  1410 {
  1411 	if (s.isEmpty() ) return NULL;
  1412 
  1413 	// Old maps don't have multiple mapcenters and don't save full path
  1414 	if (s.left(2) !="mc")
  1415 		s="mc:0,"+s;
  1416 
  1417 	QStringList parts=s.split (",");
  1418 	QString typ;
  1419 	int n;
  1420 	TreeItem *ti=rootItem;
  1421 
  1422 	while (!parts.isEmpty() )
  1423 	{
  1424 		typ=parts.first().left(2);
  1425 		n=parts.first().right(parts.first().length() - 3).toInt();
  1426 		parts.removeFirst();
  1427 		if (typ=="mc" || typ=="bo")
  1428 			ti=ti->getBranchNum (n);
  1429 		else if (typ=="fi")
  1430 			ti=ti->getImageNum (n);
  1431 		else if (typ=="ai")
  1432 			ti=ti->getAttributeNum (n);
  1433 		else if (typ=="xl")
  1434 			ti=ti->getXLinkNum (n);
  1435 		if(!ti) return NULL;		
  1436 	}
  1437 	return  ti;
  1438 }
  1439 
  1440 TreeItem* VymModel::findID (const QString &s)	//FIXME-4 Search also other types...
  1441 {
  1442 	BranchItem *cur=NULL;
  1443 	BranchItem *prev=NULL;
  1444 	next(cur,prev);
  1445 	while (cur) 
  1446 	{
  1447 		if (s==cur->getID() ) return cur;
  1448 		next(cur,prev);
  1449 	}
  1450 	return NULL;
  1451 }
  1452 
  1453 //////////////////////////////////////////////
  1454 // Interface 
  1455 //////////////////////////////////////////////
  1456 void VymModel::setVersion (const QString &s)
  1457 {
  1458 	version=s;
  1459 }
  1460 
  1461 void VymModel::setAuthor (const QString &s)
  1462 {
  1463 	saveState (
  1464 		QString ("setMapAuthor (\"%1\")").arg(author),
  1465 		QString ("setMapAuthor (\"%1\")").arg(s),
  1466 		QString ("Set author of map to \"%1\"").arg(s)
  1467 	);
  1468 	author=s;
  1469 }
  1470 
  1471 QString VymModel::getAuthor()
  1472 {
  1473 	return author;
  1474 }
  1475 
  1476 void VymModel::setComment (const QString &s)
  1477 {
  1478 	saveState (
  1479 		QString ("setMapComment (\"%1\")").arg(comment),
  1480 		QString ("setMapComment (\"%1\")").arg(s),
  1481 		QString ("Set comment of map")
  1482 	);
  1483 	comment=s;
  1484 }
  1485 
  1486 QString VymModel::getComment ()
  1487 {
  1488 	return comment;
  1489 }
  1490 
  1491 QString VymModel::getDate ()
  1492 {
  1493 	return QDate::currentDate().toString ("yyyy-MM-dd");
  1494 }
  1495 
  1496 int VymModel::branchCount()	// FIXME-4 Optimize this: use internal counter instead of going through whole map each time...
  1497 {
  1498 	int c=0;
  1499 	BranchItem *cur=NULL;
  1500 	BranchItem *prev=NULL;
  1501 	next(cur,prev);
  1502 	while (cur) 
  1503 	{
  1504 		c++;
  1505 		next(cur,prev);
  1506 	}
  1507 	return c;
  1508 }
  1509 
  1510 void VymModel::setHeading(const QString &s)
  1511 {
  1512 	BranchItem *selbi=getSelectedBranch();
  1513 	if (selbi)
  1514 	{
  1515 		saveState(
  1516 			selbi,
  1517 			"setHeading (\""+selbi->getHeading()+"\")", 
  1518 			selbi,
  1519 			"setHeading (\""+s+"\")", 
  1520 			QString("Set heading of %1 to \"%2\"").arg(getObjectName(selbi)).arg(s) );
  1521 		selbi->setHeading(s );
  1522 		emitDataHasChanged ( selbi);	//FIXME-3 maybe emit signal from TreeItem? 
  1523 		reposition();
  1524 		emitSelectionChanged();
  1525 	}
  1526 }
  1527 
  1528 QString VymModel::getHeading()
  1529 {
  1530 	TreeItem *selti=getSelectedItem();
  1531 	if (selti)
  1532 		return selti->getHeading();
  1533 	else	
  1534 		return QString();
  1535 }
  1536 
  1537 BranchItem* VymModel::findText (QString s, bool cs)   
  1538 {
  1539 	QTextDocument::FindFlags flags=0;
  1540 	if (cs) flags=QTextDocument::FindCaseSensitively;
  1541 
  1542 	if (!findCurrent) 
  1543 	{	// Nothing found or new find process
  1544 		if (EOFind)
  1545 			// nothing found, start again
  1546 			EOFind=false;
  1547 		findCurrent=NULL;	
  1548 		findPrevious=NULL;	
  1549 		next (findCurrent,findPrevious);
  1550 	}	
  1551 	bool searching=true;
  1552 	bool foundNote=false;
  1553 	while (searching && !EOFind)
  1554 	{
  1555 		if (findCurrent)
  1556 		{
  1557 			// Searching in Note
  1558 			if (findCurrent->getNote().contains(s,cs))
  1559 			{
  1560 				select (findCurrent);
  1561 				/*
  1562 				if (getSelectedBranch()!=itFind) 
  1563 				{
  1564 					select(itFind);
  1565 					emitShowSelection();
  1566 				}
  1567 				*/
  1568 				if (textEditor->findText(s,flags)) 
  1569 				{
  1570 					searching=false;
  1571 					foundNote=true;
  1572 				}	
  1573 			}
  1574 			// Searching in Heading
  1575 			if (searching && findCurrent->getHeading().contains (s,cs) ) 
  1576 			{
  1577 				select(findCurrent);
  1578 				searching=false;
  1579 			}
  1580 		}	
  1581 		if (!foundNote)
  1582 		{
  1583 			if (!next(findCurrent,findPrevious) )
  1584 				EOFind=true;
  1585 		}
  1586 	//cout <<"still searching...  "<<qPrintable( itFind->getHeading())<<endl;
  1587 	}	
  1588 	if (!searching)
  1589 		return getSelectedBranch();
  1590 	else
  1591 		return NULL;
  1592 }
  1593 
  1594 void VymModel::findReset()
  1595 {	// Necessary if text to find changes during a find process
  1596 	findCurrent=NULL;
  1597 	findPrevious=NULL;
  1598 	EOFind=false;
  1599 }
  1600 
  1601 void VymModel::setScene (QGraphicsScene *s)
  1602 {
  1603 	mapScene=s;	
  1604 }
  1605 
  1606 void VymModel::setURL(const QString &url) 
  1607 {
  1608 	TreeItem *selti=getSelectedItem();
  1609 	if (selti)
  1610 	{
  1611 		QString oldurl=selti->getURL();
  1612 		selti->setURL (url);
  1613 		saveState (
  1614 			selti,
  1615 			QString ("setURL (\"%1\")").arg(oldurl),
  1616 			selti,
  1617 			QString ("setURL (\"%1\")").arg(url),
  1618 			QString ("set URL of %1 to %2").arg(getObjectName(selti)).arg(url)
  1619 		);
  1620 		reposition();
  1621 		emitDataHasChanged (selti);
  1622 		emitShowSelection();
  1623 	}
  1624 }	
  1625 
  1626 QString VymModel::getURL()	
  1627 {
  1628 	TreeItem *selti=getSelectedItem();
  1629 	if (selti)
  1630 		return selti->getURL();
  1631 	else	
  1632 		return QString();
  1633 }
  1634 
  1635 QStringList VymModel::getURLs()	
  1636 {
  1637 	QStringList urls;
  1638 	BranchItem *selbi=getSelectedBranch();
  1639 	BranchItem *cur=selbi;
  1640 	BranchItem *prev=NULL;
  1641 	while (cur) 
  1642 	{
  1643 		if (!cur->getURL().isEmpty()) urls.append( cur->getURL());
  1644 		cur=next (cur,prev,selbi);
  1645 	}	
  1646 	return urls;
  1647 }
  1648 
  1649 
  1650 void VymModel::setFrameType(const FrameObj::FrameType &t)	//FIXME-4 not saved if there is no LMO
  1651 {
  1652 	BranchItem *bi=getSelectedBranch();
  1653 	if (bi)
  1654 	{
  1655 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1656 		if (bo)
  1657 		{
  1658 			QString s=bo->getFrameTypeName();
  1659 			bo->setFrameType (t);
  1660 			saveState (bi, QString("setFrameType (\"%1\")").arg(s),
  1661 				bi, QString ("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),QString ("set type of frame to %1").arg(s));
  1662 			reposition();
  1663 			bo->updateLinkGeometry();
  1664 		}
  1665 	}
  1666 }
  1667 
  1668 void VymModel::setFrameType(const QString &s)	//FIXME-4 not saved if there is no LMO
  1669 {
  1670 	BranchItem *bi=getSelectedBranch();
  1671 	if (bi)
  1672 	{
  1673 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1674 		if (bo)
  1675 		{
  1676 			saveState (bi, QString("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),
  1677 				bi, QString ("setFrameType (\"%1\")").arg(s),QString ("set type of frame to %1").arg(s));
  1678 			bo->setFrameType (s);
  1679 			reposition();
  1680 			bo->updateLinkGeometry();
  1681 		}
  1682 	}
  1683 }
  1684 
  1685 void VymModel::setFramePenColor(const QColor &c)	//FIXME-4 not saved if there is no LMO
  1686 
  1687 {
  1688 	BranchItem *bi=getSelectedBranch();
  1689 	if (bi)
  1690 	{
  1691 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1692 		if (bo)
  1693 		{
  1694 			saveState (bi, QString("setFramePenColor (\"%1\")").arg(bo->getFramePenColor().name() ),
  1695 				bi, QString ("setFramePenColor (\"%1\")").arg(c.name() ),QString ("set pen color of frame to %1").arg(c.name() ));
  1696 			bo->setFramePenColor (c);
  1697 		}	
  1698 	}	
  1699 }
  1700 
  1701 void VymModel::setFrameBrushColor(const QColor &c)	//FIXME-4 not saved if there is no LMO
  1702 {
  1703 	BranchItem *bi=getSelectedBranch();
  1704 	if (bi)
  1705 	{
  1706 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1707 		if (bo)
  1708 		{
  1709 			saveState (bi, QString("setFrameBrushColor (\"%1\")").arg(bo->getFrameBrushColor().name() ),
  1710 				bi, QString ("setFrameBrushColor (\"%1\")").arg(c.name() ),QString ("set brush color of frame to %1").arg(c.name() ));
  1711 			bo->setFrameBrushColor (c);
  1712 		}	
  1713 	}	
  1714 }
  1715 
  1716 void VymModel::setFramePadding (const int &i) //FIXME-4 not saved if there is no LMO
  1717 {
  1718 	BranchItem *bi=getSelectedBranch();
  1719 	if (bi)
  1720 	{
  1721 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1722 		if (bo)
  1723 		{
  1724 			saveState (bi, QString("setFramePadding (\"%1\")").arg(bo->getFramePadding() ),
  1725 				bi, QString ("setFramePadding (\"%1\")").arg(i),QString ("set brush color of frame to %1").arg(i));
  1726 			bo->setFramePadding (i);
  1727 			reposition();
  1728 			bo->updateLinkGeometry();
  1729 		}	
  1730 	}	
  1731 }
  1732 
  1733 void VymModel::setFrameBorderWidth(const int &i) //FIXME-4 not saved if there is no LMO
  1734 {
  1735 	BranchItem *bi=getSelectedBranch();
  1736 	if (bi)
  1737 	{
  1738 		BranchObj *bo=(BranchObj*)(bi->getLMO());
  1739 		if (bo)
  1740 		{
  1741 			saveState (bi, QString("setFrameBorderWidth (\"%1\")").arg(bo->getFrameBorderWidth() ),
  1742 				bi, QString ("setFrameBorderWidth (\"%1\")").arg(i),QString ("set border width of frame to %1").arg(i));
  1743 			bo->setFrameBorderWidth (i);
  1744 			reposition();
  1745 			bo->updateLinkGeometry();
  1746 		}	
  1747 	}	
  1748 }
  1749 
  1750 void VymModel::setIncludeImagesVer(bool b)
  1751 {
  1752 	BranchItem *bi=getSelectedBranch();
  1753 	if (bi)
  1754 	{
  1755 		QString u= b ? "false" : "true";
  1756 		QString r=!b ? "false" : "true";
  1757 		
  1758 		saveState(
  1759 			bi,
  1760 			QString("setIncludeImagesVertically (%1)").arg(u),
  1761 			bi, 
  1762 			QString("setIncludeImagesVertically (%1)").arg(r),
  1763 			QString("Include images vertically in %1").arg(getObjectName(bi))
  1764 		);	
  1765 		bi->setIncludeImagesVer(b);
  1766 		emitDataHasChanged ( bi);	
  1767 		reposition();
  1768 	}	
  1769 }
  1770 
  1771 void VymModel::setIncludeImagesHor(bool b)	
  1772 {
  1773 	BranchItem *bi=getSelectedBranch();
  1774 	if (bi)
  1775 	{
  1776 		QString u= b ? "false" : "true";
  1777 		QString r=!b ? "false" : "true";
  1778 		
  1779 		saveState(
  1780 			bi,
  1781 			QString("setIncludeImagesHorizontally (%1)").arg(u),
  1782 			bi, 
  1783 			QString("setIncludeImagesHorizontally (%1)").arg(r),
  1784 			QString("Include images horizontally in %1").arg(getObjectName(bi))
  1785 		);	
  1786 		bi->setIncludeImagesHor(b);
  1787 		emitDataHasChanged ( bi);
  1788 		reposition();
  1789 	}	
  1790 }
  1791 
  1792 void VymModel::setHideLinkUnselected (bool b)//FIXME-2
  1793 {
  1794 	TreeItem *ti=getSelectedItem();
  1795 	if (ti && (ti->getType()==TreeItem::Image ||ti->isBranchLikeType()))
  1796 	{
  1797 		QString u= b ? "false" : "true";
  1798 		QString r=!b ? "false" : "true";
  1799 		
  1800 		saveState(
  1801 			ti,
  1802 			QString("setHideLinkUnselected (%1)").arg(u),
  1803 			ti, 
  1804 			QString("setHideLinkUnselected (%1)").arg(r),
  1805 			QString("Hide link of %1 if unselected").arg(getObjectName(ti))
  1806 		);	
  1807 		((MapItem*)ti)->setHideLinkUnselected(b);
  1808 	}
  1809 }
  1810 
  1811 void VymModel::setHideExport(bool b)
  1812 {
  1813 	TreeItem *ti=getSelectedItem();
  1814 	if (ti && 
  1815 		(ti->getType()==TreeItem::Image ||ti->isBranchLikeType()))
  1816 	{
  1817 		ti->setHideInExport (b);
  1818 		QString u= b ? "false" : "true";
  1819 		QString r=!b ? "false" : "true";
  1820 		
  1821 		saveState(
  1822 			ti,
  1823 			QString ("setHideExport (%1)").arg(u),
  1824 			ti,
  1825 			QString ("setHideExport (%1)").arg(r),
  1826 			QString ("Set HideExport flag of %1 to %2").arg(getObjectName(ti)).arg (r)
  1827 		);	
  1828 			emitDataHasChanged(ti);
  1829 			emitSelectionChanged();
  1830 		updateActions();
  1831 		reposition();
  1832 		// emitSelectionChanged();
  1833 		// FIXME-3 VM needed? scene()->update();
  1834 	}
  1835 }
  1836 
  1837 void VymModel::toggleHideExport()
  1838 {
  1839 	TreeItem *selti=getSelectedItem();
  1840 	if (selti)
  1841 		setHideExport ( !selti->hideInExport() );
  1842 }
  1843 
  1844 
  1845 void VymModel::copy()	
  1846 {
  1847 	TreeItem *selti=getSelectedItem();
  1848 	if (selti &&
  1849 		(selti->getType() == TreeItem::Branch || 
  1850 		selti->getType() == TreeItem::MapCenter  ||
  1851 		selti->getType() == TreeItem::Image ))
  1852 	{
  1853 		if (redosAvail == 0)
  1854 		{
  1855 			// Copy to history
  1856 			QString s=getSelectString(selti);
  1857 			saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",selti  );
  1858 			curClipboard=curStep;
  1859 		}
  1860 
  1861 		// Copy also to global clipboard, because we are at last step in history
  1862 		QString bakMapName(QString("history-%1").arg(curStep));
  1863 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1864 		copyDir (bakMapDir,clipboardDir );
  1865 
  1866 		clipboardEmpty=false;
  1867 		updateActions();
  1868 	}	    
  1869 }
  1870 
  1871 
  1872 void VymModel::pasteNoSave(const int &n)
  1873 {
  1874 	bool old=blockSaveState;
  1875 	blockSaveState=true;
  1876 	bool zippedOrg=zipped;
  1877 	if (redosAvail > 0 || n!=0)
  1878 	{
  1879 		// Use the "historical" buffer
  1880 		QString bakMapName(QString("history-%1").arg(n));
  1881 		QString bakMapDir(tmpMapDir +"/"+bakMapName);
  1882 		load (bakMapDir+"/"+clipboardFile,ImportAdd, VymMap);
  1883 	} else
  1884 		// Use the global buffer
  1885 		load (clipboardDir+"/"+clipboardFile,ImportAdd, VymMap);
  1886 	zipped=zippedOrg;
  1887 	blockSaveState=old;
  1888 }
  1889 
  1890 void VymModel::paste()	
  1891 {   
  1892 	BranchItem *selbi=getSelectedBranch();
  1893 	if (selbi)
  1894 	{
  1895 		saveStateChangingPart(
  1896 			selbi,
  1897 			selbi,
  1898 			QString ("paste (%1)").arg(curClipboard),
  1899 			QString("Paste to %1").arg( getObjectName(selbi))
  1900 		);
  1901 		pasteNoSave(0);
  1902 		reposition();
  1903 	}
  1904 }
  1905 
  1906 void VymModel::cut()	
  1907 {
  1908 	TreeItem *selti=getSelectedItem();
  1909 	if ( selti && (selti->isBranchLikeType() ||selti->getType()==TreeItem::Image))
  1910 	{
  1911 		copy();
  1912 		deleteSelection();
  1913 		reposition();
  1914 	}
  1915 }
  1916 
  1917 bool VymModel::moveUp(BranchItem *bi)	//FIXME-2 crashes if trying to move MCO
  1918 {
  1919 	if (bi && bi->canMoveUp()) 
  1920 		return relinkBranch (bi,(BranchItem*)bi->parent(),bi->num()-1);
  1921 	else	
  1922 		return false;
  1923 }
  1924 
  1925 void VymModel::moveUp()	
  1926 {
  1927 	BranchItem *selbi=getSelectedBranch();
  1928 	if (selbi)
  1929 	{
  1930 		QString oldsel=getSelectString();
  1931 		if (moveUp (selbi))
  1932 			saveState (
  1933 				getSelectString(),"moveDown ()",
  1934 				oldsel,"moveUp ()",
  1935 				QString("Move up %1").arg(getObjectName(selbi)));
  1936 	}
  1937 }
  1938 
  1939 bool VymModel::moveDown(BranchItem *bi)	
  1940 {
  1941 	if (bi && bi->canMoveDown())
  1942 		return relinkBranch (bi,(BranchItem*)bi->parent(),bi->num()+1);
  1943 	else
  1944 		return false;
  1945 }
  1946 
  1947 void VymModel::moveDown()	
  1948 {
  1949 	BranchItem *selbi=getSelectedBranch();
  1950 	if (selbi)
  1951 	{
  1952 		QString oldsel=getSelectString();
  1953 		if ( moveDown(selbi))
  1954 			saveState (
  1955 				getSelectString(),"moveUp ()",
  1956 				oldsel,"moveDown ()",
  1957 				QString("Move down %1").arg(getObjectName(selbi)));
  1958 	}
  1959 }
  1960 
  1961 void VymModel::detach()	
  1962 {
  1963 	BranchItem *selbi=getSelectedBranch();
  1964 	if (selbi && selbi->depth()>0)
  1965 	{
  1966 		//QString oldsel=getSelectString();
  1967 		if ( relinkBranch (selbi,rootItem,-1) )
  1968 			saveState (
  1969 				selbi,QString("relink()"), //FIXME-1 add paramters
  1970 				selbi,"detach ()",
  1971 				QString("Detach %1").arg(getObjectName(selbi))
  1972 			);
  1973 	}
  1974 }
  1975 
  1976 void VymModel::sortChildren()
  1977 {
  1978 	BranchItem* selbi=getSelectedBranch();
  1979 	if (selbi)
  1980 	{
  1981 		if(selbi->branchCount()>1)
  1982 		{
  1983 			saveStateChangingPart(
  1984 				selbi,selbi, "sortChildren ()",
  1985 				QString("Sort children of %1").arg(getObjectName(selbi)));
  1986 			selbi->sortChildren();
  1987 			reposition();
  1988 			emitShowSelection();
  1989 		}
  1990 	}
  1991 }
  1992 
  1993 BranchItem* VymModel::createMapCenter()
  1994 {
  1995 	BranchItem *newbi=addMapCenter (QPointF (0,0) );
  1996 	return newbi;
  1997 }
  1998 
  1999 BranchItem* VymModel::createBranch(BranchItem *dst)	
  2000 {
  2001 	if (dst)
  2002 		return addNewBranchInt (dst,-2);
  2003 	else
  2004 		return NULL;
  2005 }
  2006 
  2007 ImageItem* VymModel::createImage(BranchItem *dst)
  2008 {
  2009 	if (dst)
  2010 	{
  2011 		QModelIndex parix;
  2012 		int n;
  2013 
  2014 		QList<QVariant> cData;
  2015 		cData << "new" << "undef";
  2016 
  2017 		ImageItem *newii=new ImageItem(cData) ;	
  2018 		//newii->setHeading (QApplication::translate("Heading of new image in map", "new image"));
  2019 
  2020 		emit (layoutAboutToBeChanged() );
  2021 
  2022 			parix=index(dst);
  2023 			if (!parix.isValid()) cout << "VM::createII invalid index\n";
  2024 			n=dst->getRowNumAppend(newii);
  2025 			beginInsertRows (parix,n,n);
  2026 			dst->appendChild (newii);	
  2027 			endInsertRows ();
  2028 
  2029 		emit (layoutChanged() );
  2030 
  2031 		// save scroll state. If scrolled, automatically select
  2032 		// new branch in order to tmp unscroll parent...
  2033 		newii->createMapObj(mapScene);
  2034 		reposition();
  2035 		return newii;
  2036 	} 
  2037 	return NULL;
  2038 }
  2039 
  2040 XLinkItem* VymModel::createXLink(BranchItem *bi,bool createMO)
  2041 {
  2042 	if (bi)
  2043 	{
  2044 		QModelIndex parix;
  2045 		int n;
  2046 
  2047 		QList<QVariant> cData;
  2048 		cData << "new xLink"<<"undef";
  2049 
  2050 		XLinkItem *newxli=new XLinkItem(cData) ;	
  2051 		newxli->setBegin (bi);
  2052 
  2053 		emit (layoutAboutToBeChanged() );
  2054 
  2055 			parix=index(bi);
  2056 			n=bi->getRowNumAppend(newxli);
  2057 			beginInsertRows (parix,n,n);
  2058 			bi->appendChild (newxli);	
  2059 			endInsertRows ();
  2060 
  2061 		emit (layoutChanged() );
  2062 
  2063 		// save scroll state. If scrolled, automatically select
  2064 		// new branch in order to tmp unscroll parent...
  2065 		if (createMO) 
  2066 		{
  2067 			newxli->createMapObj(mapScene);
  2068 			reposition();
  2069 		}
  2070 		return newxli;
  2071 	} 
  2072 	return NULL;
  2073 }
  2074 
  2075 AttributeItem* VymModel::addAttribute()	// FIXME-2 savestate missing
  2076 {
  2077 	BranchItem *selbi=getSelectedBranch();
  2078 	if (selbi)
  2079 	{
  2080 		QList<QVariant> cData;
  2081 		cData << "new attribute" << "undef";
  2082 		AttributeItem *a=new AttributeItem (cData);
  2083 
  2084 		emit (layoutAboutToBeChanged() );
  2085 
  2086 		QModelIndex parix=index(selbi);
  2087 		int n=selbi->getRowNumAppend (a);
  2088 		beginInsertRows (parix,n,n);	
  2089 		selbi->appendChild (a);	
  2090 		endInsertRows ();
  2091 
  2092 		emit (layoutChanged() );
  2093 
  2094 		reposition();
  2095 		return a;
  2096 	}
  2097 	return NULL;
  2098 }
  2099 
  2100 BranchItem* VymModel::addMapCenter ()
  2101 {
  2102 	BranchItem *bi=addMapCenter (contextPos);
  2103 	updateActions();
  2104 	emitShowSelection();
  2105 	saveState (
  2106 		bi,
  2107 		"delete()",
  2108 		NULL,
  2109 		QString ("addMapCenter (%1,%2)").arg (contextPos.x()).arg(contextPos.y()),
  2110 		QString ("Adding MapCenter to (%1,%2)").arg (contextPos.x()).arg(contextPos.y())
  2111 	);	
  2112 	return bi;	
  2113 }
  2114 
  2115 BranchItem* VymModel::addMapCenter(QPointF absPos)	
  2116 // createMapCenter could then probably be merged with createBranch
  2117 {
  2118 
  2119 	// Create TreeItem
  2120 	QModelIndex parix=index(rootItem);
  2121 
  2122 	QList<QVariant> cData;
  2123 	cData << "VM:addMapCenter" << "undef";
  2124 	BranchItem *newbi=new BranchItem (cData,rootItem);
  2125 	newbi->setHeading (QApplication::translate("Heading of mapcenter in new map", "New map"));
  2126 	int n=rootItem->getRowNumAppend (newbi);
  2127 
  2128 	emit (layoutAboutToBeChanged() );
  2129 	beginInsertRows (parix,n,n);
  2130 
  2131 	rootItem->appendChild (newbi);
  2132 
  2133 	endInsertRows();
  2134 	emit (layoutChanged() );
  2135 
  2136 	// Create MapObj
  2137 	newbi->setPositionMode (MapItem::Absolute);
  2138 	BranchObj *bo=newbi->createMapObj(mapScene);
  2139 	if (bo) bo->move (absPos);
  2140 		
  2141 	return newbi;
  2142 }
  2143 
  2144 BranchItem* VymModel::addNewBranchInt(BranchItem *dst,int num)
  2145 {
  2146 	// Depending on pos:
  2147 	// -3		insert in children of parent  above selection 
  2148 	// -2		add branch to selection 
  2149 	// -1		insert in children of parent below selection 
  2150 	// 0..n		insert in children of parent at pos
  2151 
  2152 	// Create TreeItem
  2153 	QList<QVariant> cData;
  2154 	cData << "new" << "undef";
  2155 
  2156 	BranchItem *parbi;
  2157 	QModelIndex parix;
  2158 	int n;
  2159 	BranchItem *newbi=new BranchItem (cData);	
  2160 	newbi->setHeading (QApplication::translate("Heading of new branch in map", "new"));
  2161 
  2162 	emit (layoutAboutToBeChanged() );
  2163 
  2164 	if (num==-2)
  2165 	{
  2166 		parbi=dst;
  2167 		parix=index(parbi);
  2168 		n=parbi->getRowNumAppend (newbi);
  2169 		beginInsertRows (parix,n,n);	
  2170 		parbi->appendChild (newbi);	
  2171 		endInsertRows ();
  2172 	}else if (num==-1 || num==-3)
  2173 	{
  2174 		// insert below selection
  2175 		parbi=(BranchItem*)dst->parent();
  2176 		parix=index(parbi);  
  2177 		
  2178 		n=dst->childNumber() + (3+num)/2;	//-1 |-> 1;-3 |-> 0
  2179 		beginInsertRows (parix,n,n);	
  2180 		parbi->insertBranch(n,newbi);	
  2181 		endInsertRows ();
  2182 	}
  2183 	emit (layoutChanged() );
  2184 
  2185 	// save scroll state. If scrolled, automatically select
  2186 	// new branch in order to tmp unscroll parent...
  2187 	newbi->createMapObj(mapScene);
  2188 	reposition();
  2189 	return newbi;
  2190 }	
  2191 
  2192 BranchItem* VymModel::addNewBranch(int pos)
  2193 {
  2194 	// Different meaning than num in addNewBranchInt!
  2195 	// -1	add above
  2196 	//  0	add as child
  2197 	// +1	add below
  2198 	BranchItem *newbi=NULL;
  2199 	BranchItem *selbi=getSelectedBranch();
  2200 
  2201 	if (selbi)
  2202 	{
  2203 		// FIXME-3 setCursor (Qt::ArrowCursor);  //Still needed?
  2204 
  2205 		newbi=addNewBranchInt (selbi,pos-2);
  2206 
  2207 		if (newbi)
  2208 		{
  2209 			saveState(
  2210 				newbi,		
  2211 				"delete ()",
  2212 				selbi,
  2213 				QString ("addBranch (%1)").arg(pos),
  2214 				QString ("Add new branch to %1").arg(getObjectName(selbi)));	
  2215 
  2216 			reposition();
  2217 			// emitSelectionChanged(); FIXME-3
  2218 			latestAddedItem=newbi;
  2219 			// In Network mode, the client needs to know where the new branch is,
  2220 			// so we have to pass on this information via saveState.
  2221 			// TODO: Get rid of this positioning workaround
  2222 			/* FIXME-4  network problem:  QString ps=qpointfToString (newbo->getAbsPos());
  2223 			sendData ("selectLatestAdded ()");
  2224 			sendData (QString("move %1").arg(ps));
  2225 			sendSelection();
  2226 			*/
  2227 		}
  2228 	}	
  2229 	return newbi;
  2230 }
  2231 
  2232 
  2233 BranchItem* VymModel::addNewBranchBefore()	
  2234 {
  2235 	BranchItem *newbi=NULL;
  2236 	BranchItem *selbi=getSelectedBranch();
  2237 	if (selbi && selbi->getType()==TreeItem::Branch)
  2238 		 // We accept no MapCenter here, so we _have_ a parent
  2239 	{
  2240 		//QPointF p=bo->getRelPos();
  2241 
  2242 
  2243 		// add below selection
  2244 		newbi=addNewBranchInt (selbi,-1);
  2245 
  2246 		if (newbi)
  2247 		{
  2248 			//newbi->move2RelPos (p);
  2249 
  2250 			// Move selection to new branch
  2251 			relinkBranch (selbi,newbi,0);
  2252 
  2253 			saveState (newbi, "deleteKeepChildren ()", newbi, "addBranchBefore ()", 
  2254 				QString ("Add branch before %1").arg(getObjectName(selbi)));
  2255 
  2256 			// FIXME-3 needed? reposition();
  2257 			// emitSelectionChanged(); FIXME-3 
  2258 		}
  2259 	}	
  2260 	return newbi;
  2261 }
  2262 
  2263 bool VymModel::relinkBranch (BranchItem *branch, BranchItem *dst, int pos)
  2264 {
  2265 	if (branch && dst)
  2266 	{
  2267 		if (branch->depth()==0) 
  2268 		{
  2269 			cout <<"VM::relinkBranch  d=0 for "<<branch->getHeadingStd()<<endl;
  2270 		}
  2271 		emit (layoutAboutToBeChanged() );
  2272 		BranchItem *branchpi=(BranchItem*)branch->parent();
  2273 		// Remove at current position
  2274 		int n=branch->childNum();
  2275 		beginRemoveRows (index(branchpi),n,n);
  2276 		branchpi->removeChild (n);
  2277 		endRemoveRows();
  2278 
  2279 		if (pos<0 ||pos>dst->branchCount() ) pos=dst->branchCount();
  2280 
  2281 		// Append as last branch to dst
  2282 		if (dst->branchCount()==0)
  2283 			n=0;
  2284 		else	
  2285 			n=dst->getFirstBranch()->childNumber(); 
  2286 		beginInsertRows (index(dst),n+pos,n+pos);
  2287 		dst->insertBranch (pos,branch);
  2288 		endInsertRows();
  2289 
  2290 		// Correct type if necessesary
  2291 		if (branch->getType()==TreeItem::MapCenter) 
  2292 			branch->setType(TreeItem::Branch);
  2293 
  2294 		// reset parObj, fonts, frame, etc in related LMO or other view-objects
  2295 		branch->updateStyles();
  2296 
  2297 		emit (layoutChanged() );
  2298 		reposition();	// both for moveUp/Down and relinking
  2299 		if (dst->isScrolled() )
  2300 		{
  2301 			select (dst);	
  2302 			branch->updateVisibility();
  2303 		}
  2304 		else	
  2305 			select (branch);
  2306 		return true;
  2307 	}
  2308 	return false;
  2309 }
  2310 
  2311 bool VymModel::relinkImage (ImageItem *image, BranchItem *dst)
  2312 {
  2313 	if (image && dst)
  2314 	{
  2315 		emit (layoutAboutToBeChanged() );
  2316 
  2317 		BranchItem *pi=(BranchItem*)(image->parent());
  2318 		QString oldParString=getSelectString (pi);
  2319 		// Remove at current position
  2320 		int n=image->childNum();
  2321 		beginRemoveRows (index(pi),n,n);
  2322 		pi->removeChild (n);
  2323 		endRemoveRows();
  2324 
  2325 		// Add at dst
  2326 		QModelIndex dstix=index(dst);
  2327 		n=dst->getRowNumAppend (image);
  2328 		beginInsertRows (dstix,n,n+1);	
  2329 		dst->appendChild (image);	
  2330 		endInsertRows ();
  2331 
  2332 		// Set new parent also for lmo
  2333 		if (image->getLMO() && dst->getLMO() )
  2334 			image->getLMO()->setParObj (dst->getLMO() );
  2335 
  2336 		emit (layoutChanged() );
  2337 		saveState(
  2338 			image,
  2339 			QString("relinkTo (\"%1\")").arg(oldParString), 
  2340 			image,
  2341 			QString ("relinkTo (\"%1\")").arg(getSelectString (dst)),
  2342 			QString ("Relink floatimage to %1").arg(getObjectName(dst)));
  2343 		return true;	
  2344 	}
  2345 	return false;
  2346 }
  2347 
  2348 void VymModel::deleteSelection()	
  2349 {
  2350 	BranchItem *selbi=getSelectedBranch();
  2351 
  2352 	if (selbi)
  2353 	{
  2354 		unselect();
  2355 		saveStateRemovingPart (selbi, QString ("Delete %1").arg(getObjectName(selbi)));
  2356 
  2357 		TreeItem *pi=deleteItem (selbi);
  2358 		if (pi)
  2359 		{
  2360 			select (pi);
  2361 			emitShowSelection();
  2362 		}
  2363 		return;
  2364 	}
  2365 	TreeItem *ti=getSelectedItem();
  2366 	if (ti)
  2367 	{
  2368 		TreeItem *pi=ti->parent();
  2369 		if (!pi) return;
  2370 		if (ti->getType()==TreeItem::Image || ti->getType()==TreeItem::Attribute)
  2371 		{
  2372 			saveStateChangingPart(
  2373 				pi, 
  2374 				ti,
  2375 				"delete ()",
  2376 				QString("Delete %1").arg(getObjectName(ti))
  2377 			);
  2378 			unselect();
  2379 			deleteItem (ti);
  2380 			emitDataHasChanged (pi);
  2381 			select (pi);
  2382 			reposition();
  2383 			emitShowSelection();
  2384 		} else if (ti->getType()==TreeItem::XLink)
  2385 		{
  2386 			//FIXME-2 savestate missing
  2387 			deleteItem (ti);
  2388 		} else
  2389 			qWarning ("VymmModel::deleteSelection()  unknown type?!");
  2390 	}
  2391 }
  2392 
  2393 void VymModel::deleteKeepChildren()	//FIXME-3 does not work yet for mapcenters
  2394 
  2395 {
  2396 	BranchItem *selbi=getSelectedBranch();
  2397 	BranchItem *pi;
  2398 	if (selbi)
  2399 	{
  2400 		// Don't use this on mapcenter
  2401 		if (selbi->depth()<2) return;
  2402 
  2403 		pi=(BranchItem*)(selbi->parent());
  2404 		// Check if we have childs at all to keep
  2405 		if (selbi->branchCount()==0) 
  2406 		{
  2407 			deleteSelection();
  2408 			return;
  2409 		}
  2410 
  2411 		QPointF p;
  2412 		if (selbi->getLMO()) p=selbi->getLMO()->getRelPos();
  2413 		saveStateChangingPart(
  2414 			pi,
  2415 			selbi,
  2416 			"deleteKeepChildren ()",
  2417 			QString("Remove %1 and keep its children").arg(getObjectName(selbi))
  2418 		);
  2419 
  2420 		QString sel=getSelectString(selbi);
  2421 		unselect();
  2422 		int pos=selbi->num();
  2423 		BranchItem *bi=selbi->getFirstBranch();
  2424 		while (bi)
  2425 		{
  2426 			relinkBranch (bi,pi,pos);
  2427 			bi=selbi->getFirstBranch();
  2428 			pos++;
  2429 		}
  2430 		deleteItem (selbi);
  2431 		reposition();
  2432 		select (sel);
  2433 		BranchObj *bo=getSelectedBranchObj();
  2434 		if (bo) 
  2435 		{
  2436 			bo->move2RelPos (p);
  2437 			reposition();
  2438 		}
  2439 	}	
  2440 }
  2441 
  2442 void VymModel::deleteChildren()		
  2443 
  2444 {
  2445 	BranchItem *selbi=getSelectedBranch();
  2446 	if (selbi)
  2447 	{		
  2448 		saveStateChangingPart(
  2449 			selbi, 
  2450 			selbi,
  2451 			"deleteChildren ()",
  2452 			QString( "Remove children of branch %1").arg(getObjectName(selbi))
  2453 		);
  2454 		emit (layoutAboutToBeChanged() );
  2455 
  2456 		QModelIndex ix=index (selbi);
  2457 		int n=selbi->branchCount()-1;
  2458 		beginRemoveRows (ix,0,n);
  2459 		removeRows (0,n+1,ix);
  2460 		endRemoveRows();
  2461 		if (selbi->isScrolled()) selbi->unScroll();
  2462 		emit (layoutChanged() );
  2463 		reposition();
  2464 	}	
  2465 }
  2466 
  2467 TreeItem* VymModel::deleteItem (TreeItem *ti)
  2468 {
  2469 	if (ti)
  2470 	{
  2471 		TreeItem *pi=ti->parent();
  2472 		QModelIndex parentIndex=index(pi);
  2473 
  2474 		emit (layoutAboutToBeChanged() );
  2475 
  2476 		int n=ti->childNum();
  2477 		beginRemoveRows (parentIndex,n,n);
  2478 		removeRows (n,1,parentIndex);
  2479 		endRemoveRows();
  2480 		reposition();
  2481 
  2482 		emit (layoutChanged() );
  2483 		if (pi->depth()>=0) return pi;
  2484 	}	
  2485 	return NULL;
  2486 }
  2487 
  2488 void VymModel::clearItem (TreeItem *ti)
  2489 {
  2490 	if (ti)
  2491 	{
  2492 		QModelIndex parentIndex=index(ti);
  2493 		if (!parentIndex.isValid()) return;
  2494 
  2495 		int n=ti->childCount();
  2496 		if (n==0) return;
  2497 
  2498 		emit (layoutAboutToBeChanged() );
  2499 
  2500 		beginRemoveRows (parentIndex,0,n-1);
  2501 		removeRows (0,n,parentIndex);
  2502 		endRemoveRows();
  2503 		reposition();
  2504 
  2505 		emit (layoutChanged() );
  2506 
  2507 	}	
  2508 	return ;
  2509 }
  2510 
  2511 bool VymModel::scrollBranch(BranchItem *bi)
  2512 {
  2513 	if (bi)	
  2514 	{
  2515 		if (bi->isScrolled()) return false;
  2516 		if (bi->branchCount()==0) return false;
  2517 		if (bi->depth()==0) return false;
  2518 		if (bi->toggleScroll())
  2519 		{
  2520 			QString u,r;
  2521 			r="scroll";
  2522 			u="unscroll";
  2523 			saveState(
  2524 				bi,
  2525 				QString ("%1 ()").arg(u),
  2526 				bi,
  2527 				QString ("%1 ()").arg(r),
  2528 				QString ("%1 %2").arg(r).arg(getObjectName(bi))
  2529 			);
  2530 			emitDataHasChanged(bi);
  2531 			emitSelectionChanged();
  2532 			mapScene->update(); //Needed for _quick_ update,  even in 1.13.x 
  2533 			return true;
  2534 		}
  2535 	}	
  2536 	return false;
  2537 }
  2538 
  2539 bool VymModel::unscrollBranch(BranchItem *bi)
  2540 {
  2541 	if (bi)
  2542 	{
  2543 		if (!bi->isScrolled()) return false;
  2544 		if (bi->branchCount()==0) return false;
  2545 		if (bi->depth()==0) return false;
  2546 		if (bi->toggleScroll())
  2547 		{
  2548 			reposition();
  2549 		QString u,r;
  2550 		u="scroll";
  2551 		r="unscroll";
  2552 		saveState(
  2553 			bi,
  2554 			QString ("%1 ()").arg(u),
  2555 			bi,
  2556 			QString ("%1 ()").arg(r),
  2557 			QString ("%1 %2").arg(r).arg(getObjectName(bi))
  2558 		);
  2559 		emitDataHasChanged(bi);
  2560 		emitSelectionChanged();
  2561 			mapScene->update(); //Needed for _quick_ update,  even in 1.13.x 
  2562 		return true;
  2563 	}	
  2564 	}	
  2565 	return false;
  2566 }
  2567 
  2568 void VymModel::toggleScroll()	
  2569 {
  2570 	BranchItem *bi=(BranchItem*)getSelectedBranch();
  2571 	if (bi && bi->isBranchLikeType() )
  2572 	{
  2573 		if (bi->isScrolled())
  2574 			unscrollBranch (bi);
  2575 		else
  2576 			scrollBranch (bi);
  2577 	}
  2578 	// saveState & reposition are called in above functions
  2579 }
  2580 
  2581 void VymModel::unscrollChildren() 	//FIXME-2 does not update flag yet, possible segfault
  2582 {
  2583 	BranchItem *selbi=getSelectedBranch();
  2584 	BranchItem *prev=NULL;
  2585 	BranchItem *cur=selbi;
  2586 	if (selbi)
  2587 	{
  2588 		saveStateChangingPart(
  2589 			selbi,
  2590 			selbi,
  2591 			QString ("unscrollChildren ()"),
  2592 			QString ("unscroll all children of %1").arg(getObjectName(selbi))
  2593 		);	
  2594 		while (cur) 
  2595 		{
  2596 			if (cur->isScrolled())
  2597 			{
  2598 				cur->toggleScroll(); 
  2599 				emitDataHasChanged (cur);
  2600 		}
  2601 			cur=next (cur,prev,selbi);
  2602 		}	
  2603 		updateActions();
  2604 		reposition();
  2605 	}	
  2606 }
  2607 
  2608 void VymModel::emitExpandAll()
  2609 {
  2610 	emit (expandAll() );
  2611 }
  2612 
  2613 void VymModel::toggleStandardFlag (const QString &name, FlagRow *master)
  2614 {
  2615 	BranchItem *bi=getSelectedBranch();
  2616 	if (bi) 
  2617 	{
  2618 		QString u,r;
  2619 		if (bi->isActiveStandardFlag(name))
  2620 		{
  2621 			r="unsetFlag";
  2622 			u="setFlag";
  2623 		}	
  2624 		else
  2625 		{
  2626 			u="unsetFlag";
  2627 			r="setFlag";
  2628 		}	
  2629 		saveState(
  2630 			bi,
  2631 			QString("%1 (\"%2\")").arg(u).arg(name), 
  2632 			bi,
  2633 			QString("%1 (\"%2\")").arg(r).arg(name),
  2634 			QString("Toggling standard flag \"%1\" of %2").arg(name).arg(getObjectName(bi)));
  2635 			bi->toggleStandardFlag (name, master);
  2636 		reposition();
  2637 		emitSelectionChanged();	
  2638 	}
  2639 }
  2640 
  2641 void VymModel::addFloatImage (const QPixmap &img) 
  2642 {
  2643 	BranchItem *selbi=getSelectedBranch();
  2644 	if (selbi)
  2645 	{
  2646 		ImageItem *ii=createImage (selbi);
  2647 		ii->load(img);
  2648 		ii->setOriginalFilename("No original filename (image added by dropevent)");	
  2649 		QString s=getSelectString(selbi);
  2650 		saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",ii  );
  2651 		saveState (ii,"delete ()", selbi,QString("paste(%1)").arg(curStep),"Pasting dropped image");
  2652 		reposition();
  2653 		// FIXME-3 VM needed? scene()->update();
  2654 	}
  2655 }
  2656 
  2657 
  2658 void VymModel::colorBranch (QColor c)	
  2659 {
  2660 	BranchItem *selbi=getSelectedBranch();
  2661 	if (selbi)
  2662 	{
  2663 		saveState(
  2664 			selbi, 
  2665 			QString ("colorBranch (\"%1\")").arg(selbi->getHeadingColor().name()),
  2666 			selbi,
  2667 			QString ("colorBranch (\"%1\")").arg(c.name()),
  2668 			QString("Set color of %1 to %2").arg(getObjectName(selbi)).arg(c.name())
  2669 		);	
  2670 		selbi->setHeadingColor(c); // color branch
  2671 		mapScene->update();
  2672 	}
  2673 }
  2674 
  2675 void VymModel::colorSubtree (QColor c) 
  2676 {
  2677 	BranchItem *selbi=getSelectedBranch();
  2678 	if (selbi)
  2679 	{
  2680 		saveStateChangingPart(
  2681 			selbi,
  2682 			selbi,
  2683 			QString ("colorSubtree (\"%1\")").arg(c.name()),
  2684 			QString ("Set color of %1 and children to %2").arg(getObjectName(selbi)).arg(c.name())
  2685 		);	
  2686 		BranchItem *prev=NULL;
  2687 		BranchItem *cur=selbi;
  2688 		while (cur) 
  2689 		{
  2690 			cur->setHeadingColor(c); // color links, color children
  2691 			cur=next (cur,prev,selbi);
  2692 		}	
  2693 	mapScene->update();
  2694 	}
  2695 }
  2696 
  2697 QColor VymModel::getCurrentHeadingColor()	
  2698 {
  2699 	BranchItem *selbi=getSelectedBranch();
  2700 	if (selbi)	return selbi->getHeadingColor();
  2701 		
  2702 	QMessageBox::warning(0,"Warning","Can't get color of heading,\nthere's no branch selected");
  2703 	return Qt::black;
  2704 }
  2705 
  2706 
  2707 
  2708 void VymModel::editURL()	
  2709 {
  2710 	TreeItem *selti=getSelectedItem();
  2711 	if (selti)
  2712 	{		
  2713 		bool ok;
  2714 		QString text = QInputDialog::getText(
  2715 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2716 				selti->getURL(), &ok, NULL);
  2717 		if ( ok) 
  2718 			// user entered something and pressed OK
  2719 			setURL(text);
  2720 	}
  2721 }
  2722 
  2723 void VymModel::editLocalURL()
  2724 {
  2725 	TreeItem *selti=getSelectedItem();
  2726 	if (selti)
  2727 	{		
  2728 		QStringList filters;
  2729 		filters <<"All files (*)";
  2730 		filters << tr("Text","Filedialog") + " (*.txt)";
  2731 		filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
  2732 		filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
  2733 		filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
  2734 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Set URL to a local file"));
  2735 		fd->setFilters (filters);
  2736 		fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
  2737 		fd->setDirectory (lastFileDir);
  2738 		if (! selti->getVymLink().isEmpty() )
  2739 			fd->selectFile( selti->getURL() );
  2740 		fd->show();
  2741 
  2742 		if ( fd->exec() == QDialog::Accepted )
  2743 		{
  2744 			lastFileDir=QDir (fd->directory().path());
  2745 			setURL (fd->selectedFile() );
  2746 		}
  2747 	}
  2748 }
  2749 
  2750 
  2751 void VymModel::editHeading2URL() 
  2752 {
  2753 	TreeItem *selti=getSelectedItem();
  2754 	if (selti)
  2755 		setURL (selti->getHeading());
  2756 }	
  2757 
  2758 void VymModel::editBugzilla2URL()	
  2759 {
  2760 	TreeItem *selti=getSelectedItem();
  2761 	if (selti)
  2762 	{		
  2763 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+selti->getHeading();
  2764 		setURL (url);
  2765 	}
  2766 }	
  2767 
  2768 void VymModel::editFATE2URL()
  2769 {
  2770 	TreeItem *selti=getSelectedItem();
  2771 	if (selti)
  2772 	{		
  2773 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+selti->getHeading();
  2774 		saveState(
  2775 			selti,
  2776 			"setURL (\""+selti->getURL()+"\")",
  2777 			selti,
  2778 			"setURL (\""+url+"\")",
  2779 			QString("Use heading of %1 as link to FATE").arg(getObjectName(selti))
  2780 		);	
  2781 		selti->setURL (url);
  2782 		// FIXME-4 updateActions();
  2783 	}
  2784 }	
  2785 
  2786 void VymModel::editVymLink()
  2787 {
  2788 	BranchItem *bi=getSelectedBranch();
  2789 	if (bi)
  2790 	{		
  2791 		QStringList filters;
  2792 		filters <<"VYM map (*.vym)";
  2793 		QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Link to another map"));
  2794 		fd->setFilters (filters);
  2795 		fd->setCaption(vymName+" - " +tr("Link to another map"));
  2796 		fd->setDirectory (lastFileDir);
  2797 		if (! bi->getVymLink().isEmpty() )
  2798 			fd->selectFile( bi->getVymLink() );
  2799 		fd->show();
  2800 
  2801 		QString fn;
  2802 		if ( fd->exec() == QDialog::Accepted )
  2803 		{
  2804 			lastFileDir=QDir (fd->directory().path());
  2805 			saveState(
  2806 				bi,
  2807 				"setVymLink (\""+bi->getVymLink()+"\")",
  2808 				bi,
  2809 				"setVymLink (\""+fd->selectedFile()+"\")",
  2810 				QString("Set vymlink of %1 to %2").arg(getObjectName(bi)).arg(fd->selectedFile())
  2811 			);	
  2812 			setVymLink (fd->selectedFile() );	// FIXME-2 ok?
  2813 		}
  2814 	}
  2815 }
  2816 
  2817 void VymModel::setVymLink (const QString &s)	// FIXME-3 no savestate?
  2818 {
  2819 	// Internal function, no saveState needed
  2820 	TreeItem *selti=getSelectedItem();
  2821 	if (selti)
  2822 	{
  2823 		selti->setVymLink(s);
  2824 		reposition();
  2825 		emitDataHasChanged (selti);
  2826 		emitShowSelection();
  2827 	}
  2828 }
  2829 
  2830 void VymModel::deleteVymLink()
  2831 {
  2832 	BranchItem *bi=getSelectedBranch();
  2833 	if (bi)
  2834 	{		
  2835 		saveState(
  2836 			bi,
  2837 			"setVymLink (\""+bi->getVymLink()+"\")", 
  2838 			bi,
  2839 			"setVymLink (\"\")",
  2840 			QString("Unset vymlink of %1").arg(getObjectName(bi))
  2841 		);	
  2842 		bi->setVymLink ("" );
  2843 		updateActions();
  2844 		reposition();
  2845 	}
  2846 }
  2847 
  2848 QString VymModel::getVymLink()
  2849 {
  2850 	BranchItem *bi=getSelectedBranch();
  2851 	if (bi)
  2852 		return bi->getVymLink();
  2853 	else	
  2854 		return "";
  2855 	
  2856 }
  2857 
  2858 QStringList VymModel::getVymLinks()	
  2859 {
  2860 	QStringList links;
  2861 	BranchItem *selbi=getSelectedBranch();
  2862 	BranchItem *cur=selbi;
  2863 	BranchItem *prev=NULL;
  2864 	while (cur) 
  2865 	{
  2866 		if (!cur->getVymLink().isEmpty()) links.append( cur->getVymLink());
  2867 		cur=next (cur,prev,selbi);
  2868 	}	
  2869 	return links;
  2870 }
  2871 
  2872 
  2873 void VymModel::followXLink(int i)	
  2874 {
  2875 	i=0;
  2876 	BranchItem *selbi=getSelectedBranch();
  2877 	if (selbi)
  2878 	{
  2879 		selbi=selbi->getXLinkNum(i)->getPartnerBranch();
  2880 		if (selbi) select (selbi);
  2881 	}
  2882 }
  2883 
  2884 void VymModel::editXLink(int i)	
  2885 {
  2886 	i=0;
  2887 	BranchItem *selbi=getSelectedBranch();
  2888 	if (selbi)
  2889 	{
  2890 		XLinkItem *xli=selbi->getXLinkNum(i);
  2891 		if (xli) 
  2892 		{
  2893 			EditXLinkDialog dia;
  2894 			dia.setXLink (xli);
  2895 			dia.setSelection(selbi);
  2896 			if (dia.exec() == QDialog::Accepted)
  2897 			{
  2898 				if (dia.useSettingsGlobal() )
  2899 				{
  2900 					setMapDefXLinkColor (xli->getColor() );
  2901 					setMapDefXLinkWidth (xli->getWidth() );
  2902 				}
  2903 				if (dia.deleteXLink()) deleteItem (xli);
  2904 			}
  2905 		}	
  2906 	}
  2907 }
  2908 
  2909 
  2910 
  2911 
  2912 
  2913 //////////////////////////////////////////////
  2914 // Scripting
  2915 //////////////////////////////////////////////
  2916 
  2917 void VymModel::parseAtom(const QString &atom)
  2918 {
  2919 	TreeItem* selti=getSelectedItem();
  2920 	BranchItem *selbi=getSelectedBranch();
  2921 	QString s,t;
  2922 	double x,y;
  2923 	int n;
  2924 	bool b,ok;
  2925 
  2926 	// Split string s into command and parameters
  2927 	parser.parseAtom (atom);
  2928 	QString com=parser.getCommand();
  2929 	
  2930 	// External commands
  2931 	/////////////////////////////////////////////////////////////////////
  2932 	if (com=="addBranch")
  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 			QList <int> pl;
  2943 			pl << 0 <<1;
  2944 			if (parser.checkParCount(pl))
  2945 			{
  2946 				if (parser.parCount()==0)
  2947 					addNewBranch (0);
  2948 				else
  2949 				{
  2950 					n=parser.parInt (ok,0);
  2951 					if (ok ) addNewBranch (n);
  2952 				}
  2953 			}
  2954 		}
  2955 	/////////////////////////////////////////////////////////////////////
  2956 	} else if (com=="addBranchBefore")
  2957 	{
  2958 		if (!selti)
  2959 		{
  2960 			parser.setError (Aborted,"Nothing selected");
  2961 		} else if (! selbi )
  2962 		{				  
  2963 			parser.setError (Aborted,"Type of selection is not a branch");
  2964 		} else 
  2965 		{	
  2966 			if (parser.parCount()==0)
  2967 			{
  2968 				addNewBranchBefore ();
  2969 			}	
  2970 		}
  2971 	/////////////////////////////////////////////////////////////////////
  2972 	} else if (com==QString("addMapCenter"))
  2973 	{
  2974 		if (parser.checkParCount(2))
  2975 		{
  2976 			x=parser.parDouble (ok,0);
  2977 			if (ok)
  2978 			{
  2979 				y=parser.parDouble (ok,1);
  2980 				if (ok) addMapCenter (QPointF(x,y));
  2981 			}
  2982 		}	
  2983 	/////////////////////////////////////////////////////////////////////
  2984 	} else if (com==QString("addMapReplace"))
  2985 	{
  2986 		if (!selti)
  2987 		{
  2988 			parser.setError (Aborted,"Nothing selected");
  2989 		} else if (! selbi )
  2990 		{				  
  2991 			parser.setError (Aborted,"Type of selection is not a branch");
  2992 		} else if (parser.checkParCount(1))
  2993 		{
  2994 			//s=parser.parString (ok,0);	// selection
  2995 			t=parser.parString (ok,0);	// path to map
  2996 			if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  2997 			addMapReplaceInt(getSelectString(selbi),t);	
  2998 		}
  2999 	/////////////////////////////////////////////////////////////////////
  3000 	} else if (com==QString("addMapInsert"))
  3001 	{
  3002 		if (parser.parCount()==2)
  3003 		{
  3004 
  3005 			if (!selti)
  3006 			{
  3007 				parser.setError (Aborted,"Nothing selected");
  3008 			} else if (! selbi )
  3009 			{				  
  3010 				parser.setError (Aborted,"Type of selection is not a branch");
  3011 			} else 
  3012 			{	
  3013 				t=parser.parString (ok,0);	// path to map
  3014 				n=parser.parInt(ok,1);		// position
  3015 				if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  3016 				addMapInsertInt(t,n);	
  3017 			}
  3018 		} else if (parser.parCount()==1)
  3019 		{
  3020 			t=parser.parString (ok,0);	// path to map
  3021 			if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
  3022 			addMapInsertInt(t);	
  3023 		} else
  3024 			parser.setError (Aborted,"Wrong number of parameters");
  3025 	/////////////////////////////////////////////////////////////////////
  3026 	} else if (com==QString("addXLink"))
  3027 	{
  3028 		if (parser.parCount()>1)
  3029 		{
  3030 			s=parser.parString (ok,0);	// begin
  3031 			t=parser.parString (ok,1);	// end
  3032 			BranchItem *begin=(BranchItem*)findBySelectString(s);
  3033 			BranchItem *end=(BranchItem*)findBySelectString(t);
  3034 			if (begin && end)
  3035 			{
  3036 				if (begin->isBranchLikeType() && end->isBranchLikeType())
  3037 				{
  3038 					XLinkItem *xl=createXLink (begin,true);
  3039 					if (xl)
  3040 					{
  3041 						xl->setEnd (end);
  3042 						xl->activate();
  3043 					} else
  3044 						parser.setError (Aborted,"Failed to create xLink");
  3045 				}
  3046 				else
  3047 					parser.setError (Aborted,"begin or end of xLink are not branch or mapcenter");
  3048 				
  3049 			} else
  3050 				parser.setError (Aborted,"Couldn't select begin or end of xLink");
  3051 		} else
  3052 			parser.setError (Aborted,"Need at least 2 parameters for begin and end");
  3053 	/////////////////////////////////////////////////////////////////////
  3054 	} else if (com=="clearFlags")	
  3055 	{
  3056 		if (!selti )
  3057 		{
  3058 			parser.setError (Aborted,"Nothing selected");
  3059 		} else if (! selbi )
  3060 		{				  
  3061 			parser.setError (Aborted,"Type of selection is not a branch");
  3062 		} else if (parser.checkParCount(0))
  3063 		{
  3064 			selbi->deactivateAllStandardFlags();	
  3065 		}
  3066 	/////////////////////////////////////////////////////////////////////
  3067 	} else if (com=="colorBranch")
  3068 	{
  3069 		if (!selti)
  3070 		{
  3071 			parser.setError (Aborted,"Nothing selected");
  3072 		} else if (! selbi )
  3073 		{				  
  3074 			parser.setError (Aborted,"Type of selection is not a branch");
  3075 		} else if (parser.checkParCount(1))
  3076 		{	
  3077 			QColor c=parser.parColor (ok,0);
  3078 			if (ok) colorBranch (c);
  3079 		}	
  3080 	/////////////////////////////////////////////////////////////////////
  3081 	} else if (com=="colorSubtree")
  3082 	{
  3083 		if (!selti)
  3084 		{
  3085 			parser.setError (Aborted,"Nothing selected");
  3086 		} else if (! selbi )
  3087 		{				  
  3088 			parser.setError (Aborted,"Type of selection is not a branch");
  3089 		} else if (parser.checkParCount(1))
  3090 		{	
  3091 			QColor c=parser.parColor (ok,0);
  3092 			if (ok) colorSubtree (c);
  3093 		}	
  3094 	/////////////////////////////////////////////////////////////////////
  3095 	} else if (com=="copy")
  3096 	{
  3097 		if (!selti)
  3098 		{
  3099 			parser.setError (Aborted,"Nothing selected");
  3100 		} else if ( selectionType()!=TreeItem::Branch  && 
  3101 					selectionType()!=TreeItem::MapCenter  &&
  3102 					selectionType()!=TreeItem::Image )
  3103 		{				  
  3104 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3105 		} else if (parser.checkParCount(0))
  3106 		{	
  3107 			copy();
  3108 		}	
  3109 	/////////////////////////////////////////////////////////////////////
  3110 	} else if (com=="cut")
  3111 	{
  3112 		if (!selti)
  3113 		{
  3114 			parser.setError (Aborted,"Nothing selected");
  3115 		} else if ( selectionType()!=TreeItem::Branch  && 
  3116 					selectionType()!=TreeItem::MapCenter  &&
  3117 					selectionType()!=TreeItem::Image )
  3118 		{				  
  3119 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3120 		} else if (parser.checkParCount(0))
  3121 		{	
  3122 			cut();
  3123 		}	
  3124 	/////////////////////////////////////////////////////////////////////
  3125 	} else if (com=="delete")
  3126 	{
  3127 		if (!selti)
  3128 		{
  3129 			parser.setError (Aborted,"Nothing selected");
  3130 		} 
  3131 		/*else if (selectionType() != TreeItem::Branch && selectionType() != TreeItem::Image )
  3132 		{
  3133 			parser.setError (Aborted,"Type of selection is wrong.");
  3134 		} 
  3135 		*/
  3136 		else if (parser.checkParCount(0))
  3137 		{	
  3138 			deleteSelection();
  3139 		}	
  3140 	/////////////////////////////////////////////////////////////////////
  3141 	} else if (com=="deleteKeepChildren")
  3142 	{
  3143 		if (!selti)
  3144 		{
  3145 			parser.setError (Aborted,"Nothing selected");
  3146 		} else if (! selbi )
  3147 		{
  3148 			parser.setError (Aborted,"Type of selection is not a branch");
  3149 		} else if (parser.checkParCount(0))
  3150 		{	
  3151 			deleteKeepChildren();
  3152 		}	
  3153 	/////////////////////////////////////////////////////////////////////
  3154 	} else if (com=="deleteChildren")
  3155 	{
  3156 		if (!selti)
  3157 		{
  3158 			parser.setError (Aborted,"Nothing selected");
  3159 		} else if (! selbi)
  3160 		{
  3161 			parser.setError (Aborted,"Type of selection is not a branch");
  3162 		} else if (parser.checkParCount(0))
  3163 		{	
  3164 			deleteChildren();
  3165 		}	
  3166 	/////////////////////////////////////////////////////////////////////
  3167 	} else if (com=="exportASCII")
  3168 	{
  3169 		QString fname="";
  3170 		ok=true;
  3171 		if (parser.parCount()>=1)
  3172 			// Hey, we even have a filename
  3173 			fname=parser.parString(ok,0); 
  3174 		if (!ok)
  3175 		{
  3176 			parser.setError (Aborted,"Could not read filename");
  3177 		} else
  3178 		{
  3179 				exportASCII (fname,false);
  3180 		}
  3181 	/////////////////////////////////////////////////////////////////////
  3182 	} else if (com=="exportImage")
  3183 	{
  3184 		QString fname="";
  3185 		ok=true;
  3186 		if (parser.parCount()>=2)
  3187 			// Hey, we even have a filename
  3188 			fname=parser.parString(ok,0); 
  3189 		if (!ok)
  3190 		{
  3191 			parser.setError (Aborted,"Could not read filename");
  3192 		} else
  3193 		{
  3194 			QString format="PNG";
  3195 			if (parser.parCount()>=2)
  3196 			{
  3197 				format=parser.parString(ok,1);
  3198 			}
  3199 			exportImage (fname,false,format);
  3200 		}
  3201 	/////////////////////////////////////////////////////////////////////
  3202 	} else if (com=="exportXHTML")
  3203 	{
  3204 		QString fname="";
  3205 		ok=true;
  3206 		if (parser.parCount()>=2)
  3207 			// Hey, we even have a filename
  3208 			fname=parser.parString(ok,1); 
  3209 		if (!ok)
  3210 		{
  3211 			parser.setError (Aborted,"Could not read filename");
  3212 		} else
  3213 		{
  3214 			exportXHTML (fname,false);
  3215 		}
  3216 	/////////////////////////////////////////////////////////////////////
  3217 	} else if (com=="exportXML")
  3218 	{
  3219 		QString fname="";
  3220 		ok=true;
  3221 		if (parser.parCount()>=2)
  3222 			// Hey, we even have a filename
  3223 			fname=parser.parString(ok,1); 
  3224 		if (!ok)
  3225 		{
  3226 			parser.setError (Aborted,"Could not read filename");
  3227 		} else
  3228 		{
  3229 			exportXML (fname,false);
  3230 		}
  3231 	/////////////////////////////////////////////////////////////////////
  3232 	} else if (com=="importDir")
  3233 	{
  3234 		if (!selti)
  3235 		{
  3236 			parser.setError (Aborted,"Nothing selected");
  3237 		} else if (! selbi )
  3238 		{				  
  3239 			parser.setError (Aborted,"Type of selection is not a branch");
  3240 		} else if (parser.checkParCount(1))
  3241 		{
  3242 			s=parser.parString(ok,0);
  3243 			if (ok) importDirInt(s);
  3244 		}	
  3245 	/////////////////////////////////////////////////////////////////////
  3246 	} else if (com=="relinkTo")
  3247 	{
  3248 		if (!selti)
  3249 		{
  3250 			parser.setError (Aborted,"Nothing selected");
  3251 		} else if ( selbi)
  3252 		{
  3253 			if (parser.checkParCount(4))
  3254 			{
  3255 				// 0	selectstring of parent
  3256 				// 1	num in parent (for branches)
  3257 				// 2,3	x,y of mainbranch or mapcenter
  3258 				s=parser.parString(ok,0);
  3259 				TreeItem *dst=findBySelectString (s);
  3260 				if (dst)
  3261 				{	
  3262 					if (dst->getType()==TreeItem::Branch) 
  3263 					{
  3264 						// Get number in parent
  3265 						n=parser.parInt (ok,1);
  3266 						if (ok)
  3267 						{
  3268 							relinkBranch (selbi,(BranchItem*)dst,n);
  3269 							emitSelectionChanged();
  3270 						}	
  3271 					} else if (dst->getType()==TreeItem::MapCenter) 
  3272 					{
  3273 						relinkBranch (selbi,(BranchItem*)dst);
  3274 						// Get coordinates of mainbranch
  3275 						x=parser.parDouble(ok,2);
  3276 						if (ok)
  3277 						{
  3278 							y=parser.parDouble(ok,3);
  3279 							if (ok) 
  3280 							{
  3281 								if (selbi->getLMO()) selbi->getLMO()->move (x,y);
  3282 								emitSelectionChanged();
  3283 							}
  3284 						}
  3285 					}	
  3286 				}	
  3287 			}	
  3288 		} else if ( selti->getType() == TreeItem::Image) 
  3289 		{
  3290 			if (parser.checkParCount(1))
  3291 			{
  3292 				// 0	selectstring of parent
  3293 				s=parser.parString(ok,0);
  3294 				TreeItem *dst=findBySelectString (s);
  3295 				if (dst)
  3296 				{	
  3297 					if (dst->isBranchLikeType())
  3298 						relinkImage ( ((ImageItem*)selti),(BranchItem*)dst);
  3299 				} else	
  3300 					parser.setError (Aborted,"Destination is not a branch");
  3301 			}		
  3302 		} else
  3303 			parser.setError (Aborted,"Type of selection is not a floatimage or branch");
  3304 	/////////////////////////////////////////////////////////////////////
  3305 	} else if (com=="loadImage")
  3306 	{
  3307 		if (!selti)
  3308 		{
  3309 			parser.setError (Aborted,"Nothing selected");
  3310 		} else if (! selbi )
  3311 		{				  
  3312 			parser.setError (Aborted,"Type of selection is not a branch");
  3313 		} else if (parser.checkParCount(1))
  3314 		{
  3315 			s=parser.parString(ok,0);
  3316 			if (ok) loadFloatImageInt (selbi,s);
  3317 		}	
  3318 	/////////////////////////////////////////////////////////////////////
  3319 	} else if (com=="moveUp")
  3320 	{
  3321 		if (!selti )
  3322 		{
  3323 			parser.setError (Aborted,"Nothing selected");
  3324 		} else if (! selbi )
  3325 		{				  
  3326 			parser.setError (Aborted,"Type of selection is not a branch");
  3327 		} else if (parser.checkParCount(0))
  3328 		{
  3329 			moveUp();
  3330 		}	
  3331 	/////////////////////////////////////////////////////////////////////
  3332 	} else if (com=="moveDown")
  3333 	{
  3334 		if (!selti )
  3335 		{
  3336 			parser.setError (Aborted,"Nothing selected");
  3337 		} else if (! selbi )
  3338 		{				  
  3339 			parser.setError (Aborted,"Type of selection is not a branch");
  3340 		} else if (parser.checkParCount(0))
  3341 		{
  3342 			moveDown();
  3343 		}	
  3344 	/////////////////////////////////////////////////////////////////////
  3345 	} else if (com=="move")
  3346 	{
  3347 		if (!selti )
  3348 		{
  3349 			parser.setError (Aborted,"Nothing selected");
  3350 		} else if ( selectionType()!=TreeItem::Branch  && 
  3351 					selectionType()!=TreeItem::MapCenter  &&
  3352 					selectionType()!=TreeItem::Image )
  3353 		{				  
  3354 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3355 		} else if (parser.checkParCount(2))
  3356 		{	
  3357 			x=parser.parDouble (ok,0);
  3358 			if (ok)
  3359 			{
  3360 				y=parser.parDouble (ok,1);
  3361 				if (ok) move (x,y);
  3362 			}
  3363 		}	
  3364 	/////////////////////////////////////////////////////////////////////
  3365 	} else if (com=="moveRel")
  3366 	{
  3367 		if (!selti )
  3368 		{
  3369 			parser.setError (Aborted,"Nothing selected");
  3370 		} else if ( selectionType()!=TreeItem::Branch  && 
  3371 					selectionType()!=TreeItem::MapCenter  &&
  3372 					selectionType()!=TreeItem::Image )
  3373 		{				  
  3374 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3375 		} else if (parser.checkParCount(2))
  3376 		{	
  3377 			x=parser.parDouble (ok,0);
  3378 			if (ok)
  3379 			{
  3380 				y=parser.parDouble (ok,1);
  3381 				if (ok) moveRel (x,y);
  3382 			}
  3383 		}	
  3384 	/////////////////////////////////////////////////////////////////////
  3385 	} else if (com=="nop")
  3386 	{
  3387 	/////////////////////////////////////////////////////////////////////
  3388 	} else if (com=="paste")
  3389 	{
  3390 		if (!selti )
  3391 		{
  3392 			parser.setError (Aborted,"Nothing selected");
  3393 		} else if (! selbi )
  3394 		{				  
  3395 			parser.setError (Aborted,"Type of selection is not a branch");
  3396 		} else if (parser.checkParCount(1))
  3397 		{	
  3398 			n=parser.parInt (ok,0);
  3399 			if (ok) pasteNoSave(n);
  3400 		}	
  3401 	/////////////////////////////////////////////////////////////////////
  3402 	} else if (com=="qa")
  3403 	{
  3404 		if (!selti )
  3405 		{
  3406 			parser.setError (Aborted,"Nothing selected");
  3407 		} else if (! selbi )
  3408 		{				  
  3409 			parser.setError (Aborted,"Type of selection is not a branch");
  3410 		} else if (parser.checkParCount(4))
  3411 		{	
  3412 			QString c,u;
  3413 			c=parser.parString (ok,0);
  3414 			if (!ok)
  3415 			{
  3416 				parser.setError (Aborted,"No comment given");
  3417 			} else
  3418 			{
  3419 				s=parser.parString (ok,1);
  3420 				if (!ok)
  3421 				{
  3422 					parser.setError (Aborted,"First parameter is not a string");
  3423 				} else
  3424 				{
  3425 					t=parser.parString (ok,2);
  3426 					if (!ok)
  3427 					{
  3428 						parser.setError (Aborted,"Condition is not a string");
  3429 					} else
  3430 					{
  3431 						u=parser.parString (ok,3);
  3432 						if (!ok)
  3433 						{
  3434 							parser.setError (Aborted,"Third parameter is not a string");
  3435 						} else
  3436 						{
  3437 							if (s!="heading")
  3438 							{
  3439 								parser.setError (Aborted,"Unknown type: "+s);
  3440 							} else
  3441 							{
  3442 								if (! (t=="eq") ) 
  3443 								{
  3444 									parser.setError (Aborted,"Unknown operator: "+t);
  3445 								} else
  3446 								{
  3447 									if (! selbi    )
  3448 									{
  3449 										parser.setError (Aborted,"Type of selection is not a branch");
  3450 									} else
  3451 									{
  3452 										if (selbi->getHeading() == u)
  3453 										{
  3454 											cout << "PASSED: " << qPrintable (c)  << endl;
  3455 										} else
  3456 										{
  3457 											cout << "FAILED: " << qPrintable (c)  << endl;
  3458 										}
  3459 									}
  3460 								}
  3461 							}
  3462 						} 
  3463 					} 
  3464 				} 
  3465 			}
  3466 		}	
  3467 	/////////////////////////////////////////////////////////////////////
  3468 	} else if (com=="saveImage")
  3469 	{
  3470 		ImageItem *ii=getSelectedImage();
  3471 		if (!ii )
  3472 		{
  3473 			parser.setError (Aborted,"No image selected");
  3474 		} else if (parser.checkParCount(2))
  3475 		{
  3476 			s=parser.parString(ok,0);
  3477 			if (ok)
  3478 			{
  3479 				t=parser.parString(ok,1);
  3480 				if (ok) saveFloatImageInt (ii,t,s);
  3481 			}
  3482 		}	
  3483 	/////////////////////////////////////////////////////////////////////
  3484 	} else if (com=="scroll")
  3485 	{
  3486 		if (!selti)
  3487 		{
  3488 			parser.setError (Aborted,"Nothing selected");
  3489 		} else if (! selbi )
  3490 		{				  
  3491 			parser.setError (Aborted,"Type of selection is not a branch");
  3492 		} else if (parser.checkParCount(0))
  3493 		{	
  3494 			if (!scrollBranch (selbi))	
  3495 				parser.setError (Aborted,"Could not scroll branch");
  3496 		}	
  3497 	/////////////////////////////////////////////////////////////////////
  3498 	} else if (com=="select")
  3499 	{
  3500 		if (parser.checkParCount(1))
  3501 		{
  3502 			s=parser.parString(ok,0);
  3503 			if (ok) select (s);
  3504 		}	
  3505 	/////////////////////////////////////////////////////////////////////
  3506 	} else if (com=="selectLastBranch")
  3507 	{
  3508 		if (!selti )
  3509 		{
  3510 			parser.setError (Aborted,"Nothing selected");
  3511 		} else if (! selbi )
  3512 		{				  
  3513 			parser.setError (Aborted,"Type of selection is not a branch");
  3514 		} else if (parser.checkParCount(0))
  3515 		{	
  3516 			BranchItem *bi=selbi->getLastBranch();
  3517 			if (!bi)
  3518 				parser.setError (Aborted,"Could not select last branch");
  3519 			select (bi);		// FIXME-3 was selectInt
  3520 				
  3521 		}	
  3522 	/////////////////////////////////////////////////////////////////////
  3523 	} else /* FIXME-2 if (com=="selectLastImage")
  3524 	{
  3525 		if (!selti )
  3526 		{
  3527 			parser.setError (Aborted,"Nothing selected");
  3528 		} else if (! selbi )
  3529 		{				  
  3530 			parser.setError (Aborted,"Type of selection is not a branch");
  3531 		} else if (parser.checkParCount(0))
  3532 		{	
  3533 			FloatImageObj *fio=selb->getLastFloatImage();
  3534 			if (!fio)
  3535 				parser.setError (Aborted,"Could not select last image");
  3536 			select (fio);		// FIXME-3 was selectInt
  3537 				
  3538 		}	
  3539 	/////////////////////////////////////////////////////////////////////
  3540 	} else */ if (com=="selectLatestAdded")
  3541 	{
  3542 		if (!latestAddedItem)
  3543 		{
  3544 			parser.setError (Aborted,"No latest added object");
  3545 		} else
  3546 		{	
  3547 			if (!select (latestAddedItem))
  3548 				parser.setError (Aborted,"Could not select latest added object ");
  3549 		}	
  3550 	/////////////////////////////////////////////////////////////////////
  3551 	} else if (com=="setFrameType")
  3552 	{
  3553 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3554 		{
  3555 			parser.setError (Aborted,"Type of selection does not allow setting frame type");
  3556 		}
  3557 		else if (parser.checkParCount(1))
  3558 		{
  3559 			s=parser.parString(ok,0);
  3560 			if (ok) setFrameType (s);
  3561 		}	
  3562 	/////////////////////////////////////////////////////////////////////
  3563 	} else if (com=="setFramePenColor")
  3564 	{
  3565 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3566 		{
  3567 			parser.setError (Aborted,"Type of selection does not allow setting of pen color");
  3568 		}
  3569 		else if (parser.checkParCount(1))
  3570 		{
  3571 			QColor c=parser.parColor(ok,0);
  3572 			if (ok) setFramePenColor (c);
  3573 		}	
  3574 	/////////////////////////////////////////////////////////////////////
  3575 	} else if (com=="setFrameBrushColor")
  3576 	{
  3577 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3578 		{
  3579 			parser.setError (Aborted,"Type of selection does not allow setting brush color");
  3580 		}
  3581 		else if (parser.checkParCount(1))
  3582 		{
  3583 			QColor c=parser.parColor(ok,0);
  3584 			if (ok) setFrameBrushColor (c);
  3585 		}	
  3586 	/////////////////////////////////////////////////////////////////////
  3587 	} else if (com=="setFramePadding")
  3588 	{
  3589 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3590 		{
  3591 			parser.setError (Aborted,"Type of selection does not allow setting frame padding");
  3592 		}
  3593 		else if (parser.checkParCount(1))
  3594 		{
  3595 			n=parser.parInt(ok,0);
  3596 			if (ok) setFramePadding(n);
  3597 		}	
  3598 	/////////////////////////////////////////////////////////////////////
  3599 	} else if (com=="setFrameBorderWidth")
  3600 	{
  3601 		if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3602 		{
  3603 			parser.setError (Aborted,"Type of selection does not allow setting frame border width");
  3604 		}
  3605 		else if (parser.checkParCount(1))
  3606 		{
  3607 			n=parser.parInt(ok,0);
  3608 			if (ok) setFrameBorderWidth (n);
  3609 		}	
  3610 	/////////////////////////////////////////////////////////////////////
  3611 	} else if (com=="setMapAuthor")
  3612 	{
  3613 		if (parser.checkParCount(1))
  3614 		{
  3615 			s=parser.parString(ok,0);
  3616 			if (ok) setAuthor (s);
  3617 		}	
  3618 	/////////////////////////////////////////////////////////////////////
  3619 	} else if (com=="setMapComment")
  3620 	{
  3621 		if (parser.checkParCount(1))
  3622 		{
  3623 			s=parser.parString(ok,0);
  3624 			if (ok) setComment(s);
  3625 		}	
  3626 	/////////////////////////////////////////////////////////////////////
  3627 	} else if (com=="setMapBackgroundColor")
  3628 	{
  3629 		if (!selti )
  3630 		{
  3631 			parser.setError (Aborted,"Nothing selected");
  3632 		} else if (! selbi )
  3633 		{				  
  3634 			parser.setError (Aborted,"Type of selection is not a branch");
  3635 		} else if (parser.checkParCount(1))
  3636 		{
  3637 			QColor c=parser.parColor (ok,0);
  3638 			if (ok) setMapBackgroundColor (c);
  3639 		}	
  3640 	/////////////////////////////////////////////////////////////////////
  3641 	} else if (com=="setMapDefLinkColor")
  3642 	{
  3643 		if (!selti )
  3644 		{
  3645 			parser.setError (Aborted,"Nothing selected");
  3646 		} else if (! selbi )
  3647 		{				  
  3648 			parser.setError (Aborted,"Type of selection is not a branch");
  3649 		} else if (parser.checkParCount(1))
  3650 		{
  3651 			QColor c=parser.parColor (ok,0);
  3652 			if (ok) setMapDefLinkColor (c);
  3653 		}	
  3654 	/////////////////////////////////////////////////////////////////////
  3655 	} else if (com=="setMapLinkStyle")
  3656 	{
  3657 		if (parser.checkParCount(1))
  3658 		{
  3659 			s=parser.parString (ok,0);
  3660 			if (ok) setMapLinkStyle(s);
  3661 		}	
  3662 	/////////////////////////////////////////////////////////////////////
  3663 	} else if (com=="setHeading")
  3664 	{
  3665 		if (!selti )
  3666 		{
  3667 			parser.setError (Aborted,"Nothing selected");
  3668 		} else if (! selbi )
  3669 		{				  
  3670 			parser.setError (Aborted,"Type of selection is not a branch");
  3671 		} else if (parser.checkParCount(1))
  3672 		{
  3673 			s=parser.parString (ok,0);
  3674 			if (ok) 
  3675 				setHeading (s);
  3676 		}	
  3677 	/////////////////////////////////////////////////////////////////////
  3678 	} else if (com=="setHideExport")
  3679 	{
  3680 		if (!selti )
  3681 		{
  3682 			parser.setError (Aborted,"Nothing selected");
  3683 		} else if (selectionType()!=TreeItem::Branch && selectionType() != TreeItem::MapCenter &&selectionType()!=TreeItem::Image)
  3684 		{				  
  3685 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  3686 		} else if (parser.checkParCount(1))
  3687 		{
  3688 			b=parser.parBool(ok,0);
  3689 			if (ok) setHideExport (b);
  3690 		}
  3691 	/////////////////////////////////////////////////////////////////////
  3692 	} else if (com=="setIncludeImagesHorizontally")
  3693 	{ 
  3694 		if (!selti )
  3695 		{
  3696 			parser.setError (Aborted,"Nothing selected");
  3697 		} else if (! selbi)
  3698 		{				  
  3699 			parser.setError (Aborted,"Type of selection is not a branch");
  3700 		} else if (parser.checkParCount(1))
  3701 		{
  3702 			b=parser.parBool(ok,0);
  3703 			if (ok) setIncludeImagesHor(b);
  3704 		}
  3705 	/////////////////////////////////////////////////////////////////////
  3706 	} else if (com=="setIncludeImagesVertically")
  3707 	{
  3708 		if (!selti )
  3709 		{
  3710 			parser.setError (Aborted,"Nothing selected");
  3711 		} else if (! selbi)
  3712 		{				  
  3713 			parser.setError (Aborted,"Type of selection is not a branch");
  3714 		} else if (parser.checkParCount(1))
  3715 		{
  3716 			b=parser.parBool(ok,0);
  3717 			if (ok) setIncludeImagesVer(b);
  3718 		}
  3719 	/////////////////////////////////////////////////////////////////////
  3720 	} else if (com=="setHideLinkUnselected")
  3721 	{
  3722 		if (!selti )
  3723 		{
  3724 			parser.setError (Aborted,"Nothing selected");
  3725 		} else if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
  3726 		{				  
  3727 			parser.setError (Aborted,"Type of selection does not allow hiding the link");
  3728 		} else if (parser.checkParCount(1))
  3729 		{
  3730 			b=parser.parBool(ok,0);
  3731 			if (ok) setHideLinkUnselected(b);
  3732 		}
  3733 	/////////////////////////////////////////////////////////////////////
  3734 	} else if (com=="setSelectionColor")
  3735 	{
  3736 		if (parser.checkParCount(1))
  3737 		{
  3738 			QColor c=parser.parColor (ok,0);
  3739 			if (ok) setSelectionColorInt (c);
  3740 		}	
  3741 	/////////////////////////////////////////////////////////////////////
  3742 	} else if (com=="setURL")
  3743 	{
  3744 		if (!selti )
  3745 		{
  3746 			parser.setError (Aborted,"Nothing selected");
  3747 		} else if (! selbi )
  3748 		{				  
  3749 			parser.setError (Aborted,"Type of selection is not a branch");
  3750 		} else if (parser.checkParCount(1))
  3751 		{
  3752 			s=parser.parString (ok,0);
  3753 			if (ok) setURL(s);
  3754 		}	
  3755 	/////////////////////////////////////////////////////////////////////
  3756 	} else if (com=="setVymLink")
  3757 	{
  3758 		if (!selti )
  3759 		{
  3760 			parser.setError (Aborted,"Nothing selected");
  3761 		} else if (! selbi )
  3762 		{				  
  3763 			parser.setError (Aborted,"Type of selection is not a branch");
  3764 		} else if (parser.checkParCount(1))
  3765 		{
  3766 			s=parser.parString (ok,0);
  3767 			if (ok) setVymLink(s);
  3768 		}	
  3769 	}
  3770 	/////////////////////////////////////////////////////////////////////
  3771 	else if (com=="setFlag")
  3772 	{
  3773 		if (!selti )
  3774 		{
  3775 			parser.setError (Aborted,"Nothing selected");
  3776 		} else if (! selbi )
  3777 		{				  
  3778 			parser.setError (Aborted,"Type of selection is not a branch");
  3779 		} else if (parser.checkParCount(1))
  3780 		{
  3781 			s=parser.parString(ok,0);
  3782 			if (ok) 
  3783 				selbi->activateStandardFlag(s);
  3784 		}
  3785 	/////////////////////////////////////////////////////////////////////
  3786 	} else /* FIXME-2 if (com=="setFrameType")
  3787 	{
  3788 		if (!selti )
  3789 		{
  3790 			parser.setError (Aborted,"Nothing selected");
  3791 		} else if (! selb )
  3792 		{				  
  3793 			parser.setError (Aborted,"Type of selection is not a branch");
  3794 		} else if (parser.checkParCount(1))
  3795 		{
  3796 			s=parser.parString(ok,0);
  3797 			if (ok) 
  3798 				setFrameType (s);
  3799 		}
  3800 	/////////////////////////////////////////////////////////////////////
  3801 	} else*/ if (com=="sortChildren")
  3802 	{
  3803 		if (!selti )
  3804 		{
  3805 			parser.setError (Aborted,"Nothing selected");
  3806 		} else if (! selbi )
  3807 		{				  
  3808 			parser.setError (Aborted,"Type of selection is not a branch");
  3809 		} else if (parser.checkParCount(0))
  3810 		{
  3811 			sortChildren();
  3812 		}
  3813 	/////////////////////////////////////////////////////////////////////
  3814 	} else if (com=="toggleFlag")
  3815 	{
  3816 		if (!selti )
  3817 		{
  3818 			parser.setError (Aborted,"Nothing selected");
  3819 		} else if (! selbi )
  3820 		{				  
  3821 			parser.setError (Aborted,"Type of selection is not a branch");
  3822 		} else if (parser.checkParCount(1))
  3823 		{
  3824 			s=parser.parString(ok,0);
  3825 			if (ok) 
  3826 				selbi->toggleStandardFlag(s);	
  3827 		}
  3828 	/////////////////////////////////////////////////////////////////////
  3829 	} else  if (com=="unscroll")
  3830 	{
  3831 		if (!selti)
  3832 		{
  3833 			parser.setError (Aborted,"Nothing selected");
  3834 		} else if (! selbi )
  3835 		{				  
  3836 			parser.setError (Aborted,"Type of selection is not a branch");
  3837 		} else if (parser.checkParCount(0))
  3838 		{	
  3839 			if (!unscrollBranch (selbi))	
  3840 				parser.setError (Aborted,"Could not unscroll branch");
  3841 		}	
  3842 	/////////////////////////////////////////////////////////////////////
  3843 	} else if (com=="unscrollChildren")
  3844 	{
  3845 		if (!selti)
  3846 		{
  3847 			parser.setError (Aborted,"Nothing selected");
  3848 		} else if (! selbi )
  3849 		{				  
  3850 			parser.setError (Aborted,"Type of selection is not a branch");
  3851 		} else if (parser.checkParCount(0))
  3852 		{	
  3853 			unscrollChildren ();
  3854 		}	
  3855 	/////////////////////////////////////////////////////////////////////
  3856 	} else if (com=="unsetFlag")
  3857 	{
  3858 		if (!selti)
  3859 		{
  3860 			parser.setError (Aborted,"Nothing selected");
  3861 		} else if (! selbi )
  3862 		{				  
  3863 			parser.setError (Aborted,"Type of selection is not a branch");
  3864 		} else if (parser.checkParCount(1))
  3865 		{
  3866 			s=parser.parString(ok,0);
  3867 			if (ok) 
  3868 				selbi->deactivateStandardFlag(s);
  3869 		}
  3870 	} else 
  3871 		parser.setError (Aborted,"Unknown command");
  3872 
  3873 	// Any errors?
  3874 	if (parser.errorLevel()==NoError)
  3875 	{
  3876 		// setChanged();  FIXME-2 should not be called e.g. for export?!
  3877 		reposition();
  3878 	}	
  3879 	else	
  3880 	{
  3881 		// TODO Error handling
  3882 		qWarning("VymModel::parseAtom: Error!");
  3883 		qWarning(parser.errorMessage());
  3884 	} 
  3885 }
  3886 
  3887 void VymModel::runScript (QString script)
  3888 {
  3889 	parser.setScript (script);
  3890 	parser.runScript();
  3891 	while (parser.next() ) 
  3892 		parseAtom(parser.getAtom());
  3893 }
  3894 
  3895 void VymModel::setExportMode (bool b)
  3896 {
  3897 	// should be called before and after exports
  3898 	// depending on the settings
  3899 	if (b && settings.value("/export/useHideExport","true")=="true")
  3900 		setHideTmpMode (TreeItem::HideExport);
  3901 	else	
  3902 		setHideTmpMode (TreeItem::HideNone);
  3903 }
  3904 
  3905 void VymModel::exportImage(QString fname, bool askName, QString format)
  3906 {
  3907 	if (fname=="")
  3908 	{
  3909 		fname=getMapName()+".png";
  3910 		format="PNG";
  3911 	} 	
  3912 
  3913 	if (askName)
  3914 	{
  3915 		QStringList fl;
  3916 		QFileDialog *fd=new QFileDialog (NULL);
  3917 		fd->setCaption (tr("Export map as image"));
  3918 		fd->setDirectory (lastImageDir);
  3919 		fd->setFileMode(QFileDialog::AnyFile);
  3920 		fd->setFilters  (imageIO.getFilters() );
  3921 		if (fd->exec())
  3922 		{
  3923 			fl=fd->selectedFiles();
  3924 			fname=fl.first();
  3925 			format=imageIO.getType(fd->selectedFilter());
  3926 		} 
  3927 	}
  3928 
  3929 	setExportMode (true);
  3930 	QPixmap pix (mapEditor->getPixmap());
  3931 	pix.save(fname, format);
  3932 	setExportMode (false);
  3933 }
  3934 
  3935 
  3936 void VymModel::exportXML(QString dir, bool askForName)
  3937 {
  3938 	if (askForName)
  3939 	{
  3940 		dir=browseDirectory(NULL,tr("Export XML to directory"));
  3941 		if (dir =="" && !reallyWriteDirectory(dir) )
  3942 		return;
  3943 	}
  3944 
  3945 	// Hide stuff during export, if settings want this
  3946 	setExportMode (true);
  3947 
  3948 	// Create subdirectories
  3949 	makeSubDirs (dir);
  3950 
  3951 	// write to directory	//FIXME-4 check totalBBox here...
  3952 	QString saveFile=saveToDir (dir,mapName+"-",true,mapEditor->getTotalBBox().topLeft() ,NULL); 
  3953 	QFile file;
  3954 
  3955 	file.setName ( dir + "/"+mapName+".xml");
  3956 	if ( !file.open( QIODevice::WriteOnly ) )
  3957 	{
  3958 		// This should neverever happen
  3959 		QMessageBox::critical (0,tr("Critical Export Error"),tr("VymModel::exportXML couldn't open %1").arg(file.name()));
  3960 		return;
  3961 	}	
  3962 
  3963 	// Write it finally, and write in UTF8, no matter what 
  3964 	QTextStream ts( &file );
  3965 	ts.setEncoding (QTextStream::UnicodeUTF8);
  3966 	ts << saveFile;
  3967 	file.close();
  3968 
  3969 	// Now write image, too
  3970 	exportImage (dir+"/images/"+mapName+".png",false,"PNG");
  3971 
  3972 	setExportMode (false);
  3973 }
  3974 
  3975 void VymModel::exportASCII(QString fname,bool askName)
  3976 {
  3977 	ExportASCII ex;
  3978 	ex.setModel (this);
  3979 	if (fname=="") 
  3980 		ex.setFile (mapName+".txt");	
  3981 	else
  3982 		ex.setFile (fname);
  3983 
  3984 	if (askName)
  3985 	{
  3986 		//ex.addFilter ("TXT (*.txt)");
  3987 		ex.setDir(lastImageDir);
  3988 		//ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
  3989 		ex.execDialog() ; 
  3990 	} 
  3991 	if (!ex.canceled())
  3992 	{
  3993 		setExportMode(true);
  3994 		ex.doExport();
  3995 		setExportMode(false);
  3996 	}
  3997 }
  3998 
  3999 void VymModel::exportXHTML (const QString &dir, bool askForName)
  4000 {
  4001 			ExportXHTMLDialog dia(NULL);
  4002 			dia.setFilePath (filePath );
  4003 			dia.setMapName (mapName );
  4004 			dia.readSettings();
  4005 			if (dir!="") dia.setDir (dir);
  4006 
  4007 			bool ok=true;
  4008 			
  4009 			if (askForName)
  4010 			{
  4011 				if (dia.exec()!=QDialog::Accepted) 
  4012 					ok=false;
  4013 				else	
  4014 				{
  4015 					QDir d (dia.getDir());
  4016 					// Check, if warnings should be used before overwriting
  4017 					// the output directory
  4018 					if (d.exists() && d.count()>0)
  4019 					{
  4020 						WarningDialog warn;
  4021 						warn.showCancelButton (true);
  4022 						warn.setText(QString(
  4023 							"The directory %1 is not empty.\n"
  4024 							"Do you risk to overwrite some of its contents?").arg(d.path() ));
  4025 						warn.setCaption("Warning: Directory not empty");
  4026 						warn.setShowAgainName("mainwindow/overwrite-dir-xhtml");
  4027 
  4028 						if (warn.exec()!=QDialog::Accepted) ok=false;
  4029 					}
  4030 				}	
  4031 			}
  4032 
  4033 			if (ok)
  4034 			{
  4035 				exportXML (dia.getDir(),false );
  4036 				dia.doExport(mapName );
  4037 				//if (dia.hasChanged()) setChanged();
  4038 			}
  4039 }
  4040 
  4041 void VymModel::exportOOPresentation(const QString &fn, const QString &cf)
  4042 {
  4043 	ExportOO ex;
  4044 	ex.setFile (fn);
  4045 	ex.setModel (this);
  4046 	if (ex.setConfigFile(cf)) 
  4047 	{
  4048 		setExportMode (true);
  4049 		ex.exportPresentation();
  4050 		setExportMode (false);
  4051 	}
  4052 }
  4053 
  4054 
  4055 
  4056 
  4057 //////////////////////////////////////////////
  4058 // View related
  4059 //////////////////////////////////////////////
  4060 
  4061 void VymModel::registerEditor(QWidget *me)
  4062 {
  4063 	mapEditor=(MapEditor*)me;
  4064 }
  4065 
  4066 void VymModel::unregisterEditor(QWidget *)
  4067 {
  4068 	mapEditor=NULL;
  4069 }
  4070 
  4071 void VymModel::setContextPos(QPointF p)
  4072 {
  4073 	contextPos=p;
  4074 }
  4075 
  4076 void VymModel::unsetContextPos()
  4077 {
  4078 	contextPos=QPointF();
  4079 }
  4080 
  4081 void VymModel::updateNoteFlag()
  4082 {
  4083 	setChanged();
  4084 	TreeItem *selti=getSelectedItem();
  4085 	if (selti)
  4086 	{
  4087 		if (textEditor->isEmpty()) 
  4088 			selti->clearNote();
  4089 		else
  4090 			selti->setNote (textEditor->getText());
  4091 		emitDataHasChanged(selti);		
  4092 		emitSelectionChanged();
  4093 
  4094 	}
  4095 }
  4096 
  4097 void VymModel::updateRelPositions()		//FIXME-3 VM should have no need to updateRelPos
  4098 {
  4099 	/* FIXME-3 ???
  4100 	for (int i=0; i<rootItem->branchCount(); i++)
  4101 		((MapCenterObj*)rootItem->getBranchObjNum(i))->updateRelPositions();
  4102 		*/
  4103 		/*
  4104 	void MapCenterObj::updateRelPositions()
  4105 	{
  4106 		if (repositionRequest) unsetAllRepositionRequests();
  4107 
  4108 		// update relative Positions of branches and floats
  4109 		for (int i=0; i<treeItem->branchCount(); ++i)
  4110 		{
  4111 			treeItem->getBranchObjNum(i)->setRelPos();
  4112 			treeItem->getBranchObjNum(i)->setOrientation();
  4113 		}
  4114 		
  4115 		for (int i=0; i<floatimage.size(); ++i)
  4116 			floatimage.at(i)->setRelPos();
  4117 
  4118 		if (repositionRequest) reposition();
  4119 	}
  4120 	*/
  4121 }
  4122 
  4123 void VymModel::reposition()	//FIXME-4 VM should have no need to reposition, but the views...
  4124 {
  4125 	//cout << "VM::reposition blocked="<<blockReposition<<endl;
  4126 	if (blockReposition) return;
  4127 
  4128 	for (int i=0;i<rootItem->branchCount(); i++)
  4129 		rootItem->getBranchObjNum(i)->reposition();	//	for positioning heading
  4130 	//emitSelectionChanged();	
  4131 }
  4132 
  4133 
  4134 void VymModel::setMapLinkStyle (const QString & s)
  4135 {
  4136 	QString snow;
  4137 	switch (linkstyle)
  4138 	{
  4139 		case LinkableMapObj::Line :
  4140 			snow="StyleLine";
  4141 			break;
  4142 		case LinkableMapObj::Parabel:
  4143 			snow="StyleParabel";
  4144 			break;
  4145 		case LinkableMapObj::PolyLine:
  4146 			snow="StylePolyLine";
  4147 			break;
  4148 		case LinkableMapObj::PolyParabel:
  4149 			snow="StylePolyParabel";
  4150 			break;
  4151 		default:	
  4152 			snow="UndefinedStyle";
  4153 			break;
  4154 	}
  4155 
  4156 	saveState (
  4157 		QString("setMapLinkStyle (\"%1\")").arg(s),
  4158 		QString("setMapLinkStyle (\"%1\")").arg(snow),
  4159 		QString("Set map link style (\"%1\")").arg(s)
  4160 	);	
  4161 
  4162 	if (s=="StyleLine")
  4163 		linkstyle=LinkableMapObj::Line;
  4164 	else if (s=="StyleParabel")
  4165 		linkstyle=LinkableMapObj::Parabel;
  4166 	else if (s=="StylePolyLine")
  4167 		linkstyle=LinkableMapObj::PolyLine;
  4168 	else if (s=="StylePolyParabel")	
  4169 		linkstyle=LinkableMapObj::PolyParabel;
  4170 	else
  4171 		linkstyle=LinkableMapObj::UndefinedStyle;
  4172 
  4173 	BranchItem *cur=NULL;
  4174 	BranchItem *prev=NULL;
  4175 	BranchObj *bo;
  4176 	next (cur,prev);
  4177 	while (cur) 
  4178 	{
  4179 		bo=(BranchObj*)(cur->getLMO() );
  4180 		bo->setLinkStyle(bo->getDefLinkStyle(cur->parent() ));	//FIXME-3 better emit dataCHanged and leave the changes to View
  4181 		cur=next(cur,prev);
  4182 	}
  4183 	reposition();
  4184 }
  4185 
  4186 LinkableMapObj::Style VymModel::getMapLinkStyle ()
  4187 {
  4188 	return linkstyle;
  4189 }	
  4190 
  4191 void VymModel::setMapDefLinkColor(QColor col)
  4192 {
  4193 	if ( !col.isValid() ) return;
  4194 	saveState (
  4195 		QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
  4196 		QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
  4197 		QString("Set map link color to %1").arg(col.name())
  4198 	);
  4199 
  4200 	defLinkColor=col;
  4201 	BranchItem *cur=NULL;
  4202 	BranchItem *prev=NULL;
  4203 	BranchObj *bo;
  4204 	cur=next(cur,prev);
  4205 	while (cur) 
  4206 	{
  4207 		bo=(BranchObj*)(cur->getLMO() );
  4208 		bo->setLinkColor();
  4209 		next(cur,prev);
  4210 	}
  4211 	updateActions();
  4212 }
  4213 
  4214 void VymModel::setMapLinkColorHintInt()
  4215 {
  4216 	// called from setMapLinkColorHint(lch) or at end of parse
  4217 	BranchItem *cur=NULL;
  4218 	BranchItem *prev=NULL;
  4219 	BranchObj *bo;
  4220 	cur=next(cur,prev);
  4221 	while (cur) 
  4222 	{
  4223 		bo=(BranchObj*)(cur->getLMO() );
  4224 		bo->setLinkColor();
  4225 		cur=next(cur,prev);
  4226 	}
  4227 }
  4228 
  4229 void VymModel::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
  4230 {
  4231 	linkcolorhint=lch;
  4232 	setMapLinkColorHintInt();
  4233 }
  4234 
  4235 void VymModel::toggleMapLinkColorHint()
  4236 {
  4237 	if (linkcolorhint==LinkableMapObj::HeadingColor)
  4238 		linkcolorhint=LinkableMapObj::DefaultColor;
  4239 	else	
  4240 		linkcolorhint=LinkableMapObj::HeadingColor;
  4241 	BranchItem *cur=NULL;
  4242 	BranchItem *prev=NULL;
  4243 	BranchObj *bo;
  4244 	cur=next(cur,prev);
  4245 	while (cur) 
  4246 	{
  4247 		bo=(BranchObj*)(cur->getLMO() );
  4248 		bo->setLinkColor();
  4249 		next(cur,prev);
  4250 	}
  4251 }
  4252 
  4253 void VymModel::selectMapBackgroundImage ()	// FIXME-2 move to ME
  4254 {
  4255 	Q3FileDialog *fd=new Q3FileDialog( NULL);
  4256 	fd->setMode (Q3FileDialog::ExistingFile);
  4257 	fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  4258 	ImagePreview *p =new ImagePreview (fd);
  4259 	fd->setContentsPreviewEnabled( TRUE );
  4260 	fd->setContentsPreview( p, p );
  4261 	fd->setPreviewMode( Q3FileDialog::Contents );
  4262 	fd->setCaption(vymName+" - " +tr("Load background image"));
  4263 	fd->setDir (lastImageDir);
  4264 	fd->show();
  4265 
  4266 	if ( fd->exec() == QDialog::Accepted )
  4267 	{
  4268 		// TODO selectMapBackgroundImg in QT4 use:	lastImageDir=fd->directory();
  4269 		lastImageDir=QDir (fd->dirPath());
  4270 		setMapBackgroundImage (fd->selectedFile());
  4271 	}
  4272 }	
  4273 
  4274 void VymModel::setMapBackgroundImage (const QString &fn)	//FIXME-3 missing savestate, move to ME
  4275 {
  4276 	QColor oldcol=mapScene->backgroundBrush().color();
  4277 	/*
  4278 	saveState(
  4279 		selection,
  4280 		QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
  4281 		selection,
  4282 		QString ("setMapBackgroundImage (%1)").arg(col.name()),
  4283 		QString("Set background color of map to %1").arg(col.name()));
  4284 	*/	
  4285 	QBrush brush;
  4286 	brush.setTextureImage (QPixmap (fn));
  4287 	mapScene->setBackgroundBrush(brush);
  4288 }
  4289 
  4290 void VymModel::selectMapBackgroundColor()	// FIXME-3 move to ME
  4291 {
  4292 	QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), NULL);
  4293 	if ( !col.isValid() ) return;
  4294 	setMapBackgroundColor( col );
  4295 }
  4296 
  4297 
  4298 void VymModel::setMapBackgroundColor(QColor col)	// FIXME-3 move to ME
  4299 {
  4300 	QColor oldcol=mapScene->backgroundBrush().color();
  4301 	saveState(
  4302 		QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
  4303 		QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
  4304 		QString("Set background color of map to %1").arg(col.name()));
  4305 	mapScene->setBackgroundBrush(col);
  4306 }
  4307 
  4308 QColor VymModel::getMapBackgroundColor()	// FIXME-3 move to ME
  4309 {
  4310     return mapScene->backgroundBrush().color();
  4311 }
  4312 
  4313 
  4314 LinkableMapObj::ColorHint VymModel::getMapLinkColorHint()	// FIXME-3 move to ME
  4315 {
  4316 	return linkcolorhint;
  4317 }
  4318 
  4319 QColor VymModel::getMapDefLinkColor()	// FIXME-3 move to ME
  4320 {
  4321 	return defLinkColor;
  4322 }
  4323 
  4324 void VymModel::setMapDefXLinkColor(QColor col)	// FIXME-3 move to ME
  4325 {
  4326 	defXLinkColor=col;
  4327 }
  4328 
  4329 QColor VymModel::getMapDefXLinkColor()	// FIXME-3 move to ME
  4330 {
  4331 	return defXLinkColor;
  4332 }
  4333 
  4334 void VymModel::setMapDefXLinkWidth (int w)	// FIXME-3 move to ME
  4335 {
  4336 	defXLinkWidth=w;
  4337 }
  4338 
  4339 int VymModel::getMapDefXLinkWidth()	// FIXME-3 move to ME
  4340 {
  4341 	return defXLinkWidth;
  4342 }
  4343 
  4344 void VymModel::move(const double &x, const double &y)
  4345 {
  4346 	int i=x; i=y;
  4347 	MapItem *seli = (MapItem*)getSelectedItem();
  4348 	if (seli && (seli->isBranchLikeType() || seli->getType()==TreeItem::Image))
  4349 	{
  4350 		LinkableMapObj *lmo=seli->getLMO();
  4351 		if (lmo)
  4352 		{
  4353 			QPointF ap(lmo->getAbsPos());
  4354 			QPointF to(x, y);
  4355 			if (ap != to)
  4356 			{
  4357 				QString ps=qpointFToString(ap);
  4358 				QString s=getSelectString(seli);
  4359 				saveState(
  4360 					s, "move "+ps, 
  4361 					s, "move "+qpointFToString(to), 
  4362 					QString("Move %1 to %2").arg(getObjectName(seli)).arg(ps));
  4363 				lmo->move(x,y);
  4364 				reposition();
  4365 				emitSelectionChanged();
  4366 			}
  4367 		}
  4368 	}
  4369 }
  4370 
  4371 void VymModel::moveRel (const double &x, const double &y)	
  4372 {
  4373 	int i=x; i=y;
  4374 	MapItem *seli = (MapItem*)getSelectedItem();
  4375 	if (seli && (seli->isBranchLikeType() || seli->getType()==TreeItem::Image))
  4376 	{
  4377 		LinkableMapObj *lmo=seli->getLMO();
  4378 		if (lmo)
  4379 		{
  4380 			QPointF rp(lmo->getRelPos());
  4381 			QPointF to(x, y);
  4382 			if (rp != to)
  4383 			{
  4384 				QString ps=qpointFToString (lmo->getRelPos());
  4385 				QString s=getSelectString(seli);
  4386 				saveState(
  4387 					s, "moveRel "+ps, 
  4388 					s, "moveRel "+qpointFToString(to), 
  4389 					QString("Move %1 to relative position %2").arg(getObjectName(seli)).arg(ps));
  4390 				((OrnamentedObj*)lmo)->move2RelPos (x,y);
  4391 				reposition();
  4392 				lmo->updateLinkGeometry();
  4393 				emitSelectionChanged();
  4394 			}
  4395 		}	
  4396 	}
  4397 }
  4398 
  4399 
  4400 void VymModel::animate()
  4401 {
  4402 	animationTimer->stop();
  4403 	BranchObj *bo;
  4404 	int i=0;
  4405 	while (i<animObjList.size() )
  4406 	{
  4407 		bo=(BranchObj*)animObjList.at(i);
  4408 		if (!bo->animate())
  4409 		{
  4410 			if (i>=0) 
  4411 			{	
  4412 				animObjList.removeAt(i);
  4413 				i--;
  4414 			}
  4415 		}
  4416 		bo->reposition();
  4417 		i++;
  4418 	} 
  4419 	QItemSelection sel=selModel->selection();
  4420 	emit (selectionChanged(sel,sel));
  4421 
  4422 	mapScene->update();
  4423 	if (!animObjList.isEmpty()) animationTimer->start();
  4424 }
  4425 
  4426 
  4427 void VymModel::startAnimation(BranchObj *bo, const QPointF &start, const QPointF &dest)
  4428 {
  4429 	if (bo && bo->getTreeItem()->depth()>0) 
  4430 	{
  4431 		AnimPoint ap;
  4432 		ap.setStart (start);
  4433 		ap.setDest  (dest);
  4434 		ap.setTicks (animationTicks);
  4435 		ap.setAnimated (true);
  4436 		bo->setAnimation (ap);
  4437 		animObjList.append( bo );
  4438 		animationTimer->setSingleShot (true);
  4439 		animationTimer->start(animationInterval);
  4440 	}
  4441 }
  4442 
  4443 void VymModel::stopAnimation (MapObj *mo)
  4444 {
  4445 	int i=animObjList.indexOf(mo);
  4446     if (i>=0)
  4447 		animObjList.removeAt (i);
  4448 }
  4449 
  4450 void VymModel::sendSelection()
  4451 {
  4452 	if (netstate!=Server) return;
  4453 	sendData (QString("select (\"%1\")").arg(getSelectString()) );
  4454 }
  4455 
  4456 void VymModel::newServer()
  4457 {
  4458 	port=54321;
  4459 	sendCounter=0;
  4460     tcpServer = new QTcpServer(this);
  4461     if (!tcpServer->listen(QHostAddress::Any,port)) {
  4462         QMessageBox::critical(NULL, "vym server",
  4463                               QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
  4464         //FIXME-3 needed? we are no widget any longer... close();
  4465         return;
  4466     }
  4467 	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
  4468 	netstate=Server;
  4469 	cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
  4470 }
  4471 
  4472 void VymModel::connectToServer()
  4473 {
  4474 	port=54321;
  4475 	server="salam.suse.de";
  4476 	server="localhost";
  4477 	clientSocket = new QTcpSocket (this);
  4478 	clientSocket->abort();
  4479     clientSocket->connectToHost(server ,port);
  4480 	connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
  4481     connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
  4482             this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
  4483 	netstate=Client;		
  4484 	cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
  4485 
  4486 	
  4487 }
  4488 
  4489 void VymModel::newClient()
  4490 {
  4491     QTcpSocket *newClient = tcpServer->nextPendingConnection();
  4492     connect(newClient, SIGNAL(disconnected()),
  4493             newClient, SLOT(deleteLater()));
  4494 
  4495 	cout <<"ME::newClient  at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
  4496 
  4497 	clientList.append (newClient);
  4498 }
  4499 
  4500 
  4501 void VymModel::sendData(const QString &s)
  4502 {
  4503 	if (clientList.size()==0) return;
  4504 
  4505 	// Create bytearray to send
  4506 	QByteArray block;
  4507     QDataStream out(&block, QIODevice::WriteOnly);
  4508     out.setVersion(QDataStream::Qt_4_0);
  4509 
  4510 	// Reserve some space for blocksize
  4511     out << (quint16)0;
  4512 
  4513 	// Write sendCounter
  4514     out << sendCounter++;
  4515 
  4516 	// Write data
  4517     out << s;
  4518 
  4519 	// Go back and write blocksize so far
  4520     out.device()->seek(0);
  4521     quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
  4522 	out << bs;
  4523 
  4524 	if (debug)
  4525 		cout << "ME::sendData  bs="<<bs<<"  counter="<<sendCounter<<"  s="<<qPrintable(s)<<endl;
  4526 
  4527 	for (int i=0; i<clientList.size(); ++i)
  4528 	{
  4529 		//cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
  4530 		clientList.at(i)->write (block);
  4531 	}
  4532 }
  4533 
  4534 void VymModel::readData ()
  4535 {
  4536 	while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
  4537 	{
  4538 		if (debug)
  4539 			cout <<"readData  bytesAvail="<<clientSocket->bytesAvailable();
  4540 		quint16 recCounter;
  4541 		quint16 blockSize;
  4542 
  4543 		QDataStream in(clientSocket);
  4544 		in.setVersion(QDataStream::Qt_4_0);
  4545 
  4546 		in >> blockSize;
  4547 		in >> recCounter;
  4548 		
  4549 		QString t;
  4550 		in >>t;
  4551 		if (debug)
  4552 			cout << "  t="<<qPrintable (t)<<endl;
  4553 		parseAtom (t);
  4554 	}
  4555 	return;
  4556 }
  4557 
  4558 void VymModel::displayNetworkError(QAbstractSocket::SocketError socketError)
  4559 {
  4560     switch (socketError) {
  4561     case QAbstractSocket::RemoteHostClosedError:
  4562         break;
  4563     case QAbstractSocket::HostNotFoundError:
  4564         QMessageBox::information(NULL, vymName +" Network client",
  4565                                  "The host was not found. Please check the "
  4566                                     "host name and port settings.");
  4567         break;
  4568     case QAbstractSocket::ConnectionRefusedError:
  4569         QMessageBox::information(NULL, vymName + " Network client",
  4570                                  "The connection was refused by the peer. "
  4571                                     "Make sure the fortune server is running, "
  4572                                     "and check that the host name and port "
  4573                                     "settings are correct.");
  4574         break;
  4575     default:
  4576         QMessageBox::information(NULL, vymName + " Network client",
  4577                                  QString("The following error occurred: %1.")
  4578                                  .arg(clientSocket->errorString()));
  4579     }
  4580 }
  4581 
  4582 /* FIXME-3 Playing with DBUS...
  4583 QDBusVariant VymModel::query (const QString &query)
  4584 {
  4585 	TreeItem *selti=getSelectedItem();
  4586 	if (selti)
  4587 		return QDBusVariant (selti->getHeading());
  4588 	else
  4589 		return QDBusVariant ("Nothing selected.");
  4590 }
  4591 */
  4592 
  4593 void VymModel::testslot()	//FIXME-3
  4594 {
  4595 	cout << "VM::testslot called\n";
  4596 }
  4597 
  4598 void VymModel::selectMapSelectionColor()
  4599 {
  4600 	QColor col = QColorDialog::getColor( defLinkColor, NULL);
  4601 	setSelectionColor (col);
  4602 }
  4603 
  4604 void VymModel::setSelectionColorInt (QColor col)
  4605 {
  4606 	if ( !col.isValid() ) return;
  4607 	saveState (
  4608 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4609 		QString("setSelectionColor (%1)").arg(col.name()),
  4610 		QString("Set color of selection box to %1").arg(col.name())
  4611 	);
  4612 
  4613 	mapEditor->setSelectionColor (col);
  4614 }
  4615 
  4616 void VymModel::emitSelectionChanged(const QItemSelection &newsel)
  4617 {
  4618 	emit (selectionChanged(newsel,newsel));	// needed e.g. to update geometry in editor
  4619 	emitShowSelection();
  4620 	sendSelection();
  4621 }
  4622 
  4623 void VymModel::emitSelectionChanged()
  4624 {
  4625 	QItemSelection newsel=selModel->selection();
  4626 	emitSelectionChanged (newsel);
  4627 }
  4628 
  4629 void VymModel::setSelectionColor(QColor col)
  4630 {
  4631 	if ( !col.isValid() ) return;
  4632 	saveState (
  4633 		QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
  4634 		QString("setSelectionColor (%1)").arg(col.name()),
  4635 		QString("Set color of selection box to %1").arg(col.name())
  4636 	);
  4637 	setSelectionColorInt (col);
  4638 }
  4639 
  4640 QColor VymModel::getSelectionColor()
  4641 {
  4642 	return mapEditor->getSelectionColor();
  4643 }
  4644 
  4645 void VymModel::setHideTmpMode (TreeItem::HideTmpMode mode)
  4646 {
  4647 	hidemode=mode;
  4648 	for (int i=0;i<rootItem->childCount();i++)
  4649 		rootItem->child(i)->setHideTmp (mode);	
  4650 	reposition();
  4651 	// FIXME-3 needed? scene()->update();
  4652 }
  4653 
  4654 //////////////////////////////////////////////
  4655 // Selection related
  4656 //////////////////////////////////////////////
  4657 
  4658 void VymModel::setSelectionModel (QItemSelectionModel *sm)
  4659 {
  4660 	selModel=sm;
  4661 }
  4662 
  4663 QItemSelectionModel* VymModel::getSelectionModel()
  4664 {
  4665 	return selModel;
  4666 }
  4667 
  4668 void VymModel::setSelectionBlocked (bool b)
  4669 {
  4670 	selectionBlocked=b;
  4671 }
  4672 
  4673 bool VymModel::isSelectionBlocked()
  4674 {
  4675 	return selectionBlocked;
  4676 }
  4677 
  4678 bool VymModel::select ()
  4679 {
  4680 	return select (selModel->selectedIndexes().first());	// TODO no multiselections yet
  4681 }
  4682 
  4683 bool VymModel::select (const QString &s)
  4684 {
  4685 	if (s.isEmpty())
  4686 	{
  4687 		unselect();
  4688 		return true;
  4689 	}
  4690 	TreeItem *ti=findBySelectString(s);
  4691 	if (ti) return select (index(ti));
  4692 	return false;
  4693 }
  4694 
  4695 bool VymModel::select (LinkableMapObj *lmo)
  4696 {
  4697 	QItemSelection oldsel=selModel->selection();
  4698 
  4699 	if (lmo)
  4700 		return select (index (lmo->getTreeItem()) );
  4701 	else	
  4702 		return false;
  4703 }
  4704 
  4705 bool VymModel::select (TreeItem *ti)
  4706 {
  4707 	if (ti) return select (index(ti));
  4708 	return false;
  4709 }
  4710 
  4711 bool VymModel::select (const QModelIndex &index)
  4712 {
  4713 	if (index.isValid() )
  4714 	{
  4715 		selModel->select (index,QItemSelectionModel::ClearAndSelect  );
  4716 		BranchItem *bi=getSelectedBranch();
  4717 		if (bi) bi->setLastSelectedBranch();
  4718 		return true;
  4719 	}
  4720 	return false;
  4721 }
  4722 
  4723 void VymModel::unselect()
  4724 {
  4725 	lastSelectString=getSelectString();
  4726 	selModel->clearSelection();
  4727 }	
  4728 
  4729 bool VymModel::reselect()
  4730 {
  4731 	return select (lastSelectString);
  4732 }	
  4733 
  4734 void VymModel::emitShowSelection()	
  4735 {
  4736 	if (!blockReposition)
  4737 		emit (showSelection() );
  4738 }
  4739 
  4740 void VymModel::emitNoteHasChanged (TreeItem *ti)
  4741 {
  4742 	QModelIndex ix=index(ti);
  4743 	emit (noteHasChanged (ix) );
  4744 }
  4745 
  4746 void VymModel::emitDataHasChanged (TreeItem *ti)
  4747 {
  4748 	QModelIndex ix=index(ti);
  4749 	emit (dataChanged (ix,ix) );
  4750 }
  4751 
  4752 
  4753 bool VymModel::selectFirstBranch()
  4754 {
  4755 	TreeItem *ti=getSelectedBranch();
  4756 	if (ti)
  4757 	{
  4758 		TreeItem *par=ti->parent();
  4759 		if (par) 
  4760 		{
  4761 			TreeItem *ti2=par->getFirstBranch();
  4762 			if (ti2) return  select(ti2);
  4763 		}
  4764 	}		
  4765 	return false;
  4766 }
  4767 
  4768 bool VymModel::selectLastBranch()
  4769 {
  4770 	TreeItem *ti=getSelectedBranch();
  4771 	if (ti)
  4772 	{
  4773 		TreeItem *par=ti->parent();
  4774 		if (par) 
  4775 		{
  4776 			TreeItem *ti2=par->getLastBranch();
  4777 			if (ti2) return select(ti2);
  4778 		}
  4779 	}		
  4780 	return false;
  4781 }
  4782 
  4783 bool VymModel::selectLastSelectedBranch()
  4784 {
  4785 	BranchItem *bi=getSelectedBranch();
  4786 	if (bi)
  4787 	{
  4788 		bi=bi->getLastSelectedBranch();
  4789 		if (bi) return select (bi);
  4790 	}		
  4791 	return false;
  4792 }
  4793 
  4794 bool VymModel::selectParent()
  4795 {
  4796 	TreeItem *ti=getSelectedItem();
  4797 	TreeItem *par;
  4798 	if (ti)
  4799 	{
  4800 		par=ti->parent();
  4801 		if (par) 
  4802 			return select(par);
  4803 	}		
  4804 	return false;
  4805 }
  4806 
  4807 TreeItem::Type VymModel::selectionType()
  4808 {
  4809 	QModelIndexList list=selModel->selectedIndexes();
  4810 	if (list.isEmpty()) return TreeItem::Undefined;	
  4811 	TreeItem *ti = getItem (list.first() );
  4812 	return ti->getType();
  4813 
  4814 }
  4815 
  4816 LinkableMapObj* VymModel::getSelectedLMO()
  4817 {
  4818 	QModelIndexList list=selModel->selectedIndexes();
  4819 	if (!list.isEmpty() )
  4820 	{
  4821 		TreeItem *ti = getItem (list.first() );
  4822 		TreeItem::Type type=ti->getType();
  4823 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter || type==TreeItem::Image)
  4824 			return ((MapItem*)ti)->getLMO();
  4825 	}
  4826 	return NULL;
  4827 }
  4828 
  4829 BranchObj* VymModel::getSelectedBranchObj()	// FIXME-3 this should not be needed in the end!!!
  4830 {
  4831 	TreeItem *ti = getSelectedBranch();
  4832 	if (ti)
  4833 		return (BranchObj*)(  ((MapItem*)ti)->getLMO());
  4834 	else	
  4835 		return NULL;
  4836 }
  4837 
  4838 BranchItem* VymModel::getSelectedBranch()
  4839 {
  4840 	QModelIndexList list=selModel->selectedIndexes();
  4841 	if (!list.isEmpty() )
  4842 	{
  4843 		TreeItem *ti = getItem (list.first() );
  4844 		TreeItem::Type type=ti->getType();
  4845 		if (type ==TreeItem::Branch || type==TreeItem::MapCenter)
  4846 			return (BranchItem*)ti;
  4847 	}
  4848 	return NULL;
  4849 }
  4850 
  4851 ImageItem* VymModel::getSelectedImage()
  4852 {
  4853 	QModelIndexList list=selModel->selectedIndexes();
  4854 	if (!list.isEmpty())
  4855 	{
  4856 		TreeItem *ti=getItem (list.first());
  4857 		if (ti && ti->getType()==TreeItem::Image)
  4858 			return (ImageItem*)ti;
  4859 	}
  4860 	return NULL;
  4861 }
  4862 
  4863 AttributeItem* VymModel::getSelectedAttribute()	
  4864 {
  4865 	QModelIndexList list=selModel->selectedIndexes();
  4866 	if (!list.isEmpty() )
  4867 	{
  4868 		TreeItem *ti = getItem (list.first() );
  4869 		TreeItem::Type type=ti->getType();
  4870 		if (type ==TreeItem::Attribute)
  4871 			return (AttributeItem*)ti;
  4872 	} 
  4873 	return NULL;
  4874 }
  4875 
  4876 TreeItem* VymModel::getSelectedItem()	
  4877 {
  4878 	QModelIndexList list=selModel->selectedIndexes();
  4879 	if (!list.isEmpty() )
  4880 		return getItem (list.first() );
  4881 	else	
  4882 		return NULL;
  4883 }
  4884 
  4885 QModelIndex VymModel::getSelectedIndex()
  4886 {
  4887 	QModelIndexList list=selModel->selectedIndexes();
  4888 	if (list.isEmpty() )
  4889 		return QModelIndex();
  4890 	else
  4891 		return list.first();
  4892 }
  4893 
  4894 QString VymModel::getSelectString ()
  4895 {
  4896 	return getSelectString (getSelectedItem());
  4897 }
  4898 
  4899 QString VymModel::getSelectString (LinkableMapObj *lmo)	// only for convenience. Used in MapEditor
  4900 {
  4901 	if (!lmo) return QString();
  4902 	return getSelectString (lmo->getTreeItem() );
  4903 }
  4904 
  4905 QString VymModel::getSelectString (TreeItem *ti) 
  4906 {
  4907 	QString s;
  4908 	if (!ti) return s;
  4909 	switch (ti->getType())
  4910 	{
  4911 		case TreeItem::MapCenter: s="mc:"; break;
  4912 		case TreeItem::Branch: s="bo:";break;
  4913 		case TreeItem::Image: s="fi:";break;
  4914 		case TreeItem::Attribute: s="ai:";break;
  4915 		case TreeItem::XLink: s="xl:";break;
  4916 		default:
  4917 			s="unknown type in VymModel::getSelectString()";
  4918 			break;
  4919 	}
  4920 	s=  s + QString("%1").arg(ti->num());
  4921 	if (ti->depth() >0)
  4922 		// call myself recursively
  4923 		s= getSelectString(ti->parent()) +","+s;
  4924 			
  4925 	return s;
  4926 }
  4927