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