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