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