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