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