mapeditor.cpp
author insilmaril
Mon, 16 Oct 2006 12:42:54 +0000
changeset 392 18f824bd3070
parent 390 0e1aeb21cb78
child 393 053b8645e3e9
permissions -rw-r--r--
Code simplifications
     1 #include "mapeditor.h"
     2 
     3 #include <q3dragobject.h>
     4 #include <q3urloperator.h>
     5 #include <q3networkprotocol.h>
     6 #include <q3paintdevicemetrics.h>
     7 #include <q3filedialog.h>
     8 
     9 #include <iostream>
    10 #include <cstdlib>
    11 #include <typeinfo>
    12 
    13 #include "version.h"
    14 
    15 #include "api.h"
    16 #include "editxlinkdialog.h"
    17 #include "exports.h"
    18 #include "extrainfodialog.h"
    19 #include "file.h"
    20 #include "linkablemapobj.h"
    21 #include "mainwindow.h"
    22 #include "misc.h"
    23 #include "texteditor.h"
    24 #include "warningdialog.h"
    25 #include "xml.h"
    26 
    27 
    28 extern TextEditor *textEditor;
    29 extern int statusbarTime;
    30 extern Main *mainWindow;
    31 extern QString tmpVymDir;
    32 extern QString clipboardDir;
    33 extern bool clipboardEmpty;
    34 extern FlagRowObj *standardFlagsDefault;
    35 
    36 extern QMenu* branchContextMenu;
    37 extern QMenu* branchAddContextMenu;
    38 extern QMenu* branchRemoveContextMenu;
    39 extern QMenu* branchLinksContextMenu;
    40 extern QMenu* branchXLinksContextMenuEdit;
    41 extern QMenu* branchXLinksContextMenuFollow;
    42 extern QMenu* floatimageContextMenu;
    43 extern QMenu* saveImageFormatMenu;
    44 extern QMenu* canvasContextMenu;
    45 extern QMenu* lastMapsMenu;
    46 extern QMenu* importMenu;
    47 extern QMenu* exportMenu;
    48 
    49 
    50 extern Settings settings;
    51 extern ImageIO imageIO;
    52 
    53 extern QString iconPath;
    54 extern QDir vymBaseDir;
    55 extern QDir lastImageDir;
    56 
    57 int MapEditor::mapNum=0;	// make instance
    58 
    59 ///////////////////////////////////////////////////////////////////////
    60 ///////////////////////////////////////////////////////////////////////
    61 MapEditor::MapEditor(
    62 	QWidget* parent, const char* name, Qt::WFlags f) :
    63   Q3CanvasView(parent,name,f), urlOperator(0), imageBuffer(0)
    64 {
    65 	//cout << "Constructor ME "<<this<<endl;
    66 	mapNum++;
    67 
    68     viewport()->setAcceptDrops(true);
    69 
    70     mapCanvas = new Q3Canvas(width(),height());
    71 	mapCanvas->setAdvancePeriod(30);
    72 	mapCanvas->setBackgroundColor (Qt::white);
    73 
    74     setCanvas (mapCanvas);
    75 	
    76 	// Always show scroll bars (automatic would flicker sometimes)
    77 	setVScrollBarMode ( Q3ScrollView::AlwaysOn );
    78 	setHScrollBarMode ( Q3ScrollView::AlwaysOn );
    79 
    80     mapCenter = new MapCenterObj(mapCanvas);
    81     mapCenter->setVisibility (true);
    82 	mapCenter->setMapEditor (this);
    83 	mapCenter->setHeading (tr("New Map","Heading of mapcenter in new map"));
    84 	mapCenter->move(mapCanvas->width()/2-mapCenter->width()/2,mapCanvas->height()/2-mapCenter->height()/2);
    85 
    86     printer=NULL;
    87 
    88     actColor=Qt::black; setColor (actColor);
    89 	defLinkColor=QColor (0,0,255);
    90 	defXLinkColor=QColor (180,180,180);
    91 	linkcolorhint=DefaultColor;
    92 	linkstyle=StylePolyParabel;
    93 
    94 	// Create bitmap cursors, platform dependant
    95 	#if defined(Q_OS_MACX)
    96 		handOpenCursor=QCursor ( QPixmap(iconPath+"cursorhandopen16.png"),1,1 );		
    97 		pickColorCursor=QCursor ( QPixmap (iconPath+"cursorcolorpicker16.png"), 1,15 ); 
    98 	#else
    99 		handOpenCursor=QCursor (QPixmap(iconPath+"cursorhandopen.png"),1,1);		
   100 		pickColorCursor=QCursor ( QPixmap(iconPath+"cursorcolorpicker.png"), 5,27 ); 
   101 	#endif
   102 
   103 	pickingColor=false;
   104 	drawingLink=false;
   105 	copyingObj=false;
   106 
   107     editingBO=NULL;
   108     selection=NULL;
   109     selectionLast=NULL;
   110     movingObj=NULL;
   111 
   112 	xelection.setMapCenter (mapCenter);
   113 
   114 	defXLinkWidth=1;
   115 	defXLinkColor=QColor (230,230,230);
   116 
   117     mapChanged=false;
   118 	mapDefault=true;
   119 	mapUnsaved=false;
   120 	
   121 	zipped=true;
   122 	filePath="";
   123 	fileName=tr("unnamed");
   124 	mapName="";
   125 
   126 	stepsTotal=settings.readNumEntry("/mapeditor/stepsTotal",50);
   127 	undoSet.setEntry ("/history/stepsTotal",QString::number(stepsTotal));
   128 	
   129 	// Initialize find routine
   130 	itFind=NULL;				
   131 	EOFind=false;
   132 
   133 	printFrame=true;
   134 	printFooter=true;
   135 
   136 	blockReposition=false;
   137 	blockSaveState=false;
   138 
   139 	hidemode=HideNone;
   140 
   141 	// Create temporary files
   142 	makeTmpDirs();
   143 
   144 	// Initially set movingCentre
   145 	updateViewCenter();
   146 
   147 	mapCenter->reposition();	//	for positioning heading
   148 
   149 	// Initialize history window;
   150 	historyWindow.setME(this);
   151 	historyWindow.setStepsTotal(stepsTotal);
   152 	historyWindow.update (undoSet);
   153 }
   154 
   155 MapEditor::~MapEditor()
   156 {
   157   if (imageBuffer) delete imageBuffer;
   158   if (urlOperator) {
   159     urlOperator->stop();
   160     delete urlOperator;
   161   }
   162 
   163 	//cout <<"Destructor MapEditor\n";
   164 }
   165 
   166 QColor MapEditor::getColor()
   167 {
   168     return actColor;
   169 }
   170 
   171 QColor MapEditor::getBackgroundColor()
   172 {
   173     return mapCanvas->backgroundColor();
   174 }
   175 
   176 MapCenterObj* MapEditor::getMapCenter()
   177 {
   178     return mapCenter;
   179 }
   180 
   181 Q3Canvas* MapEditor::getCanvas()
   182 {
   183     return mapCanvas;
   184 }
   185 
   186 void MapEditor::adjustCanvasSize()
   187 {
   188 	// To adjust the canvas to map, viewport size and position, we have to
   189 	// do some coordinate magic...
   190 	//
   191 	// Get rectangle of (scroll-)view. 
   192 	// We want to be in canvas coords, so
   193 	// we map. Important if view is zoomed...
   194 	QRect view = inverseWorldMatrix().mapRect( QRect( contentsX(), contentsY(),
   195 												visibleWidth(), visibleHeight()) );	
   196 												
   197 	// Now we need the bounding box of view AND map to calc the correct canvas size.
   198 	// Why? Because if the map itself is moved out of view, the view has to be enlarged
   199 	// to avoid jumping aroung...
   200 	QRect map=mapCenter->getTotalBBox();
   201 
   202 	// right edge - left edge
   203 	int cw= max(map.x() + map.width(),  view.x() + view.width())  - min(map.x(), view.x());
   204 	int ch= max(map.y() + map.height(), view.y() + view.height()) - min(map.y(), view.y());
   205 
   206 
   207 	if ( (cw!=mapCanvas->width()) || (ch!=mapCanvas->height()) ||
   208 		!mapCanvas->onCanvas (map.topLeft()) || !mapCanvas->onCanvas (map.bottomRight())
   209 	)	
   210 	{	
   211 		// move the map on canvas (in order to not move it on screen) this is neccessary
   212 		// a) if topleft corner of canvas is left or above topleft corner of view and also left of
   213 		//    above topleft corner of map. E.g. if map is completly inside view, but it would be possible 
   214 		//    to scroll to an empty area of canvas to the left.
   215 		// b) if topleft corner of map left of or above topleft of canvas
   216 		int dx=0;
   217 		int dy=0;
   218 
   219 		if (cw > mapCanvas->width() )
   220 		{
   221 			if (map.x()<0) dx=-map.x();	
   222 		}
   223 		if (cw <  mapCanvas->width() )
   224 			dx=-min (view.x(),map.x());
   225 		if (ch > mapCanvas->height() )
   226 		{
   227 			if (map.y()<0) dy=-map.y();	
   228 		}
   229 		if (ch <  mapCanvas->height() )
   230 		{
   231 			dy=-min (view.y(),map.y());
   232 		}
   233 		// We really have to resize now. Let's go...
   234 		mapCanvas->resize (cw,ch);
   235 		if ( (dx!=0) || (dy!=0) ) 
   236 		{
   237 			mapCenter->moveAllBy(dx,dy);
   238 			mapCenter->reposition();
   239 //			mapCenter->positionBBox();	// To move float
   240 
   241 			// scroll the view (in order to not move map on screen)
   242 			scrollBy (dx,dy);
   243 		}	
   244 	}
   245 }
   246 
   247 bool MapEditor::isRepositionBlocked()
   248 {
   249 	return blockReposition;
   250 }
   251 
   252 QString MapEditor::getName (LinkableMapObj *lmo)
   253 {
   254 	QString s;
   255 	if (!lmo) return QString("Error: NULL has no name!");
   256 
   257 	if ((typeid(*lmo) == typeid(BranchObj) ||
   258 				      typeid(*lmo) == typeid(MapCenterObj))) 
   259 	{
   260 		
   261 		s=(((BranchObj*)lmo)->getHeading());
   262 		if (s=="") s="unnamed";
   263 		return QString("branch (%1)").arg(s);
   264 		//return QString("branch (<font color=\"#0000ff\">%1</font>)").arg(s);
   265 	}	
   266 	if ((typeid(*lmo) == typeid(FloatImageObj) ))
   267 		return QString ("floatimage [%1]").arg(((FloatImageObj*)lmo)->getOriginalFilename());
   268 		//return QString ("floatimage [<font color=\"#0000ff\">%1</font>]").arg(((FloatImageObj*)lmo)->getOriginalFilename());
   269 	return QString("Unknown type has no name!");
   270 }
   271 
   272 void MapEditor::makeTmpDirs()
   273 {
   274 	// Create unique temporary directories
   275 	tmpMapDir=QDir::convertSeparators (tmpVymDir+QString("/mapeditor-%1").arg(mapNum));
   276 	histPath=QDir::convertSeparators (tmpMapDir+"/history");
   277 	QDir d;
   278 	d.mkdir (tmpMapDir);
   279 }
   280 
   281 QString MapEditor::saveToDir(const QString &tmpdir, const QString &prefix, bool writeflags, const QPoint &offset, LinkableMapObj *saveSel)
   282 {
   283 	// tmpdir		temporary directory to which data will be written
   284 	// prefix		mapname, which will be appended to images etc.
   285 	// writeflags	Only write flags for "real" save of map, not undo
   286 	// offset		offset of bbox of whole map in canvas. 
   287 	//				Needed for XML export
   288 	
   289 	// Save Header
   290 	QString ls;
   291 	switch (linkstyle)
   292 	{
   293 		case StyleLine: 
   294 			ls="StyleLine";
   295 			break;
   296 		case StyleParabel:
   297 			ls="StyleParabel";
   298 			break;
   299 		case StylePolyLine:	
   300 			ls="StylePolyLine";
   301 			break;
   302 		default:
   303 			ls="StylePolyParabel";
   304 			break;
   305 	}	
   306 
   307 	QString s="<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE vymmap>\n";
   308 	QString colhint="";
   309 	if (linkcolorhint==HeadingColor) 
   310 		colhint=attribut("linkColorHint","HeadingColor");
   311 
   312 	QString mapAttr=attribut("version",__VYM_VERSION);
   313 	if (!saveSel)
   314 		mapAttr+= attribut("author",mapCenter->getAuthor()) +
   315 				  attribut("comment",mapCenter->getComment()) +
   316 			      attribut("date",mapCenter->getDate()) +
   317 		          attribut("backgroundColor", mapCanvas->backgroundColor().name() ) +
   318 		          attribut("linkStyle", ls ) +
   319 		          attribut("linkColor", defLinkColor.name() ) +
   320 		          attribut("defXLinkColor", defXLinkColor.name() ) +
   321 		          attribut("defXLinkWidth", QString().setNum(defXLinkWidth,10) ) +
   322 		          colhint; 
   323 	s+=beginElement("vymmap",mapAttr);
   324 	incIndent();
   325 
   326 	// Find the used flags while traversing the tree
   327 	standardFlagsDefault->resetUsedCounter();
   328 	
   329 	// Reset the counters before saving
   330 	FloatImageObj (mapCanvas).resetSaveCounter();
   331 
   332 	// Build xml recursivly
   333 	if (!saveSel)
   334 		// Save complete map, if saveSel not set
   335 		s+=mapCenter->saveToDir(tmpdir,prefix,writeflags,offset);
   336 	else
   337 	{
   338 		if ( typeid(*saveSel) == typeid(BranchObj) )
   339 			// Save Subtree
   340 			s+=((BranchObj*)(saveSel))->saveToDir(tmpdir,prefix,offset);
   341 		else if ( typeid(*saveSel) == typeid(FloatImageObj) )
   342 			// Save image
   343 			s+=((FloatImageObj*)(saveSel))->saveToDir(tmpdir,prefix);
   344 			
   345 		else if (selection && typeid(*selection)==typeid(BranchObj))
   346 			// Save selected branch is saved from mainwindow		//FIXME maybe use "subtree" above?
   347 			s+=((BranchObj*)selection)->saveToDir(tmpdir,prefix,offset);
   348 	}
   349 
   350 	// Save local settings
   351 	s+=settings.getXMLData (destPath);
   352 
   353 	// Save selection
   354 	if (selection && !saveSel ) 
   355 		s+=valueElement("select",selection->getSelectString());
   356 
   357 	decIndent();
   358 	s+=endElement("vymmap");
   359 
   360 	if (writeflags)
   361 		standardFlagsDefault->saveToDir (tmpdir+"/flags/","",writeflags);
   362 	return s;
   363 }
   364 
   365 void MapEditor::saveStateComplete(const QString &comment)
   366 {
   367 	// Save complete map, Undo will replace whole map
   368 	saveState (CompleteMap,
   369 		"", "",
   370 		"", "", 
   371 		comment, 
   372 		mapCenter);
   373 }
   374 
   375 void MapEditor::saveStatePart(LinkableMapObj *undoSel, const QString &comment)
   376 {
   377 	// save the selected part of the map, Undo will replace part of map 
   378 	QString undoSelection="";
   379 	if (undoSel) undoSelection=undoSel->getSelectString();
   380 
   381 	saveState (PartOfMap,
   382 		undoSelection, "",
   383 		"", "", 
   384 		comment, 
   385 		undoSel);
   386 }
   387 
   388 void MapEditor::saveStateConstSelection(const QString &uc, const QString &rc, const QString &comment)
   389 {
   390 	// selection does not change during action,
   391 	// so just save commands for undo and redo
   392 	// and use current selection
   393 
   394 	QString sel;
   395 	if (selection) sel=selection->getSelectString();
   396 
   397 	saveState (UndoCommand,
   398 		sel, uc,
   399 		sel, rc, 
   400 		comment, 
   401 		NULL);
   402 }
   403 
   404 /* FIXME not used
   405 void MapEditor::saveStateComData(LinkableMapObj *undoSel, const QString &uc, LinkableMapObj *redoSel, const QString &rc, const QString &comment, LinkableMapObj *saveSel) 
   406 {
   407 	QString redoSelection="";
   408 	if (redoSel) redoSelection=redoSel->getSelectString();
   409 	QString undoSelection="";
   410 	if (undoSel) undoSelection=undoSel->getSelectString();
   411 
   412 	saveState (UndoCommand,
   413 		undoSelection, uc,
   414 		redoSelection, "FIXME-redoCom",	//FIXME
   415 		comment, 
   416 		saveSel);
   417 }
   418 */
   419 
   420 void MapEditor::saveState(LinkableMapObj *undoSel, const QString &uc, LinkableMapObj *redoSel, const QString &rc, const QString &comment) 
   421 {
   422 	// "Normal" savestate: save commands, selections and comment
   423 	// so just save commands for undo and redo
   424 	// and use current selection
   425 
   426 	QString redoSelection="";
   427 	if (redoSel) redoSelection=redoSel->getSelectString();
   428 	QString undoSelection="";
   429 	if (undoSel) undoSelection=undoSel->getSelectString();
   430 
   431 	saveState (UndoCommand,
   432 		undoSelection, uc,
   433 		redoSelection, rc, 
   434 		comment, 
   435 		NULL);
   436 }
   437 
   438 void MapEditor::saveState(const QString &undoSel, const QString &uc, const QString &redoSel, const QString &rc, const QString &comment) 
   439 {
   440 	// "Normal" savestate: save commands, selections and comment
   441 	// so just save commands for undo and redo
   442 	// and use current selection
   443 	saveState (UndoCommand,
   444 		undoSel, uc,
   445 		redoSel, rc, 
   446 		comment, 
   447 		NULL);
   448 }
   449 
   450 		
   451 void MapEditor::saveState(const SaveMode &savemode, const QString &undoSelection, const QString &undoCom, const QString &redoSelection, const QString &redoCom, const QString &comment, LinkableMapObj *saveSel)
   452 {
   453 	// Main saveState
   454 
   455 	if (blockSaveState) return;
   456 
   457 	/* TODO remove after testing
   458 	*/
   459 	cout << "ME::saveState()  "<<endl;
   460 	
   461 	setChanged();
   462 
   463 	int undosAvail=undoSet.readNumEntry ("/history/undosAvail",0);
   464 	int redosAvail=undoSet.readNumEntry ("/history/redosAvail",0);
   465 	int curStep=undoSet.readNumEntry ("/history/curStep",0);
   466 	// Find out current undo directory
   467 	if (undosAvail<stepsTotal) undosAvail++;
   468 	curStep++;
   469 	if (curStep>stepsTotal) curStep=1;
   470 	
   471 	QString backupXML;
   472 	QString bakMapName=QDir::convertSeparators (QString("history-%1").arg(curStep));
   473 	QString bakMapDir=QDir::convertSeparators (tmpMapDir +"/"+bakMapName);
   474 	QString bakMapPath=QDir::convertSeparators(bakMapDir+"/map.xml");
   475 
   476 	// Create bakMapDir if not available
   477 	QDir d(bakMapDir);
   478 	if (!d.exists()) 
   479 		makeSubDirs (bakMapDir);
   480 
   481 	// Save depending on how much needs to be saved	
   482 	if (!saveSel)
   483 		backupXML="";
   484 	else 
   485 		backupXML=saveToDir (bakMapDir,mapName+"-",false, QPoint (),saveSel);
   486 		
   487 	QString undoCommand="";
   488 	if (savemode==UndoCommand)
   489 	{
   490 		undoCommand=undoCom;
   491 	}	
   492 	else if (savemode==PartOfMap )
   493 	{
   494 		undoCommand="undoPart (\""+ undoSelection+"\",\""+bakMapPath+"\")";
   495 	} else
   496 	{
   497 		undoCommand="undoMap (\""+bakMapPath+"\")";
   498 	}
   499 	if (!backupXML.isEmpty())
   500 		// Write XML Data to disk
   501 		saveStringToDisk (QString(bakMapPath),backupXML);
   502 
   503 	// We would have to save all actions in a tree, to keep track of 
   504 	// possible redos after a action. Too complex, forget about redos.
   505 	redosAvail=0;
   506 
   507 	// Write the current state to disk
   508 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
   509 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
   510 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
   511 	undoSet.setEntry (QString("/history/step-%1/undoCommand").arg(curStep),undoCommand);
   512 	undoSet.setEntry (QString("/history/step-%1/undoSelection").arg(curStep),undoSelection);
   513 	undoSet.setEntry (QString("/history/step-%1/redoCommand").arg(curStep),redoCom);
   514 	undoSet.setEntry (QString("/history/step-%1/redoSelection").arg(curStep),redoSelection);
   515 	undoSet.setEntry (QString("/history/step-%1/comment").arg(curStep),comment);
   516 	undoSet.writeSettings(histPath);
   517 
   518 	/* TODO remove after testing
   519 	*/
   520 	//cout << "          into="<< histPath.toStdString()<<endl;
   521 	cout << "    stepsTotal="<<stepsTotal<<
   522 	", undosAvail="<<undosAvail<<
   523 	", redosAvail="<<redosAvail<<
   524 	", curStep="<<curStep<<endl;
   525 	cout << "    ---------------------------"<<endl;
   526 	cout << "    comment="<<comment.toStdString()<<endl;
   527 	cout << "    undoCom="<<undoCommand.toStdString()<<endl;
   528 	cout << "    undoSel="<<undoSelection.toStdString()<<endl;
   529 	cout << "    redoCom="<<redoCom.toStdString()<<endl;
   530 	cout << "    redoSel="<<redoSelection.toStdString()<<endl;
   531 	cout << "    ---------------------------"<<endl;
   532 
   533 	historyWindow.update (undoSet);
   534 }
   535 
   536 void MapEditor::parseAtom(const QString &atom)
   537 {
   538 	API api;
   539 	QString s,t;
   540 	int x,y;
   541 	bool ok;
   542 
   543 	// Split string s into command and parameters
   544 	api.parseCommand (atom);
   545 	QString com=api.command();
   546 	
   547 	// External commands
   548 	if (com=="moveBranchUp")
   549 		moveBranchUp();
   550 	else if (com=="moveBranchDown")
   551 		moveBranchDown();
   552 	else if (com=="move")
   553 	{
   554 		if (api.checkParamCount(2) && selection )
   555 		{	
   556 			x=api.parInt (ok,0);
   557 			if (ok)
   558 			{
   559 				y=api.parInt (ok,1);
   560 				if (ok) move (x,y);
   561 			}
   562 		}	
   563 	}
   564 	else if (com=="moveRel")
   565 	{
   566 		if (api.checkParamCount(2) && selection )
   567 		{	
   568 			x=api.parInt (ok,0);
   569 			if (ok)
   570 			{
   571 				y=api.parInt (ok,1);
   572 				if (ok) moveRel (x,y);
   573 			}
   574 		}	
   575 	}
   576 	else if (com=="delete")
   577 	{
   578 		if (api.checkParamCount(1) && selection )
   579 		{	
   580 			s=api.parString(ok,0);
   581 			if (ok &&select (s)) deleteSelection();
   582 		}	
   583 	}	
   584 	else if (com=="addBranch")
   585 	{
   586 		if (api.checkParamCount(1) && selection )
   587 		{	
   588 			y=api.parInt (ok,0);
   589 			if (ok ) addNewBranchInt (y);
   590 		}	
   591 	}	
   592 	else if (com=="linkBranchToPos")
   593 	{
   594 		if (selection && typeid(*selection) == typeid(BranchObj) ) 
   595 		{
   596 			if (api.checkParamCount(4))
   597 			{
   598 				// 0	selectstring of parent
   599 				// 1	num in parent (for branches)
   600 				// 2,3	x,y of mainbranch or mapcenter
   601 				s=api.parString(ok,0);
   602 				LinkableMapObj *dst=mapCenter->findObjBySelect (s);
   603 				if (dst)
   604 				{	
   605 					if (typeid(*dst) == typeid(BranchObj) ) 
   606 					{
   607 						// Get number in parent
   608 						x=api.parInt (ok,1);
   609 						if (ok)
   610 							((BranchObj*)selection)->moveBranchTo ((BranchObj*)(dst),x);
   611 					} else if (typeid(*dst) == typeid(MapCenterObj) ) 
   612 					{
   613 						((BranchObj*)selection)->moveBranchTo ((BranchObj*)(dst),-1);
   614 						// Get coordinates of mainbranch
   615 						x=api.parInt (ok,2);
   616 						if (ok)
   617 						{
   618 							y=api.parInt (ok,3);
   619 							if (ok) ((BranchObj*)selection)->move (x,y);
   620 						}
   621 					}	
   622 				}	
   623 			}
   624 		}
   625 	} else if (com=="setHeading")
   626 	{
   627 		if (api.checkParamCount(1))
   628 		{
   629 			s=api.parString (ok,0);
   630 			if (ok) 
   631 				setHeading (s);
   632 		}	
   633 	} else if (com=="setURL")
   634 	{
   635 		if (api.checkParamCount(1))
   636 		{
   637 			s=api.parString (ok,0);
   638 			if (ok) setURLInt(s);
   639 		}	
   640 	} else if (com=="setVymLink")
   641 	{
   642 		if (api.checkParamCount(1))
   643 		{
   644 			s=api.parString (ok,0);
   645 			if (ok) setVymLinkInt(s);
   646 		}	
   647 	}
   648 	else if (com=="setFlag")
   649 	{
   650 		if (selection && typeid(*selection) == typeid(BranchObj) ) 
   651 		{
   652 			if (api.checkParamCount(1) )
   653 			{	
   654 				s=api.parString(ok,0);
   655 				if (ok) 
   656 				{
   657 					BranchObj* bo=(BranchObj*)selection;
   658 					bo->activateStandardFlag(s);
   659 					bo->updateFlagsToolbar();
   660 				}	
   661 			}	
   662 		}
   663 	}	
   664 	else if (com=="unsetFlag")
   665 	{
   666 		if (selection && typeid(*selection) == typeid(BranchObj) ) 
   667 		{
   668 			if (api.checkParamCount(1) )
   669 			{	
   670 				s=api.parString(ok,0);
   671 				if (ok) 
   672 				{
   673 					BranchObj* bo=(BranchObj*)selection;
   674 					bo->deactivateStandardFlag(s);
   675 					bo->updateFlagsToolbar();
   676 				}	
   677 			}	
   678 		}
   679 	}	
   680 	// Internal commands, used for undo etc.	
   681 	else if (com==QString("undoMap"))
   682 	{
   683 		if (api.checkParamCount(1))
   684 			undoXML("",api.parString (ok,0));
   685 	} else if (com==QString("undoPart"))
   686 	{
   687 		if (api.checkParamCount(2))
   688 		{
   689 			s=api.parString (ok,0);	// undo selection
   690 			t=api.parString (ok,1);	// backup dir
   691 			if (QDir::isRelativePath(t)) t=QDir::convertSeparators (tmpMapDir + "/"+t);
   692 			cout <<t.ascii()<<endl;
   693 			undoXML(s,t);	
   694 		}
   695 	} else if (com=="select")
   696 	{
   697 		if (api.checkParamCount(1))
   698 		{
   699 			s=api.parString(ok,0);
   700 			if (ok) select (s);
   701 		}	
   702 	}	
   703 	else
   704 	{
   705 		api.setError ("Unknown command in: "+atom);
   706 	}
   707 
   708 	// Any errors?
   709 	if (api.error())
   710 	{
   711 		// TODO Error handling
   712 		qWarning("MapEditor::parseAtom: Error!");
   713 		qWarning(api.errorDesc());
   714 	}	
   715 }
   716 
   717 void MapEditor::toggleHistoryWindow()
   718 {
   719 	if (historyWindow.isVisible())
   720 		historyWindow.hide();
   721 	else	
   722 		historyWindow.show();
   723 }
   724 
   725 
   726 bool MapEditor::isDefault()
   727 {
   728     return mapDefault;
   729 }
   730 
   731 bool MapEditor::isUnsaved()
   732 {
   733     return mapUnsaved;
   734 }
   735 
   736 bool MapEditor::hasChanged()
   737 {
   738     return mapChanged;
   739 }
   740 
   741 void MapEditor::setChanged()
   742 {
   743 	mapChanged=true;
   744 	mapDefault=false;
   745 	mapUnsaved=true;
   746 	findReset();
   747 }
   748 
   749 void MapEditor::closeMap()
   750 {
   751 	// Unselect before disabling the toolbar actions
   752 	if (selection) selection->unselect();
   753 	selection=NULL;
   754 	updateActions();
   755 
   756     clear();
   757 	close();
   758 }
   759 
   760 void MapEditor::setFilePath(QString fname)
   761 {
   762 	setFilePath (fname,fname);
   763 }
   764 
   765 void MapEditor::setFilePath(QString fname, QString destname)
   766 {
   767 	if (fname.isEmpty() || fname=="")
   768 	{
   769 		filePath="";
   770 		fileName="";
   771 		destPath="";
   772 	} else
   773 	{
   774 		filePath=fname;		// becomes absolute path
   775 		fileName=fname;		// gets stripped of path
   776 		destPath=destname;	// needed for vymlinks
   777 
   778 		// If fname is not an absolute path, complete it
   779 		filePath=QDir(fname).absPath();
   780 		fileDir=filePath.left (1+filePath.findRev ("/"));
   781 
   782 		// Set short name, too. Search from behind:
   783 		int i=fileName.findRev("/");
   784 		if (i>=0) fileName=fileName.remove (0,i+1);
   785 
   786 		// Forget the .vym (or .xml) for name of map
   787 		mapName=fileName.left(fileName.findRev(".",-1,true) );
   788 
   789 		// Adjust history window
   790 		historyWindow.setCaption (__VYM " - " +tr("History for ")+fileName);
   791 	}
   792 }
   793 
   794 QString MapEditor::getFilePath()
   795 {
   796 	return filePath;
   797 }
   798 
   799 QString MapEditor::getFileName()
   800 {
   801 	return fileName;
   802 }
   803 
   804 QString MapEditor::getMapName()
   805 {
   806 	return mapName;
   807 }
   808 
   809 QString MapEditor::getDestPath()
   810 {
   811 	return destPath;
   812 }
   813 
   814 ErrorCode MapEditor::load (QString fname, LoadMode lmode)
   815 {
   816 	ErrorCode err=success;
   817 
   818 	if (lmode==NewMap)
   819 	{
   820 		if (selection) selection->unselect();
   821 		selection=NULL;
   822 		mapCenter->clear();
   823 		mapCenter->setMapEditor(this);
   824 		// (map state is set later at end of load...)
   825 	} else
   826 	{
   827 		saveStatePart(selection,"Load map");
   828 	}	
   829 	
   830     
   831     mapBuilderHandler handler;
   832 	QFile file( fname );
   833 
   834 	// I am paranoid: file should exist anyway
   835 	// according to check in mainwindow.
   836 	if (!file.exists() )
   837 	{
   838 		QMessageBox::critical( 0, tr( "Critical Parse Error" ),
   839 				   tr("Couldn't open map " +fname)+".");
   840 		err=aborted;	
   841 	} else
   842 	{
   843 		blockReposition=true;
   844 		QXmlInputSource source( file);
   845 		QXmlSimpleReader reader;
   846 		reader.setContentHandler( &handler );
   847 		reader.setErrorHandler( &handler );
   848 		handler.setMapEditor( this );
   849 		handler.setTmpDir (filePath.left(filePath.findRev("/",-1)));	// needed to load files with rel. path
   850 		handler.setInputFile (file.name());
   851 		handler.setLoadMode (lmode);
   852 		blockSaveState=true;
   853 		bool ok = reader.parse( source );
   854 		blockReposition=false;
   855 		blockSaveState=false;
   856 		file.close();
   857 		if ( ok ) 
   858 		{
   859 			mapCenter->reposition();
   860 			adjustCanvasSize();
   861 			if (lmode==NewMap)
   862 			{
   863 				mapDefault=false;
   864 				mapChanged=false;
   865 				mapUnsaved=false;
   866 			}
   867 		} else 
   868 		{
   869 			QMessageBox::critical( 0, tr( "Critical Parse Error" ),
   870 					   tr( handler.errorProtocol() ) );
   871 			// returnCode=1;	
   872 			// Still return "success": the map maybe at least
   873 			// partially read by the parser
   874 		}	
   875 	}	
   876 	updateActions();
   877 	return err;
   878 }
   879 
   880 int MapEditor::save (const SaveMode &savemode)
   881 {
   882 	int returnCode=0;
   883 
   884 	// The SaveMode UndoCommand is not supported here
   885 	if (savemode==UndoCommand) return 1;
   886 
   887 	// Create mapName and fileDir
   888 	makeSubDirs (fileDir);
   889 	QString fname;
   890 	if (saveZipped())
   891 		// save as .xml
   892 		fname=mapName+".xml";
   893 	else
   894 		// use name given by user, even if he chooses .doc
   895 		fname=fileName;
   896 
   897 
   898 	QString saveFile;
   899 	if (savemode==CompleteMap || selection==NULL)
   900 		saveFile=saveToDir (fileDir,mapName+"-",true,QPoint(),NULL);
   901 	else	
   902 		saveFile=saveToDir (fileDir,mapName+"-",true,QPoint(),selection);
   903 
   904 	if (!saveStringToDisk(fileDir+fname,saveFile))
   905 		return 1;
   906 
   907 	if (returnCode==0)
   908 	{
   909 		mapChanged=false;
   910 		mapUnsaved=false;
   911 		updateActions();
   912 	}
   913 
   914 	return returnCode;
   915 }
   916 
   917 void MapEditor::setZipped (bool z)
   918 {
   919 	zipped=z;
   920 }
   921 
   922 bool MapEditor::saveZipped ()
   923 {
   924 	return zipped;
   925 }
   926 
   927 void MapEditor::print()
   928 {
   929 	if ( !printer ) 
   930 	{
   931 		printer = new QPrinter;
   932 		printer->setColorMode (QPrinter::Color);
   933 		printer->setPrinterName (settings.value("/mainwindow/printerName",printer->printerName()).toString());
   934 	}
   935 
   936 	QRect totalBBox=mapCenter->getTotalBBox();
   937 
   938 	// Try to set orientation automagically
   939 	// Note: Interpretation of generated postscript is amibiguous, if 
   940 	// there are problems with landscape mode, see
   941 	// http://sdb.suse.de/de/sdb/html/jsmeix_print-cups-landscape-81.html
   942 
   943 	if (totalBBox.width()>totalBBox.height())
   944 		// recommend landscape
   945 		printer->setOrientation (QPrinter::Landscape);
   946 	else	
   947 		// recommend portrait
   948 		printer->setOrientation (QPrinter::Portrait);
   949 
   950 	if ( printer->setup(this) ) 
   951 	// returns false, if printing is canceled
   952 	{
   953 		QPainter pp(printer);
   954 
   955 		// Don't print the visualisation of selection
   956 		LinkableMapObj *oldselection=NULL;
   957 		if (selection) 
   958 		{
   959 			oldselection=selection;
   960 			selection->unselect();
   961 		}
   962 
   963 		// Handle sizes of map and paper:
   964 		//
   965 		// setWindow defines which part of the canvas will be transformed 
   966 		// setViewport defines area on paper in device coordinates (dpi)
   967 		// e.g. (0,50,700,700) is upper part on A4
   968 		// see also /usr/lib/qt3/doc/html/coordsys.html
   969 
   970 		Q3PaintDeviceMetrics metrics (printer);
   971 
   972 		double paperAspect = (double)metrics.width()   / (double)metrics.height();
   973 		double   mapAspect = (double)totalBBox.width() / (double)totalBBox.height();
   974 
   975 		QRect mapRect=totalBBox;
   976 		Q3CanvasRectangle *frame=NULL;
   977 		Q3CanvasText *footerFN=NULL;
   978 		Q3CanvasText *footerDate=NULL;
   979 		if (printFrame || printFooter)
   980 		{
   981 			
   982 			if (printFrame) 
   983 			{
   984 				// Print frame around map
   985 				mapRect.setRect (totalBBox.x()-10, totalBBox.y()-10, 
   986 					totalBBox.width()+20, totalBBox.height()+20);
   987 				frame=new Q3CanvasRectangle (mapRect,mapCanvas);
   988 				frame->setBrush (QColor(Qt::white));
   989 				frame->setPen (QColor(Qt::black));
   990 				frame->setZ(0);
   991 				frame->show();    
   992 			}		
   993 			/* TODO remove after testing 
   994 			QCanvasLine *l=new QCanvasLine (mapCanvas);
   995 			l->setPoints (0,0,mapRect.width(),mapRect.height());
   996 			l->setPen (QPen(QColor(black), 1));
   997 			l->setZ (200);
   998 			l->show();
   999 			*/
  1000 
  1001 			if (printFooter) 
  1002 			{
  1003 				// Print footer below map
  1004 				QFont font;		
  1005 				font.setPointSize(10);
  1006 				footerFN=new Q3CanvasText (mapCanvas);
  1007 				footerFN->setText ("VYM - " + fileName);
  1008 				footerFN->setFont(font);
  1009 				footerFN->move (mapRect.x(), mapRect.y() + mapRect.height() );
  1010 				footerFN->setZ(Z_TEXT);
  1011 				footerFN->show();    
  1012 				footerDate=new Q3CanvasText (mapCanvas);
  1013 				footerDate->setText (QDate::currentDate().toString(Qt::TextDate));
  1014 				footerDate->setFont(font);
  1015 				footerDate->move (mapRect.x()+mapRect.width()-footerDate->boundingRect().width(), mapRect.y() + mapRect.height() );
  1016 				footerDate->setZ(Z_TEXT);
  1017 				footerDate->show();    
  1018 			}
  1019 			pp.setWindow (mapRect.x(), mapRect.y(), mapRect.width(), mapRect.height()+20);
  1020 		}	else	
  1021 		{
  1022 			pp.setWindow (mapRect);
  1023 		}	
  1024 
  1025 		if (mapAspect>=paperAspect)
  1026 		{
  1027 			// Fit horizontally to paper width
  1028 			pp.setViewport(0,0, metrics.width(),(int)(metrics.width()/mapAspect) );	
  1029 		}	else
  1030 		{
  1031 			// Fit vertically to paper height
  1032 			pp.setViewport(0,0,(int)(metrics.height()*mapAspect),metrics.height());	
  1033 		}	
  1034 
  1035 		mapCanvas->drawArea(mapRect, &pp);	// draw Canvas to printer
  1036 
  1037 		// Delete Frame and footer
  1038 		if (footerFN) 
  1039 		{
  1040 			delete (footerFN);
  1041 			delete (footerDate);
  1042 		}	
  1043 		if (frame)  delete (frame);
  1044 
  1045 		// Restore selection
  1046 		if (oldselection) 
  1047 		{
  1048 			selection=oldselection;
  1049 			selection->select();
  1050 		}	
  1051 
  1052 		// Save settings in vymrc
  1053 		settings.writeEntry("/mainwindow/printerName",printer->printerName());
  1054 	}
  1055 }
  1056 
  1057 QPixmap MapEditor::getPixmap()
  1058 {
  1059 	QRect mapRect=mapCenter->getTotalBBox();
  1060 	QPixmap pix (mapRect.size());
  1061 	QPainter pp (&pix);
  1062 
  1063 	// Don't print the visualisation of selection
  1064 	LinkableMapObj *oldselection=NULL;
  1065 	if (selection) 
  1066 	{
  1067 		oldselection=selection;
  1068 		selection->unselect();
  1069 	}
  1070 
  1071 	pp.setWindow (mapRect);
  1072 
  1073 	mapCanvas->drawArea(mapRect, &pp);	// draw Canvas to painter
  1074 
  1075 
  1076 	// Restore selection
  1077 	if (oldselection) 
  1078 	{
  1079 		selection=oldselection;
  1080 		selection->select();
  1081 	}	
  1082 	
  1083 	return pix;
  1084 }
  1085 
  1086 void MapEditor::setHideTmpMode (HideTmpMode mode)
  1087 {
  1088 	hidemode=mode;
  1089 	mapCenter->setHideTmp (hidemode);
  1090 	mapCenter->reposition();
  1091 	adjustCanvasSize();
  1092 	canvas()->update();
  1093 }
  1094 
  1095 HideTmpMode MapEditor::getHideTmpMode()
  1096 {
  1097 	return hidemode;
  1098 }
  1099 
  1100 void MapEditor::exportImage(QString fn)
  1101 {
  1102 	setExportMode (true);
  1103 	QPixmap pix (getPixmap());
  1104 	pix.save(fn, "PNG");
  1105 	setExportMode (false);
  1106 }
  1107 
  1108 void MapEditor::setExportMode (bool b)
  1109 {
  1110 	// should be called before and after exports
  1111 	// depending on the settings
  1112 	if (b && settings.value("/export/useHideExport","yes")=="yes")
  1113 		setHideTmpMode (HideExport);
  1114 	else	
  1115 		setHideTmpMode (HideNone);
  1116 }
  1117 
  1118 void MapEditor::exportImage(QString fn, QString format)
  1119 {
  1120 	setExportMode (true);
  1121 	QPixmap pix (getPixmap());
  1122 	pix.save(fn, format);
  1123 	setExportMode (false);
  1124 }
  1125 
  1126 void MapEditor::exportOOPresentation(const QString &fn, const QString &cf)
  1127 {
  1128 	ExportOO ex;
  1129 	ex.setFile (fn);
  1130 	ex.setMapCenter(mapCenter);
  1131 	if (ex.setConfigFile(cf)) 
  1132 	{
  1133 		setExportMode (true);
  1134 		ex.exportPresentation();
  1135 		setExportMode (false);
  1136 	}
  1137 }
  1138 
  1139 
  1140 
  1141 void MapEditor::exportXML(const QString &dir)
  1142 {
  1143 	// Hide stuff during export, if settings want this
  1144 	setExportMode (true);
  1145 
  1146 	// Create subdirectories
  1147 	makeSubDirs (dir);
  1148 
  1149 	// write to directory
  1150 	QString saveFile=saveToDir (dir,mapName+"-",true,mapCenter->getTotalBBox().topLeft() ,NULL);
  1151 	QFile file;
  1152 
  1153 	file.setName ( dir + "/"+mapName+".xml");
  1154 	if ( !file.open( QIODevice::WriteOnly ) )
  1155 	{
  1156 		// This should neverever happen
  1157 		QMessageBox::critical (0,tr("Critical Export Error"),tr("MapEditor::exportXML couldn't open %1").arg(file.name()));
  1158 		return;
  1159 	}	
  1160 
  1161 	// Write it finally, and write in UTF8, no matter what 
  1162 	QTextStream ts( &file );
  1163 	ts.setEncoding (QTextStream::UnicodeUTF8);
  1164 	ts << saveFile;
  1165 	file.close();
  1166 
  1167 	// Now write image, too
  1168 	exportImage (dir+"/images/"+mapName+".png");
  1169 
  1170 	setExportMode (false);
  1171 }
  1172 
  1173 void MapEditor::clear()
  1174 {
  1175 	if (selection)
  1176 	{
  1177 		selection->unselect();
  1178 		selection=NULL;
  1179 	}	
  1180 
  1181 	mapCenter->clear();
  1182 }
  1183 
  1184 void MapEditor::copy()
  1185 {
  1186 	if (selection) 
  1187 	{
  1188 		// write to directory
  1189 		QString clipfile="part";
  1190 		QString saveFile=saveToDir (fileDir,clipfile+"-",true,QPoint(),selection);
  1191 		QFile file;
  1192 
  1193 		file.setName ( clipboardDir + "/"+clipfile+".xml");
  1194 		if ( !file.open( QIODevice::WriteOnly ) )
  1195 		{
  1196 			// This should neverever happen
  1197 			QMessageBox::critical (0,tr("Critical Export Error"),tr("MapEditor::exportXML couldn't open %1").arg(file.name()));
  1198 			return;
  1199 		}	
  1200 
  1201 		// Write it finally, and write in UTF8, no matter what 
  1202 		QTextStream ts( &file );
  1203 		ts.setEncoding (QTextStream::UnicodeUTF8);
  1204 		ts << saveFile;
  1205 		file.close();
  1206 
  1207 		clipboardEmpty=false;
  1208 		updateActions();
  1209 	}	    
  1210 }
  1211 
  1212 void MapEditor::redo()
  1213 {
  1214 	blockSaveState=true;
  1215 	
  1216 	// Restore variables
  1217 	int curStep=undoSet.readNumEntry (QString("/history/curStep"));
  1218 	int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
  1219 	int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
  1220 	// Can we undo at all?
  1221 	if (redosAvail<1) return;
  1222 	redosAvail--;
  1223 
  1224 	if (undosAvail<stepsTotal) undosAvail++;
  1225 	curStep++;
  1226 	if (curStep>stepsTotal) curStep=1;
  1227 	QString undoCommand=  undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
  1228 	QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
  1229 	QString redoCommand=  undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
  1230 	QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
  1231 	QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
  1232 
  1233 	// Find out current undo directory
  1234 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(curStep));
  1235 
  1236 /* TODO remove testing
  1237 */
  1238 	cout << "ME::redo() begin\n";
  1239 	cout << "    undosAvail="<<undosAvail<<endl;
  1240 	cout << "    redosAvail="<<redosAvail<<endl;
  1241 	cout << "       curStep="<<curStep<<endl;
  1242 	cout << "    ---------------------------"<<endl;
  1243 	cout << "    comment="<<comment.toStdString()<<endl;
  1244 	cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  1245 	cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  1246 	cout << "    redoCom="<<redoCommand.toStdString()<<endl;
  1247 	cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  1248 	cout << "    ---------------------------"<<endl<<endl;
  1249 
  1250 	// select  object before redo
  1251 	// FIXME better give up if no selection there...
  1252 	if (!redoSelection.isEmpty())
  1253 		select (redoSelection);
  1254 
  1255 
  1256 	parseAtom (redoCommand);
  1257 	mapCenter->reposition();
  1258 
  1259 	blockSaveState=false;
  1260 
  1261 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1262 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1263 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1264 	undoSet.writeSettings(histPath);
  1265 
  1266 	historyWindow.update (undoSet);
  1267 	updateActions();
  1268 
  1269 	/* TODO remove testing
  1270 */
  1271 	cout << "ME::redo() end\n";
  1272 	cout << "    undosAvail="<<undosAvail<<endl;
  1273 	cout << "    redosAvail="<<redosAvail<<endl;
  1274 	cout << "       curStep="<<curStep<<endl;
  1275 	cout << "    ---------------------------"<<endl<<endl;
  1276 
  1277 
  1278 }
  1279 
  1280 bool MapEditor::isRedoAvailable()
  1281 {
  1282 	if (undoSet.readNumEntry("/history/undosAvail",0)>0)
  1283 		return true;
  1284 	else	
  1285 		return false;
  1286 }
  1287 
  1288 void MapEditor::undo()
  1289 {
  1290 	blockSaveState=true;
  1291 	
  1292 	// Restore variables
  1293 	int curStep=undoSet.readNumEntry (QString("/history/curStep"));
  1294 	int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
  1295 	int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
  1296 
  1297 	// Can we undo at all?
  1298 	if (undosAvail<1) return;
  1299 
  1300 	QString undoCommand=  undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
  1301 	QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
  1302 	QString redoCommand=  undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
  1303 	QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
  1304 	QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
  1305 
  1306 	// Find out current undo directory
  1307 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(curStep));
  1308 
  1309 	// select  object before undo
  1310 	if (!undoSelection.isEmpty())
  1311 		select (undoSelection);
  1312 
  1313 /* TODO testing
  1314 */	
  1315 	cout << "ME::undo() begin\n";
  1316 	cout << "    undosAvail="<<undosAvail<<endl;
  1317 	cout << "    redosAvail="<<redosAvail<<endl;
  1318 	cout << "       curStep="<<curStep<<endl;
  1319 	cout << "    ---------------------------"<<endl;
  1320 	cout << "    comment="<<comment.toStdString()<<endl;
  1321 	cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  1322 	cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  1323 	cout << "    redoCom="<<redoCommand.toStdString()<<endl;
  1324 	cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  1325 	cout << "    ---------------------------"<<endl<<endl;
  1326 	parseAtom (undoCommand);
  1327 	mapCenter->reposition();
  1328 
  1329 	undosAvail--;
  1330 	curStep--; 
  1331 	if (curStep<1) curStep=stepsTotal;
  1332 
  1333 	redosAvail++;
  1334 
  1335 	blockSaveState=false;
  1336 /* TODO remove testing
  1337 */
  1338 	cout << "ME::undo() end\n";
  1339 	cout << "    undosAvail="<<undosAvail<<endl;
  1340 	cout << "    redosAvail="<<redosAvail<<endl;
  1341 	cout << "       curStep="<<curStep<<endl;
  1342 	cout << "    ---------------------------"<<endl<<endl;
  1343 
  1344 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1345 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1346 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1347 	undoSet.writeSettings(histPath);
  1348 
  1349 	historyWindow.update (undoSet);
  1350 	updateActions();
  1351 }
  1352 
  1353 bool MapEditor::isUndoAvailable()
  1354 {
  1355 	if (undoSet.readNumEntry("/history/undosAvail",0)>0)
  1356 		return true;
  1357 	else	
  1358 		return false;
  1359 }
  1360 
  1361 void MapEditor::gotoStep (int i)
  1362 {
  1363 	// Restore variables
  1364 	int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
  1365 	int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
  1366 
  1367 	cout << "ME::goto "<<i<<endl;
  1368 	
  1369 	if (i<0) i=undosAvail+redosAvail;
  1370 
  1371 	// Clicking above current step makes us undo things
  1372 	if (i<undosAvail) 
  1373 	{	
  1374 		for (int j=0; j<undosAvail-i; j++) undo();
  1375 		return;
  1376 	}	
  1377 	// Clicking below current step makes us redo things
  1378 	if (i>undosAvail) 
  1379 		for (int j=undosAvail; j<i; j++) redo();
  1380 
  1381 	// And ignore clicking the current row ;-)	
  1382 }
  1383 
  1384 void MapEditor::undoXML(const QString &undoSel, const QString &bakMapPath)
  1385 {
  1386 	QString bakMapDir=bakMapPath.left(bakMapPath.findRev("/"));
  1387 	QDir d(bakMapDir);
  1388 	QFile file (bakMapPath);
  1389 
  1390 	if (d.exists() )
  1391 	{
  1392 		// We need to parse saved XML data
  1393 		mapBuilderHandler handler;
  1394 		QXmlInputSource source( file);
  1395 		QXmlSimpleReader reader;
  1396 		reader.setContentHandler( &handler );
  1397 		reader.setErrorHandler( &handler );
  1398 		handler.setMapEditor( this );
  1399 		handler.setTmpDir ( bakMapDir );	// needed to load files with rel. path
  1400 		if (undoSel.isEmpty())
  1401 		{
  1402 			unselect();
  1403 			mapCenter->clear();
  1404 			handler.setLoadMode (NewMap);
  1405 		} else	
  1406 		{
  1407 			select (undoSel);
  1408 			handler.setLoadMode (ImportReplace);
  1409 		}	
  1410 		blockReposition=true;
  1411 		bool ok = reader.parse( source );
  1412 		blockReposition=false;
  1413 		if (! ok ) 
  1414 		{	
  1415 			// This should never ever happen
  1416 			QMessageBox::critical( 0, tr( "Critical Parse Error by reading backupFile" ),
  1417 								   tr( handler.errorProtocol() )+" in "+bakMapDir );
  1418 		}
  1419 	} else	
  1420 	{
  1421 		QMessageBox::critical( 0, tr( "Critical Error" ),
  1422 			tr("Temporary directory %1 used for undo is gone. \n"
  1423 			"I will create a new one, but at the moment no undo is available.\n"
  1424 			"Maybe you want to reload your original data.\n\n"
  1425 			"Sorry for any inconveniences.").arg(bakMapDir) );
  1426 		makeTmpDirs();	
  1427 	}							
  1428 }
  1429 
  1430 void MapEditor::pasteNoSave()
  1431 {
  1432 	load (clipboardDir+"/part.xml",ImportAdd);
  1433 }
  1434 
  1435 void MapEditor::cutNoSave()
  1436 {
  1437 	copy();
  1438 	deleteSelection();
  1439 }
  1440 
  1441 void MapEditor::paste()
  1442 {   
  1443 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  1444 				      typeid(*selection) == typeid(MapCenterObj))) 
  1445 	{
  1446 		saveStatePart(selection,QString("Paste to %1").arg( getName(selection)));
  1447 		pasteNoSave();
  1448 		mapCenter->reposition();
  1449 		adjustCanvasSize();
  1450 	}
  1451 }
  1452 
  1453 void MapEditor::cut()
  1454 {
  1455 	saveStatePart(selection->getParObj(),QString("Cut %1").arg(getName(selection)));
  1456 	copy();
  1457 	cutNoSave();
  1458 	mapCenter->reposition();
  1459 	adjustCanvasSize();
  1460 }
  1461 
  1462 void MapEditor::move(const int &x, const int &y)
  1463 {
  1464 	if (selection)
  1465 	{
  1466 		QString ps=qpointToString (selection->getAbsPos());
  1467 		QString s=selection->getSelectString();
  1468 		saveState(
  1469 			s, "move "+ps, 
  1470 			s, "move "+qpointToString (QPoint (x,y)), 
  1471 			QString("Move %1 to  %2").arg(getName(selection)).arg(ps));
  1472 		selection->move(x,y);
  1473 		mapCenter->reposition();
  1474 		adjustCanvasSize();
  1475 	}
  1476 
  1477 }
  1478 
  1479 void MapEditor::moveRel (const int &x, const int &y)
  1480 {
  1481 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  1482 				      typeid(*selection) == typeid(MapCenterObj) ||
  1483 					  typeid(*selection) == typeid (FloatImageObj))) 
  1484 	{
  1485 		QString ps=qpointToString (selection->getRelPos());
  1486 		QString s=selection->getSelectString();
  1487 		saveState(
  1488 			s, "moveRel "+ps, 
  1489 			s, "moveRel "+qpointToString (QPoint (x,y)), 
  1490 			QString("Move %1 to relativ position %2").arg(getName(selection)).arg(ps));
  1491 		((OrnamentedObj*)selection)->move2RelPos (x,y);
  1492 		mapCenter->reposition();
  1493 		adjustCanvasSize();
  1494 	}
  1495 }
  1496 
  1497 void MapEditor::moveBranchUp()
  1498 {
  1499 	BranchObj* bo;
  1500 	BranchObj* par;
  1501 	if (typeid(*selection) == typeid(BranchObj)  ) 
  1502 	{
  1503 		bo=(BranchObj*)selection;
  1504 		if (!bo->canMoveBranchUp()) return;
  1505 		par=(BranchObj*)(bo->getParObj());
  1506 		selection->unselect();
  1507 		bo=par->moveBranchUp (bo);	// bo will be the one below selection
  1508 		selection->select();
  1509 		saveState (selection,"moveBranchDown ()",bo,"moveBranchUp ()",QString("Move up %1").arg(getName(bo)));
  1510 		mapCenter->reposition();
  1511 		ensureSelectionVisible();
  1512 	}
  1513 }
  1514 
  1515 void MapEditor::moveBranchDown()
  1516 {
  1517 	BranchObj* bo;
  1518 	BranchObj* par;
  1519 	if (typeid(*selection) == typeid(BranchObj)  ) 
  1520 	{
  1521 		bo=(BranchObj*)selection;
  1522 		if (!bo->canMoveBranchDown()) return;
  1523 		par=(BranchObj*)(bo->getParObj());
  1524 		selection->unselect(); 
  1525 		bo=par->moveBranchDown(bo);	// bo will be the one above selection
  1526 		selection->select();
  1527 		saveState(selection,"moveBranchUp ()",bo,"moveBranchDown ()",QString("Move down %1").arg(getName(bo)));
  1528 		mapCenter->reposition();
  1529 		ensureSelectionVisible();
  1530 	}	
  1531 }
  1532 
  1533 QString MapEditor::getHeading(bool &ok, QPoint &p)
  1534 {
  1535 	if (selection  &&  
  1536 		 (typeid(*selection) == typeid(BranchObj) || 
  1537 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1538 	{
  1539 		ok=true;
  1540 		ensureSelectionVisible();
  1541 		p = ((BranchObj*)selection)->getAbsPos();
  1542 		p.setX (p.x() - contentsX());
  1543 		p.setY (p.y() - contentsY() + ((BranchObj*)selection)->height()/2);
  1544 		return ((BranchObj*)selection)->getHeading();
  1545 	}
  1546 	ok=false;
  1547 	return QString();
  1548 }
  1549 
  1550 void MapEditor::setHeading(const QString &s)
  1551 {
  1552 	if (selection  &&  
  1553 		 (typeid(*selection) == typeid(BranchObj) || 
  1554 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1555 	{
  1556 		editingBO=(BranchObj*)selection;
  1557 		saveStateConstSelection(
  1558 			"setHeading (\""+editingBO->getHeading()+"\")", 
  1559 			"setHeading (\""+s+"\")", 
  1560 			QString("Set heading of %1 to \"%2\"").arg(getName(editingBO)).arg(s) );
  1561 		editingBO->setHeading(s );
  1562 		editingBO=NULL;
  1563 		mapCenter->reposition();
  1564 		adjustCanvasSize();
  1565 		ensureSelectionVisible();
  1566 	}
  1567 }
  1568 
  1569 void MapEditor::setURLInt (const QString &s)
  1570 {
  1571 	// Internal function, no saveState needed
  1572 	if (selection  &&  
  1573 		 (typeid(*selection) == typeid(BranchObj) || 
  1574 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1575 	{
  1576 		((BranchObj*)selection)->setURL(s);
  1577 		mapCenter->reposition();
  1578 		adjustCanvasSize();
  1579 		ensureSelectionVisible();
  1580 	}
  1581 }
  1582 
  1583 void MapEditor::setHeadingInt(const QString &s)
  1584 {
  1585 	if (selection  &&  
  1586 		 (typeid(*selection) == typeid(BranchObj) || 
  1587 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1588 	{
  1589 		((BranchObj*)selection)->setHeading(s);
  1590 		mapCenter->reposition();
  1591 		adjustCanvasSize();
  1592 		ensureSelectionVisible();
  1593 	}
  1594 }
  1595 
  1596 void MapEditor::setVymLinkInt (const QString &s)
  1597 {
  1598 	// Internal function, no saveState needed
  1599 	if (selection  &&  
  1600 		 (typeid(*selection) == typeid(BranchObj) || 
  1601 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1602 	{
  1603 		((BranchObj*)selection)->setVymLink(s);
  1604 		mapCenter->reposition();
  1605 		adjustCanvasSize();
  1606 		ensureSelectionVisible();
  1607 	}
  1608 }
  1609 
  1610 BranchObj* MapEditor::addNewBranchInt(int num)
  1611 {
  1612 	// Depending on pos:
  1613 	// -3		insert in childs of parent  above selection 
  1614 	// -2		add branch to selection 
  1615 	// -1		insert in childs of parent below selection 
  1616 	// 0..n		insert in childs of parent at pos
  1617 	BranchObj *newbo=NULL;
  1618 	if (selection  &&  
  1619 		 (typeid(*selection) == typeid(BranchObj) || 
  1620 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1621 	{
  1622 		BranchObj* bo = (BranchObj*) selection;
  1623 		if (num==-2)
  1624 		{
  1625 			// save scroll state. If scrolled, automatically select
  1626 			// new branch in order to tmp unscroll parent...
  1627 			return bo->addBranch();
  1628 			
  1629 		}else if (num==-1)
  1630 		{
  1631 			num=bo->getNum()+1;
  1632 			bo=(BranchObj*)bo->getParObj();
  1633 		}else if (num==-3)
  1634 		{
  1635 			num=bo->getNum();
  1636 			bo=(BranchObj*)bo->getParObj();
  1637 		}
  1638 		if (!bo) return bo;
  1639 		newbo=bo->insertBranch(num);
  1640 	}	
  1641 	return newbo;
  1642 }	
  1643 
  1644 void MapEditor::addNewBranch(int pos)
  1645 {
  1646 	// Different meaning than num in addNewBranchInt!
  1647 	// -1	add above
  1648 	//  0	add as child
  1649 	// +1	add below
  1650 	if (selection  &&  
  1651 		 (typeid(*selection) == typeid(BranchObj) || 
  1652 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1653 	{
  1654 		BranchObj *bo = (BranchObj*) selection;
  1655 		BranchObj *newbo;
  1656 		newbo=addNewBranchInt (pos-2);
  1657 
  1658 		if (newbo)
  1659 		{
  1660 			saveStateConstSelection (
  1661 				QString ("delete (\"%1\")").arg(newbo->getSelectString()),
  1662 				QString ("addBranch (%1)").arg(pos-2),
  1663 				QString ("Add new branch to %1").arg(getName(bo)));	//TODO undoCommand
  1664 
  1665 			LinkableMapObj *oldselection=selection;
  1666 
  1667 			mapCenter->reposition();
  1668 			adjustCanvasSize();
  1669 
  1670 
  1671 			if (mainWindow->autoEdit() ||
  1672 				mainWindow->autoSelectHeading() )
  1673 			{
  1674 				selection->unselect();
  1675 				selection=newbo;
  1676 				selection->select();
  1677 				if (mainWindow->autoEdit() )
  1678 					mainWindow->editHeading();
  1679 				if (!mainWindow->autoSelectHeading()
  1680 					)//&& !wasScrolled)  //FIXME wasScrolled was moved to addNewBranchInt
  1681 				{
  1682 					selection->unselect();
  1683 					selection=oldselection;
  1684 					selection->select();
  1685 				}
  1686 			}	
  1687 		}
  1688 	}	
  1689 }
  1690 
  1691 
  1692 void MapEditor::addNewBranchHere()
  1693 {
  1694 	if (selection  &&  
  1695 		 (typeid(*selection) == typeid(BranchObj) ) )
  1696 	{
  1697 		BranchObj* bo1 = (BranchObj*) selection;
  1698 		saveStatePart(selection, QString("Add new branch here").arg(getName(bo1)));
  1699 
  1700 		bool wasScrolled=false;
  1701 		BranchObj *newbo=NULL;
  1702 		BranchObj *parbo=(BranchObj*)(selection->getParObj());
  1703 		if (parbo)
  1704 		{
  1705 			// add below selection
  1706 			newbo=parbo->insertBranch(bo1->getNum()+1);
  1707 		} 
  1708 
  1709 		LinkableMapObj *oldselection=selection;
  1710 		((BranchObj*)selection)->moveBranchTo (newbo,-1);
  1711 
  1712 		mapCenter->reposition();
  1713 		adjustCanvasSize();
  1714 		if (mainWindow->autoEdit() ||
  1715 			mainWindow->autoSelectHeading() )
  1716 		{
  1717 			selection->unselect();
  1718 			selection=newbo;
  1719 			selection->select();
  1720 			if (mainWindow->autoEdit() )
  1721 				mainWindow->editHeading();
  1722 			if (!mainWindow->autoSelectHeading()
  1723 				&& !wasScrolled)
  1724 			{
  1725 				selection->unselect();
  1726 				selection=oldselection;
  1727 				selection->select();
  1728 			}
  1729 		}	
  1730 	}	
  1731 }
  1732 
  1733 void MapEditor::deleteSelection()
  1734 {
  1735 	if (selection  && typeid(*selection) ==typeid(BranchObj) ) 
  1736 	{
  1737 		BranchObj* bo=(BranchObj*)selection;
  1738 		BranchObj* par=(BranchObj*)(bo->getParObj());
  1739 		bo->unselect();
  1740 		if (selection->getDepth()>1)
  1741 			// Normal branch, save parent with childs
  1742 			saveStatePart(par,QString("Delete %1").arg(getName(bo)));
  1743 		//	naveState (UndoCom, par, QString("insertBranchAt (%1)", bo, "", QString ("Delete %1").arg(getName(bo))));
  1744 		else
  1745 			// Mainbranch, save whole map
  1746 			// TODO Better would be to insert mainbranch again at pos
  1747 			// But undoCommand is missing right now
  1748 			saveStateComplete(QString("Delete %1").arg(getName(bo)));
  1749 		selection=NULL;
  1750 		par->removeBranch(bo);
  1751 		selection=par;
  1752 		selection->select();
  1753 		ensureSelectionVisible();
  1754 		mapCenter->reposition();
  1755 		adjustCanvasSize();
  1756 	}
  1757 	if (selection  && typeid(*selection) ==typeid(FloatImageObj) ) 
  1758 	{
  1759 		FloatImageObj* fio=(FloatImageObj*)selection;
  1760 		BranchObj* par=(BranchObj*)(fio->getParObj());
  1761 		saveStatePart(par, QString("Delete %1").arg(getName(fio)));
  1762 		fio->unselect();
  1763 		selection=NULL;
  1764 		par->removeFloatImage(fio);
  1765 		selection=par;
  1766 		selection->select();
  1767 		ensureSelectionVisible();
  1768 		mapCenter->reposition();
  1769 		adjustCanvasSize();
  1770 	}
  1771 }
  1772 
  1773 LinkableMapObj* MapEditor::getSelection()
  1774 {
  1775 	return selection;
  1776 }
  1777 
  1778 void MapEditor::unselect()
  1779 {
  1780 	if (selection) 
  1781 	{
  1782 		selectionLast=selection;
  1783 		selection->unselect();
  1784 		selection=NULL;
  1785 	}
  1786 }	
  1787 
  1788 void MapEditor::reselect()
  1789 {
  1790 	if (selectionLast)
  1791 	{
  1792 		selection=selectionLast;
  1793 		selection->select();
  1794 		selectionLast=NULL;
  1795 	}
  1796 }	
  1797 
  1798 bool MapEditor::select (const QString &s)
  1799 {
  1800 	LinkableMapObj *lmo=mapCenter->findObjBySelect(s);
  1801 
  1802 	// Finally select the found object
  1803 	if (lmo)
  1804 	{
  1805 		if (selection) unselect();
  1806 		selection=lmo;
  1807 		selection->select();
  1808 		adjustCanvasSize();
  1809 		ensureSelectionVisible();
  1810 		return true;
  1811 	} 
  1812 	return false;
  1813 }
  1814 
  1815 QString MapEditor::getSelectString()
  1816 {
  1817 	if (selection) return selection->getSelectString();
  1818 	return QString();
  1819 }
  1820 
  1821 void MapEditor::selectInt (LinkableMapObj *lmo)
  1822 {
  1823 	if (lmo && selection != lmo)
  1824 	{
  1825 		// select the MapObj
  1826 		if (selection) selection->unselect();
  1827 		selection=lmo;
  1828 		selection->select();
  1829 			
  1830 		adjustCanvasSize();
  1831 	}
  1832 }
  1833 
  1834 void MapEditor::selectNextBranchInt()
  1835 {
  1836 	// Increase number of branch
  1837 	if (selection)
  1838 	{
  1839 		QString s=selection->getSelectString();
  1840 		QString part;
  1841 		QString typ;
  1842 		QString num;
  1843 
  1844 		// Where am I? 
  1845 		part=s.section(",",-1);
  1846 		typ=part.left (3);
  1847 		num=part.right(part.length() - 3);
  1848 
  1849 		s=s.left (s.length() -num.length());
  1850 
  1851 		// Go to next lmo
  1852 		num=QString ("%1").arg(num.toUInt()+1);
  1853 
  1854 		s=s+num;
  1855 		
  1856 		// Try to select this one
  1857 		if (select (s)) return;
  1858 
  1859 		// We have no direct successor, 
  1860 		// try to increase the parental number in order to
  1861 		// find a successor with same depth
  1862 
  1863 		int d=selection->getDepth();
  1864 		int oldDepth=d;
  1865 		int i;
  1866 		bool found=false;
  1867 		bool b;
  1868 		while (!found && d>0)
  1869 		{
  1870 			s=s.section (",",0,d-1);
  1871 			// replace substring of current depth in s with "1"
  1872 			part=s.section(",",-1);
  1873 			typ=part.left (3);
  1874 			num=part.right(part.length() - 3);
  1875 
  1876 			if (d>1)
  1877 			{	
  1878 				// increase number of parent
  1879 				num=QString ("%1").arg(num.toUInt()+1);
  1880 				s=s.section (",",0,d-2) + ","+ typ+num;
  1881 			} else
  1882 			{
  1883 				// Special case, look at orientation
  1884 				if (selection->getOrientation()==OrientRightOfCenter)
  1885 					num=QString ("%1").arg(num.toUInt()+1);
  1886 				else	
  1887 					num=QString ("%1").arg(num.toUInt()-1);
  1888 				s=typ+num;
  1889 			}	
  1890 
  1891 			if (select (s))
  1892 				// pad to oldDepth, select the first branch for each depth
  1893 				for (i=d;i<oldDepth;i++)
  1894 				{
  1895 					b=select (s);
  1896 					if (b)
  1897 					{	
  1898 						if ( ((BranchObj*)selection)->countBranches()>0)
  1899 							s+=",bo:0";
  1900 						else	
  1901 							break;
  1902 					} else
  1903 						break;
  1904 				}	
  1905 
  1906 			// try to select the freshly built string
  1907 			found=select(s);
  1908 			d--;
  1909 		}
  1910 		return;
  1911 	}	
  1912 }
  1913 
  1914 void MapEditor::selectPrevBranchInt()
  1915 {
  1916 	// Decrease number of branch
  1917 	if (selection)
  1918 	{
  1919 		QString s=selection->getSelectString();
  1920 		QString part;
  1921 		QString typ;
  1922 		QString num;
  1923 
  1924 		// Where am I? 
  1925 		part=s.section(",",-1);
  1926 		typ=part.left (3);
  1927 		num=part.right(part.length() - 3);
  1928 
  1929 		s=s.left (s.length() -num.length());
  1930 
  1931 		// Go to next lmo
  1932 		num=QString ("%1").arg(num.toUInt()-1);
  1933 
  1934 		s=s+num;
  1935 		
  1936 		// Try to select this one
  1937 		if (select (s)) return;
  1938 
  1939 		// We have no direct precessor, 
  1940 		// try to decrease the parental number in order to
  1941 		// find a precessor with same depth
  1942 
  1943 		int d=selection->getDepth();
  1944 		int oldDepth=d;
  1945 		int i;
  1946 		bool found=false;
  1947 		bool b;
  1948 		while (!found && d>0)
  1949 		{
  1950 			s=s.section (",",0,d-1);
  1951 			// replace substring of current depth in s with "1"
  1952 			part=s.section(",",-1);
  1953 			typ=part.left (3);
  1954 			num=part.right(part.length() - 3);
  1955 
  1956 			if (d>1)
  1957 			{
  1958 				// decrease number of parent
  1959 				num=QString ("%1").arg(num.toUInt()-1);
  1960 				s=s.section (",",0,d-2) + ","+ typ+num;
  1961 			} else
  1962 			{
  1963 				// Special case, look at orientation
  1964 				if (selection->getOrientation()==OrientRightOfCenter)
  1965 					num=QString ("%1").arg(num.toUInt()-1);
  1966 				else	
  1967 					num=QString ("%1").arg(num.toUInt()+1);
  1968 				s=typ+num;
  1969 			}	
  1970 
  1971 			if (select(s))
  1972 				// pad to oldDepth, select the last branch for each depth
  1973 				for (i=d;i<oldDepth;i++)
  1974 				{
  1975 					b=select (s);
  1976 					if (b)
  1977 						if ( ((BranchObj*)selection)->countBranches()>0)
  1978 							s+=",bo:"+ QString ("%1").arg( ((BranchObj*)selection)->countBranches()-1 );
  1979 						else	
  1980 							break;
  1981 					else
  1982 						break;
  1983 				}	
  1984 			
  1985 			// try to select the freshly built string
  1986 			found=select(s);
  1987 			d--;
  1988 		}
  1989 		return;
  1990 	}	
  1991 }
  1992 
  1993 void MapEditor::selectUpperBranch()
  1994 {
  1995 	if (selection) 
  1996 	{
  1997 		if (typeid(*selection) == typeid(BranchObj))
  1998 		{
  1999 			if (selection->getOrientation()==OrientRightOfCenter)
  2000 				selectPrevBranchInt();
  2001 			else
  2002 				if (selection->getDepth()==1)
  2003 					selectNextBranchInt();
  2004 				else
  2005 					selectPrevBranchInt();
  2006 		}		
  2007 	}
  2008 }
  2009 
  2010 void MapEditor::selectLowerBranch()
  2011 {
  2012 	if (selection) 
  2013 	{
  2014 		if (typeid(*selection) == typeid(BranchObj))
  2015 		{
  2016 			if (selection->getOrientation()==OrientRightOfCenter)
  2017 				selectNextBranchInt();
  2018 			else
  2019 				if (selection->getDepth()==1)
  2020 					selectPrevBranchInt();
  2021 				else
  2022 					selectNextBranchInt();
  2023 		}		
  2024 	}
  2025 }
  2026 
  2027 
  2028 void MapEditor::selectLeftBranch()
  2029 {
  2030 	BranchObj* bo;
  2031 	BranchObj* par;
  2032 	if (selection) 
  2033 	{
  2034 		if (typeid(*selection) == typeid(MapCenterObj))
  2035 		{
  2036 			par=  (BranchObj*) selection;
  2037 			bo=par->getLastSelectedBranch();
  2038 			if (bo)
  2039 			{
  2040 				// Workaround for reselecting on left and right side
  2041 				if (bo->getOrientation()==OrientRightOfCenter)
  2042 				{
  2043 					bo=par->getLastBranch();
  2044 				}	
  2045 				if (bo)
  2046 				{
  2047 					par->unselect();
  2048 					selection=bo;
  2049 					selection->select();
  2050 					adjustCanvasSize();
  2051 					ensureSelectionVisible();
  2052 				}
  2053 			}	
  2054 		} else
  2055 		{
  2056 			par=(BranchObj*)(selection->getParObj());
  2057 			if (selection->getOrientation()==OrientRightOfCenter)
  2058 			{
  2059 				if (typeid(*selection) == typeid(BranchObj) ||
  2060 					typeid(*selection) == typeid(FloatImageObj))
  2061 				{
  2062 					selection->unselect();
  2063 					selection=par;
  2064 					selection->select();
  2065 					adjustCanvasSize();
  2066 					ensureSelectionVisible();
  2067 				}
  2068 			} else
  2069 			{
  2070 				if (typeid(*selection) == typeid(BranchObj) )
  2071 				{
  2072 					bo=((BranchObj*)selection)->getLastSelectedBranch();
  2073 					if (bo) 
  2074 					{
  2075 						selection->unselect();
  2076 						selection=bo;
  2077 						selection->select();
  2078 						adjustCanvasSize();
  2079 						ensureSelectionVisible();
  2080 					}
  2081 				}
  2082 			}
  2083 		}	
  2084 	}
  2085 }
  2086 
  2087 void MapEditor::selectRightBranch()
  2088 {
  2089 	BranchObj* bo;
  2090 	BranchObj* par;
  2091 
  2092 	if (selection) 
  2093 	{
  2094 		if (typeid(*selection) == typeid(MapCenterObj))
  2095 		{
  2096 			par=  (BranchObj*) selection;
  2097 			bo=par->getLastSelectedBranch();
  2098 			if (bo)
  2099 			{
  2100 				// Workaround for reselecting on left and right side
  2101 				if (bo->getOrientation()==OrientLeftOfCenter)
  2102 					bo=par->getFirstBranch();
  2103 				if (bo)
  2104 				{
  2105 					par->unselect();
  2106 					selection=bo;
  2107 					selection->select();
  2108 					ensureSelectionVisible();
  2109 				}
  2110 			}
  2111 		} else
  2112 		{
  2113 			par=(BranchObj*)(selection->getParObj());
  2114 			if (selection->getOrientation()==OrientLeftOfCenter)
  2115 			{
  2116 				if (typeid(*selection) == typeid(BranchObj) ||
  2117 					typeid(*selection) == typeid(FloatImageObj))
  2118 				{
  2119 					selection->unselect();
  2120 					selection=par;
  2121 					selection->select();
  2122 					adjustCanvasSize();
  2123 					ensureSelectionVisible();
  2124 				}
  2125 			} else
  2126 			{
  2127 				if (typeid(*selection) == typeid(BranchObj) )
  2128 				{
  2129 					bo=((BranchObj*)selection)->getLastSelectedBranch();
  2130 					if (bo) 
  2131 					{
  2132 						selection->unselect();
  2133 						selection=bo;
  2134 						selection->select();
  2135 						adjustCanvasSize();
  2136 						ensureSelectionVisible();
  2137 					}
  2138 				}
  2139 			}
  2140 		}
  2141 	}
  2142 }
  2143 
  2144 void MapEditor::selectFirstBranch()
  2145 {
  2146 	BranchObj *bo1;
  2147 	BranchObj *bo2;
  2148 	BranchObj* par;
  2149 	if (selection) {
  2150 		if (typeid(*selection) == typeid(BranchObj))
  2151 		{
  2152 			bo1=  (BranchObj*) selection;
  2153 			par=(BranchObj*)(bo1->getParObj());
  2154 			bo2=par->getFirstBranch();
  2155 			if (bo2) {
  2156 				bo1->unselect();
  2157 				selection=bo2;
  2158 				selection->select();
  2159 				ensureSelectionVisible();
  2160 			}
  2161 		}		
  2162 		adjustCanvasSize();
  2163 	}
  2164 }
  2165 
  2166 void MapEditor::selectLastBranch()
  2167 {
  2168 	BranchObj *bo1;
  2169 	BranchObj *bo2;
  2170 	BranchObj* par;
  2171 	if (selection) {
  2172 		if (typeid(*selection) == typeid(BranchObj))
  2173 		{
  2174 			bo1=  (BranchObj*) selection;
  2175 			par=(BranchObj*)(bo1->getParObj());
  2176 			bo2=par->getLastBranch();
  2177 			if (bo2) {
  2178 				bo1->unselect();
  2179 				selection=bo2;
  2180 				selection->select();
  2181 				ensureSelectionVisible();
  2182 			}
  2183 		}		
  2184 		adjustCanvasSize();
  2185 	}
  2186 }
  2187 
  2188 void MapEditor::setColor(QColor c)
  2189 {
  2190 	actColor=c;
  2191 }
  2192 
  2193 void MapEditor::selectBackgroundColor()
  2194 {
  2195 	QColor col = QColorDialog::getColor( mapCanvas->backgroundColor(), this );
  2196 	if ( !col.isValid() ) return;
  2197 	setBackgroundColor( col );
  2198 	//TODO undocomm
  2199 	saveStateComplete(QString("Set background color of map to %1").arg(col.name()));
  2200 }
  2201 
  2202 void MapEditor::setBackgroundColor(QColor c)
  2203 {
  2204 	mapCanvas->setBackgroundColor (c);
  2205 }
  2206 
  2207 QColor MapEditor::pickColor()
  2208 {
  2209 	if (selection) 
  2210 	{
  2211 		if (typeid(*selection) == typeid(BranchObj) ||
  2212 			typeid(*selection) == typeid(MapCenterObj))
  2213 		{
  2214 			BranchObj *bo=(BranchObj*)selection;
  2215 			actColor=bo->getColor(); 
  2216 		}    
  2217 	}
  2218 	return actColor;
  2219 }
  2220 
  2221 void MapEditor::colorItem()
  2222 {
  2223 	if (selection) 
  2224 	{
  2225 		if (typeid(*selection) == typeid(BranchObj) ||
  2226 			typeid(*selection) == typeid(MapCenterObj))
  2227 		{
  2228 			BranchObj *bo=(BranchObj*)selection;
  2229 			saveStatePart(selection, QString("Set color of %1 to %2").arg(getName(bo)).arg(actColor.name()));	//TODO undoCommand
  2230 			bo->setColor(actColor); // color branch
  2231 		}    
  2232 	}
  2233 }
  2234 
  2235 void MapEditor::colorBranch()
  2236 {
  2237 	if (selection) 
  2238 	{
  2239 		if (typeid(*selection) == typeid(BranchObj) ||
  2240 			typeid(*selection) == typeid(MapCenterObj))
  2241 		{
  2242 			BranchObj *bo=(BranchObj*)selection;
  2243 			saveStatePart(selection, QString ("Set color of %1 and childs to %2").arg(getName(bo)).arg(actColor.name()));	//TODO undoCommand
  2244 			bo->setColorChilds(actColor); // color links, color childs
  2245 		}    
  2246 	}
  2247 }
  2248 
  2249 
  2250 void MapEditor::toggleStandardFlag(QString f)
  2251 {
  2252 	if (selection)
  2253 	{
  2254 		if (typeid(*selection) == typeid(BranchObj) ||
  2255 			typeid(*selection) == typeid(MapCenterObj))
  2256 		{
  2257 			BranchObj *bo=(BranchObj*)selection;
  2258 			QString u,r;
  2259 			if (bo->isSetStandardFlag(f))
  2260 			{
  2261 				r="unsetFlag";
  2262 				u="setFlag";
  2263 			}	
  2264 			else
  2265 			{
  2266 				u="unsetFlag";
  2267 				r="setFlag";
  2268 			}	
  2269 			saveStateConstSelection(QString("%1 (\"%2\")").arg(u).arg(f), 
  2270 				QString("%1 (\"%2\")").arg(r).arg(f),
  2271 				QString("Toggling standard flag \"%1\" of %2").arg(f).arg(getName(bo)));
  2272 			bo->toggleStandardFlag (f,mainWindow->useFlagGroups());
  2273 			adjustCanvasSize();
  2274 		}
  2275 	}	
  2276 }
  2277 
  2278 void MapEditor::setViewCenter()
  2279 {
  2280 	// transform to CanvasView Coord:
  2281 	QPoint p=worldMatrix().map(movingCenter);
  2282 	center ( p.x(), p.y());
  2283 }
  2284 
  2285 
  2286 BranchObj* MapEditor::findText (QString s, bool cs)
  2287 {
  2288 	QTextDocument::FindFlags flags=0;
  2289 	if (cs) flags=QTextDocument::FindCaseSensitively;
  2290 
  2291 	if (!itFind) 
  2292 	{	// Nothing found or new find process
  2293 		if (EOFind)
  2294 			// nothing found, start again
  2295 			EOFind=false;
  2296 		itFind=mapCenter->first();
  2297 	}	
  2298 	bool searching=true;
  2299 	bool foundNote=false;
  2300 	while (searching && !EOFind)
  2301 	{
  2302 		if (itFind)
  2303 		{
  2304 			// Searching in Note
  2305 			if (itFind->getNote().contains(s,cs))
  2306 			{
  2307 				if (selection!=itFind) 
  2308 				{
  2309 					if (selection) ((BranchObj*)selection)->unselect();
  2310 					selection=itFind;
  2311 					selection->select();
  2312 					adjustCanvasSize();
  2313 					ensureSelectionVisible();
  2314 				}
  2315 				if (textEditor->findText(s,flags)) 
  2316 				{
  2317 					searching=false;
  2318 					foundNote=true;
  2319 				}	
  2320 			}
  2321 			// Searching in Heading
  2322 			if (searching && itFind->getHeading().contains (s,cs) ) 
  2323 			{
  2324 				if (selection) ((BranchObj*)selection)->unselect();
  2325 				selection=itFind;
  2326 				selection->select();
  2327 				adjustCanvasSize();
  2328 				ensureSelectionVisible();
  2329 				searching=false;
  2330 			}
  2331 		}	
  2332 		if (!foundNote)
  2333 		{
  2334 			itFind=itFind->next();
  2335 			if (!itFind) EOFind=true;
  2336 		}
  2337 	}	
  2338 	if (!searching)
  2339 	{
  2340 		adjustCanvasSize();
  2341 		return (BranchObj*)selection;
  2342 	}	else
  2343 		return NULL;
  2344 }
  2345 
  2346 void MapEditor::findReset()
  2347 {	// Necessary if text to find changes during a find process
  2348 	itFind=NULL;
  2349 	EOFind=false;
  2350 }
  2351 
  2352 void MapEditor::editURL()
  2353 {
  2354 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2355 			typeid(*selection) == typeid(MapCenterObj)) )
  2356 	{		
  2357 		bool ok;
  2358 		BranchObj *bo=(BranchObj*)selection;
  2359 		QString text = QInputDialog::getText(
  2360 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2361 				bo->getURL(), &ok, this );
  2362 		if ( ok) 
  2363 		{
  2364 			// user entered something and pressed OK
  2365 			saveStateConstSelection("setURL (\""+bo->getURL()+"\")","setURL (\""+text+"\")", QString("Set URL of %1 to %21").arg(getName(bo)).arg(text));	
  2366 			bo->setURL (text);
  2367 			updateActions();
  2368 		}	
  2369 	}
  2370 }
  2371 
  2372 QString MapEditor::getURL()
  2373 {
  2374 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2375 			typeid(*selection) == typeid(MapCenterObj)) )
  2376 		return ((BranchObj*)selection)->getURL();
  2377 	else
  2378 		return "";
  2379 }
  2380 
  2381 QStringList MapEditor::getURLs()
  2382 {
  2383 	QStringList urls;
  2384 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2385 			typeid(*selection) == typeid(MapCenterObj)) )
  2386 	{		
  2387 		BranchObj *bo=(BranchObj*)selection;
  2388 		bo=bo->first();	
  2389 		while (bo) 
  2390 		{
  2391 			if (!bo->getURL().isEmpty()) urls.append( bo->getURL());
  2392 			bo=bo->next();
  2393 		}	
  2394 	}	
  2395 	return urls;
  2396 }
  2397 
  2398 
  2399 void MapEditor::editHeading2URL()
  2400 {
  2401 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2402 			typeid(*selection) == typeid(MapCenterObj)) )
  2403 	{		
  2404 		BranchObj *bo=(BranchObj*)selection;
  2405 		saveStateConstSelection("setURL (\""+bo->getURL()+"\")","setURL (\""+bo->getHeading()+"\")",QString("Copy heading of %1 to URL").arg(getName(bo)));	
  2406 		bo->setURL (bo->getHeading());
  2407 		updateActions();
  2408 	}
  2409 }	
  2410 
  2411 void MapEditor::editBugzilla2URL()
  2412 {
  2413 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2414 			typeid(*selection) == typeid(MapCenterObj)) )
  2415 	{		
  2416 		BranchObj *bo=(BranchObj*)selection;
  2417 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
  2418 		saveStateConstSelection("setURL (\""+bo->getURL()+"\")","setURL (\""+url+"\")",QString("Use heading of %1 as link to Novell Bugzilla").arg(getName(bo)));	
  2419 		bo->setURL (url);
  2420 		updateActions();
  2421 	}
  2422 }	
  2423 
  2424 void MapEditor::editFATE2URL()
  2425 {
  2426 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2427 			typeid(*selection) == typeid(MapCenterObj)) )
  2428 	{		
  2429 		BranchObj *bo=(BranchObj*)selection;
  2430 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
  2431 		saveStateConstSelection("setURL (\""+bo->getURL()+"\")","setURL (\""+url+"\")",QString("Use heading of %1 as link to FATE").arg(getName(bo)));	
  2432 		bo->setURL (url);
  2433 		updateActions();
  2434 	}
  2435 }	
  2436 
  2437 void MapEditor::editVymLink()
  2438 {
  2439 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2440 			typeid(*selection) == typeid(MapCenterObj)) )
  2441 	{		
  2442 		BranchObj *bo=(BranchObj*)selection;
  2443 		Q3FileDialog *fd=new Q3FileDialog( this,__VYM " - " +tr("Link to another map"));
  2444 		fd->addFilter (QString (tr("vym map") + " (*.vym)"));
  2445 		fd->setCaption(__VYM " - " +tr("Link to another map"));
  2446 		if (! bo->getVymLink().isEmpty() )
  2447 			fd->setSelection( bo->getVymLink() );
  2448 		fd->show();
  2449 
  2450 		QString fn;
  2451 		if ( fd->exec() == QDialog::Accepted )
  2452 		{
  2453 			saveStateConstSelection("setVymLink (\""+bo->getVymLink()+"\")","setVymLink (\""+fd->selectedFile()+"\")",QString("Set vymlink of %1 to %2").arg(getName(bo)).arg(fd->selectedFile()));	
  2454 			bo->setVymLink (fd->selectedFile() );
  2455 			updateActions();
  2456 			mapCenter->reposition();
  2457 			adjustCanvasSize();
  2458 			canvas()->update();
  2459 		}
  2460 	}
  2461 }
  2462 
  2463 void MapEditor::deleteVymLink()
  2464 {
  2465 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2466 			typeid(*selection) == typeid(MapCenterObj)) )
  2467 	{		
  2468 		BranchObj *bo=(BranchObj*)selection;
  2469 		saveStateConstSelection("setVymLink (\""+bo->getVymLink()+"\")","setVymLink (\"\")",QString("Unset vymlink of %1").arg(getName(bo)));	
  2470 		bo->setVymLink ("" );
  2471 		updateActions();
  2472 		mapCenter->reposition();
  2473 		adjustCanvasSize();
  2474 		canvas()->update();
  2475 	}
  2476 }
  2477 
  2478 void MapEditor::toggleHideExport()
  2479 {
  2480 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2481 			typeid(*selection) == typeid(MapCenterObj)) ||
  2482 			(typeid(*selection)==typeid(FloatImageObj))
  2483 			)
  2484 	{		
  2485 		OrnamentedObj *oo=(OrnamentedObj*)selection;
  2486 		QString s;
  2487 		if (oo->hideInExport())
  2488 		{
  2489 			oo->setHideInExport(false);
  2490 			s="Unset";
  2491 		}	
  2492 		else	
  2493 		{
  2494 			oo->setHideInExport(true);
  2495 			s="Set";
  2496 		}	
  2497 		saveStateComplete(QString ("%1 hide export flag of %2").arg(s).arg(getName(selection)));	//TODO undoCommand
  2498 		updateActions();
  2499 		mapCenter->reposition();
  2500 		adjustCanvasSize();
  2501 		canvas()->update();
  2502 	}
  2503 }
  2504 
  2505 QString MapEditor::getVymLink()
  2506 {
  2507 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2508 			typeid(*selection) == typeid(MapCenterObj)) )
  2509 	{		
  2510 		return ((BranchObj*)selection)->getVymLink();
  2511 	}
  2512 	return "";
  2513 	
  2514 }
  2515 
  2516 QStringList MapEditor::getVymLinks()
  2517 {
  2518 	QStringList links;
  2519 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2520 			typeid(*selection) == typeid(MapCenterObj)) )
  2521 	{		
  2522 		BranchObj *bo=(BranchObj*)selection;
  2523 		bo=bo->first();	
  2524 		while (bo) 
  2525 		{
  2526 			if (!bo->getVymLink().isEmpty()) links.append( bo->getVymLink());
  2527 			bo=bo->next();
  2528 		}	
  2529 	}	
  2530 	return links;
  2531 }
  2532 
  2533 
  2534 void MapEditor::removeBranchKeepChilds()
  2535 {
  2536 	if (selection && (typeid(*selection) == typeid(BranchObj) ))
  2537 	{		
  2538 		BranchObj* bo=(BranchObj*)selection;
  2539 		BranchObj* par=(BranchObj*)(bo->getParObj());
  2540 		QString s=QString("Remove %1 and keep its childs").arg(getName(bo));
  2541 		if (bo->getDepth()==1)
  2542 			saveStateComplete(s);
  2543 		else	
  2544 			saveStatePart(selection->getParObj(),s);	// TODO undoCommand
  2545 		QString sel=selection->getSelectString();
  2546 		unselect();
  2547 		par->removeBranchHere(bo);
  2548 		mapCenter->reposition();
  2549 		select (sel);
  2550 	}	
  2551 }
  2552 
  2553 void MapEditor::removeChilds()
  2554 {
  2555 	if (selection && (typeid(*selection) == typeid(BranchObj) ))
  2556 	{		
  2557 		saveStatePart(selection->getParObj(), QString("Remove childs of branch %1").arg(getName(selection)));
  2558 		((BranchObj*)selection)->removeChilds();
  2559 		mapCenter->reposition();
  2560 	}	
  2561 }
  2562 
  2563 void MapEditor::editMapInfo()
  2564 {
  2565 	ExtraInfoDialog dia;
  2566 	dia.setMapName (getFileName() );
  2567 	dia.setAuthor (mapCenter->getAuthor() );
  2568 	dia.setComment(mapCenter->getComment() );
  2569 
  2570 	// Calc some stats
  2571 	QString stats;
  2572     int i=0;
  2573     Q3CanvasItemList l=canvas()->allItems();
  2574     for (Q3CanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) 
  2575         i++;
  2576     stats+=QString ("%1 items on canvas\n").arg (i,6);
  2577 
  2578 	uint b=0;
  2579 	uint f=0;
  2580 	uint n=0;
  2581 	uint xl=0;
  2582 	BranchObj *bo;
  2583 	bo=mapCenter->first();
  2584 	while (bo) 
  2585 	{
  2586 		if (!bo->getNote().isEmpty() ) n++;
  2587 		f+= bo->countFloatImages();
  2588 		b++;
  2589 		xl+=bo->countXLinks();
  2590 		bo=bo->next();
  2591 	}
  2592     stats+=QString ("%1 branches\n").arg (b-1,6);
  2593     stats+=QString ("%1 xLinks \n").arg (xl,6);
  2594     stats+=QString ("%1 notes\n").arg (n,6);
  2595     stats+=QString ("%1 images\n").arg (f,6);
  2596 	dia.setStats (stats);
  2597 
  2598 	// Finally show dialog
  2599 	if (dia.exec() == QDialog::Accepted)
  2600 	{
  2601 		saveStateComplete("Edit info about map");	//TODO undoCommand
  2602 		mapCenter->setAuthor (dia.getAuthor() );
  2603 		mapCenter->setComment (dia.getComment() );
  2604 	}
  2605 }
  2606 
  2607 void MapEditor::updateActions()
  2608 {
  2609 	mainWindow->updateActions();
  2610 	// FIXME maybe don't update if blockReposition is set
  2611 }
  2612 
  2613 void MapEditor::updateNoteFlag()
  2614 {
  2615 	if (selection)
  2616 		if ( (typeid(*selection) == typeid(BranchObj)) || 
  2617 			(typeid(*selection) == typeid(MapCenterObj))  )
  2618 			((BranchObj*)selection)->updateNoteFlag();
  2619 }
  2620 
  2621 void MapEditor::setLinkStyle (LinkStyle ls)
  2622 {
  2623 	linkstyle=ls;
  2624 
  2625 	saveStateComplete("Set link style");	// TODO undoCommand
  2626 	BranchObj *bo;
  2627 	bo=mapCenter->first();
  2628 	bo=bo->next();
  2629 	while (bo) 
  2630 	{
  2631 		bo->setLinkStyle(bo->getDefLinkStyle());
  2632 		bo=bo->next();
  2633 	}
  2634 	mapCenter->reposition();
  2635 }
  2636 
  2637 LinkStyle MapEditor::getLinkStyle ()
  2638 {
  2639 	return linkstyle;
  2640 }	
  2641 
  2642 void MapEditor::setLinkColor(QColor c)
  2643 {
  2644 	defLinkColor=c;
  2645 	updateActions();
  2646 }
  2647 
  2648 void MapEditor::setLinkColorHint()
  2649 {
  2650 	// called from setLinkColorHint(lch) or at end of parse
  2651 	BranchObj *bo;
  2652 	bo=mapCenter->first();
  2653 	while (bo) 
  2654 	{
  2655 		bo->setLinkColor();
  2656 		bo=bo->next();
  2657 	}
  2658 }
  2659 
  2660 void MapEditor::setLinkColorHint(LinkColorHint lch)
  2661 {
  2662 	linkcolorhint=lch;
  2663 	setLinkColorHint();
  2664 }
  2665 
  2666 void MapEditor::toggleLinkColorHint()
  2667 {
  2668 	if (linkcolorhint==HeadingColor)
  2669 		linkcolorhint=DefaultColor;
  2670 	else	
  2671 		linkcolorhint=HeadingColor;
  2672 	BranchObj *bo;
  2673 	bo=mapCenter->first();
  2674 	while (bo) 
  2675 	{
  2676 		bo->setLinkColor();
  2677 		bo=bo->next();
  2678 	}
  2679 }
  2680 
  2681 LinkColorHint MapEditor::getLinkColorHint()
  2682 {
  2683 	return linkcolorhint;
  2684 }
  2685 
  2686 QColor MapEditor::getDefLinkColor()
  2687 {
  2688 	return defLinkColor;
  2689 }
  2690 
  2691 void MapEditor::setDefXLinkColor(QColor col)
  2692 {
  2693 	defXLinkColor=col;
  2694 }
  2695 
  2696 QColor MapEditor::getDefXLinkColor()
  2697 {
  2698 	return defXLinkColor;
  2699 }
  2700 
  2701 void MapEditor::setDefXLinkWidth (int w)
  2702 {
  2703 	defXLinkWidth=w;
  2704 }
  2705 
  2706 int MapEditor::getDefXLinkWidth()
  2707 {
  2708 	return defXLinkWidth;
  2709 }
  2710 
  2711 void MapEditor::selectLinkColor()
  2712 {
  2713 	QColor col = QColorDialog::getColor( defLinkColor, this );
  2714 	if ( !col.isValid() ) return;
  2715 	setLinkColor( col );
  2716 	saveStateComplete(QString("Set link color to %1").arg(col.name()));	//TODO undoCommand
  2717 
  2718 }
  2719 
  2720 void MapEditor::toggleScroll()
  2721 {
  2722 	if (selection && (typeid(*selection) == typeid(BranchObj)) )
  2723 	{
  2724 		BranchObj *bo=((BranchObj*)selection);
  2725 		if (bo->countBranches()==0) return;
  2726 		if (bo->getDepth()==0) return;
  2727 		QString s;
  2728 		if (bo->isScrolled())
  2729 			s="Unscroll";
  2730 		else	
  2731 			s="Scroll";
  2732 		saveStatePart(selection, QString ("%1 %2").arg(s).arg(getName(bo)));
  2733 		bo->toggleScroll();
  2734 		adjustCanvasSize();
  2735 		canvas()->update();
  2736 	}
  2737 }
  2738 
  2739 void MapEditor::unScrollAll()
  2740 {
  2741 	BranchObj *bo;
  2742 	bo=mapCenter->first();
  2743 	while (bo) 
  2744 	{
  2745 		if (bo->isScrolled()) bo->toggleScroll();
  2746 		bo=bo->next();
  2747 	}
  2748 }
  2749 
  2750 void MapEditor::loadFloatImage ()
  2751 {
  2752 	if (selection && 
  2753 		(typeid(*selection) == typeid(BranchObj)) || 
  2754 		(typeid(*selection) == typeid(MapCenterObj))  )
  2755 	{
  2756 		BranchObj *bo=((BranchObj*)selection);
  2757 
  2758 		Q3FileDialog *fd=new Q3FileDialog( this);
  2759 		fd->setMode (Q3FileDialog::ExistingFiles);
  2760 		fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  2761 		ImagePreview *p =new ImagePreview (fd);
  2762 		fd->setContentsPreviewEnabled( TRUE );
  2763 		fd->setContentsPreview( p, p );
  2764 		fd->setPreviewMode( Q3FileDialog::Contents );
  2765 		fd->setCaption(__VYM " - " +tr("Load image"));
  2766 		fd->setDir (lastImageDir);
  2767 		fd->show();
  2768 
  2769 		QString fn;
  2770 		if ( fd->exec() == QDialog::Accepted )
  2771 		{
  2772 			saveStatePart(selection, QString("Add floatimage to %1").arg(getName(selection)));
  2773 			// FIXME in QT4 use:	lastImageDir=fd->directory();
  2774 			lastImageDir=QDir (fd->dirPath());
  2775 			QStringList flist = fd->selectedFiles();
  2776 			QStringList::Iterator it = flist.begin();
  2777 			while( it != flist.end() ) 
  2778 			{
  2779 				fn = *it;
  2780 				bo->addFloatImage();
  2781 				// TODO check if load was successful
  2782 				bo->getLastFloatImage()->load(*it);
  2783 				bo->getLastFloatImage()->setOriginalFilename(fn);
  2784 				++it;
  2785 			}
  2786 
  2787 			mapCenter->reposition();
  2788 			adjustCanvasSize();
  2789 			canvas()->update();
  2790 		}
  2791 		delete (p);
  2792 		delete (fd);
  2793 	}
  2794 }
  2795 
  2796 void MapEditor::saveFloatImage ()
  2797 {
  2798 	if (selection && 
  2799 		(typeid(*selection) == typeid(FloatImageObj)) )
  2800 	{
  2801 		FloatImageObj *fio=((FloatImageObj*)selection);
  2802 		QFileDialog *fd=new QFileDialog( this);
  2803 		fd->setFilters (imageIO.getFilters());
  2804 		fd->setCaption(__VYM " - " +tr("Save image"));
  2805 		fd->setFileMode( QFileDialog::AnyFile );
  2806 		fd->setDirectory (lastImageDir);
  2807 //		fd->setSelection (fio->getOriginalFilename());
  2808 		fd->show();
  2809 
  2810 		QString fn;
  2811 		if ( fd->exec() == QDialog::Accepted )
  2812 		{
  2813 			if (QFile (fd->selectedFile()).exists() )
  2814 			{
  2815 				QMessageBox mb( __VYM,
  2816 					tr("The file %1 exists already.\n"
  2817 					"Do you want to overwrite it?").arg(fd->selectedFile()),
  2818 				QMessageBox::Warning,
  2819 				QMessageBox::Yes | QMessageBox::Default,
  2820 				QMessageBox::Cancel | QMessageBox::Escape,
  2821 				QMessageBox::QMessageBox::NoButton );
  2822 
  2823 				mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
  2824 				mb.setButtonText( QMessageBox::No, tr("Cancel"));
  2825 				switch( mb.exec() ) 
  2826 				{
  2827 					case QMessageBox::Yes:
  2828 						// save 
  2829 						break;;
  2830 					case QMessageBox::Cancel:
  2831 						// do nothing
  2832 						delete (fd);
  2833 						return;
  2834 						break;
  2835 				}
  2836 			}
  2837 			fio->save (fd->selectedFile(),imageIO.getType (fd->selectedFilter() ) );
  2838 		}
  2839 		delete (fd);
  2840 	}
  2841 }
  2842 
  2843 void MapEditor::setFrame(const FrameType &t)
  2844 {
  2845 	if (selection && 
  2846 		(typeid(*selection) == typeid(BranchObj)) || 
  2847 		(typeid(*selection) == typeid(MapCenterObj))  )
  2848 	{
  2849 		selection->setFrameType (t);
  2850 		mapCenter->reposition();
  2851 		selection->updateLink();
  2852 	}
  2853 }
  2854 
  2855 void MapEditor::setIncludeImagesVer(bool b)
  2856 {
  2857 	if (selection && 
  2858 		(typeid(*selection) == typeid(BranchObj)) || 
  2859 		(typeid(*selection) == typeid(MapCenterObj))  )
  2860 		((BranchObj*)selection)->setIncludeImagesVer(b);
  2861 		mapCenter->reposition();
  2862 }
  2863 
  2864 void MapEditor::setIncludeImagesHor(bool b)
  2865 {
  2866 	if (selection && 
  2867 		(typeid(*selection) == typeid(BranchObj)) || 
  2868 		(typeid(*selection) == typeid(MapCenterObj))  )
  2869 		((BranchObj*)selection)->setIncludeImagesHor(b);
  2870 		mapCenter->reposition();
  2871 }
  2872 
  2873 void MapEditor::setHideLinkUnselected (bool b)
  2874 {
  2875 	if (selection && 
  2876 		(typeid(*selection) == typeid(BranchObj)) || 
  2877 		(typeid(*selection) == typeid(MapCenterObj))  ||
  2878 		(typeid(*selection) == typeid(FloatImageObj)) )
  2879 		selection->setHideLinkUnselected(b);
  2880 }
  2881 
  2882 void MapEditor::importDirInt(BranchObj *dst, QDir d)
  2883 {
  2884 	if (selection && 
  2885 		(typeid(*selection) == typeid(BranchObj)) || 
  2886 		(typeid(*selection) == typeid(MapCenterObj))  )
  2887 	{
  2888 		BranchObj *bo;
  2889 		
  2890 		// Traverse directories
  2891 		d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
  2892 		QFileInfoList list = d.entryInfoList();
  2893 		QFileInfo fi;
  2894 
  2895 		for (int i = 0; i < list.size(); ++i) 
  2896 		{
  2897 			fi=list.at(i);
  2898 			if (fi.fileName() != "." && fi.fileName() != ".." )
  2899 			{
  2900 				dst->addBranch();
  2901 				bo=dst->getLastBranch();
  2902 				bo->setHeading (fi.fileName() );
  2903 				bo->setColor (QColor("blue"));
  2904 				bo->toggleScroll();
  2905 				if ( !d.cd(fi.fileName()) ) 
  2906 					QMessageBox::critical (0,tr("Critical Import Error"),tr("Cannot find the directory %1").arg(fi.fileName()));
  2907 				else 
  2908 				{
  2909 					// Recursively add subdirs
  2910 					importDirInt (bo,d);
  2911 					d.cdUp();
  2912 				}
  2913 			}	
  2914 		}		
  2915 		// Traverse files
  2916 		d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
  2917 		list = d.entryInfoList();
  2918 
  2919 		for (int i = 0; i < list.size(); ++i) 
  2920 		{
  2921 			fi=list.at(i);
  2922 			dst->addBranch();
  2923 			bo=dst->getLastBranch();
  2924 			bo->setHeading (fi.fileName() );
  2925 			bo->setColor (QColor("black"));
  2926 			if (fi.fileName().right(4) == ".vym" )
  2927 				bo->setVymLink (fi.filePath());
  2928 		}	
  2929 	}		
  2930 }
  2931 
  2932 void MapEditor::importDir()
  2933 {
  2934 	if (selection && 
  2935 		(typeid(*selection) == typeid(BranchObj)) || 
  2936 		(typeid(*selection) == typeid(MapCenterObj))  )
  2937 	{
  2938 		Q3FileDialog *fd=new Q3FileDialog( this,__VYM " - " +tr("Choose directory structure to import"));
  2939 		fd->setMode (Q3FileDialog::DirectoryOnly);
  2940 		fd->addFilter (QString (tr("vym map") + " (*.vym)"));
  2941 		fd->setCaption(__VYM " - " +tr("Choose directory structure to import"));
  2942 		fd->show();
  2943 
  2944 		QString fn;
  2945 		if ( fd->exec() == QDialog::Accepted )
  2946 		{
  2947 			BranchObj *bo=((BranchObj*)selection);
  2948 			importDirInt (bo,QDir(fd->selectedFile()) );
  2949 			mapCenter->reposition();
  2950 			adjustCanvasSize();
  2951 			canvas()->update();
  2952 		}
  2953 	}	
  2954 }
  2955 
  2956 void MapEditor::followXLink(int i)
  2957 {
  2958 	if (selection && 
  2959 		(typeid(*selection) == typeid(BranchObj)) || 
  2960 		(typeid(*selection) == typeid(MapCenterObj))  )
  2961 	{
  2962 		BranchObj *bo=((BranchObj*)selection)->XLinkTargetAt(i);
  2963 		if (bo) 
  2964 		{
  2965 			selection->unselect();
  2966 			selection=bo;
  2967 			selection->select();
  2968 			ensureSelectionVisible();
  2969 		}
  2970 	}
  2971 }
  2972 
  2973 void MapEditor::editXLink(int i)
  2974 {
  2975 	if (selection && 
  2976 		(typeid(*selection) == typeid(BranchObj)) || 
  2977 		(typeid(*selection) == typeid(MapCenterObj))  )
  2978 	{
  2979 		XLinkObj *xlo=((BranchObj*)selection)->XLinkAt(i);
  2980 		if (xlo) 
  2981 		{
  2982 			EditXLinkDialog dia;
  2983 			dia.setXLink (xlo);
  2984 			dia.setSelection(selection);
  2985 			if (dia.exec() == QDialog::Accepted)
  2986 			{
  2987 				if (dia.useSettingsGlobal() )
  2988 				{
  2989 					setDefXLinkColor (xlo->getColor() );
  2990 					setDefXLinkWidth (xlo->getWidth() );
  2991 				}
  2992 				if (dia.deleteXLink())
  2993 					((BranchObj*)selection)->deleteXLinkAt(i);
  2994 				saveStateComplete("Edit xLink");	//TODO undoCommand
  2995 			}
  2996 		}	
  2997 	}
  2998 }
  2999 
  3000 void MapEditor::testFunction()
  3001 {
  3002 	cout << "MapEditor::testFunction() called\n";
  3003 
  3004 	WarningDialog dia;
  3005 	dia.showCancelButton (true);
  3006 	dia.setText("This is a longer \nWarning");
  3007 	/*
  3008 	dia.setCaption("Warning: Flux problem");
  3009 	dia.setShowAgainName("/warnings/mapeditor");
  3010 	*/
  3011 	if (dia.exec()==QDialog::Accepted)
  3012 		cout << "accepted!\n";
  3013 	else	
  3014 		cout << "canceled!\n";
  3015 	return;
  3016 
  3017 /* Hide hidden stuff temporary, maybe add this as regular function somewhere
  3018 	if (hidemode==HideNone)
  3019 	{
  3020 		setHideTmpMode (HideExport);
  3021 		mapCenter->calcBBoxSizeWithChilds();
  3022 		QRect totalBBox=mapCenter->getTotalBBox();
  3023 		QRect mapRect=totalBBox;
  3024 		QCanvasRectangle *frame=NULL;
  3025 
  3026 		cout << "  map has =("<<totalBBox.x()<<","<<totalBBox.y()<<","<<totalBBox.width()<<","<<totalBBox.height()<<")\n";
  3027 	
  3028 		mapRect.setRect (totalBBox.x(), totalBBox.y(), 
  3029 			totalBBox.width(), totalBBox.height());
  3030 		frame=new QCanvasRectangle (mapRect,mapCanvas);
  3031 		frame->setBrush (QColor(white));
  3032 		frame->setPen (QColor(black));
  3033 		frame->setZ(0);
  3034 		frame->show();    
  3035 	}	
  3036 	else	
  3037 	{
  3038 		setHideTmpMode (HideNone);
  3039 	}	
  3040 	cout <<"  hidemode="<<hidemode<<endl;
  3041 	*/
  3042 }
  3043 
  3044 void MapEditor::ensureSelectionVisible()
  3045 {
  3046 	if (selection)
  3047 	{
  3048 		LinkableMapObj* lmo= dynamic_cast <LinkableMapObj*> (selection);
  3049 		QPoint p;
  3050 		if (selection->getOrientation() == OrientLeftOfCenter)
  3051 			p= worldMatrix().map(QPoint (lmo->x(),lmo->y()));
  3052 		else	
  3053 			p= worldMatrix().map(QPoint (lmo->x()+lmo->width(),lmo->y()+lmo->height()));
  3054 		ensureVisible (p.x(), p.y() );
  3055 	}
  3056 
  3057 }
  3058 
  3059 void MapEditor::updateViewCenter()
  3060 {
  3061 	// Update movingCenter, so that we can zoom comfortably later
  3062 	QRect rc = QRect( contentsX(), contentsY(),
  3063 				  visibleWidth(), visibleHeight() );
  3064 	QRect canvasRect = inverseWorldMatrix().mapRect(rc);
  3065 	movingCenter.setX((canvasRect.right() + canvasRect.left())/2);
  3066 	movingCenter.setY((canvasRect.top() + canvasRect.bottom())/2);
  3067 }
  3068 
  3069 void MapEditor::contentsContextMenuEvent ( QContextMenuEvent * e )
  3070 {
  3071 	// Lineedits are already closed by preceding
  3072 	// mouseEvent, we don't need to close here.
  3073 
  3074     QPoint p = inverseWorldMatrix().map(e->pos());
  3075     LinkableMapObj* lmo=mapCenter->findMapObj(p, NULL);
  3076 	
  3077     if (lmo) 
  3078 	{	// MapObj was found
  3079 		if (selection != lmo)
  3080 		{
  3081 			// select the MapObj
  3082 			if (selection) selection->unselect();
  3083 			selection=lmo;
  3084 			selection->select();
  3085 			adjustCanvasSize();
  3086 		}
  3087 		// Context Menu 
  3088 		if (selection) 
  3089 		{
  3090 			if (typeid(*selection)==typeid(BranchObj) ||
  3091 				typeid(*selection)==typeid(MapCenterObj) )
  3092 			{
  3093 				// Context Menu on branch or mapcenter
  3094 				updateActions();
  3095 				branchContextMenu->popup(e->globalPos() );
  3096 			}	
  3097 			if (typeid(*selection)==typeid(FloatImageObj))
  3098 			{
  3099 				// Context Menu on floatimage
  3100 				updateActions();
  3101 				floatimageContextMenu->popup(e->globalPos() );
  3102 			}	
  3103 		}	
  3104 	} else 
  3105 	{ // No MapObj found, we are on the Canvas itself
  3106 		// Context Menu on Canvas
  3107 		updateActions();
  3108 		canvasContextMenu->popup(e->globalPos() );
  3109     } 
  3110 	e->accept();
  3111 }
  3112 
  3113 void MapEditor::contentsMousePressEvent(QMouseEvent* e)
  3114 {
  3115 	// Ignore right clicks, these will go to context menus
  3116 	if (e->button() == Qt::RightButton )
  3117 	{
  3118 		e->ignore();
  3119 		return;
  3120 	}
  3121 
  3122     QPoint p = inverseWorldMatrix().map(e->pos());
  3123     LinkableMapObj* lmo=mapCenter->findMapObj(p, NULL);
  3124 	
  3125 	e->accept();
  3126 
  3127 	//Take care of clickdesystem flags _or_ modifier modes
  3128 	//
  3129 	if (lmo && (typeid(*lmo)==typeid(BranchObj) ||
  3130 		typeid(*lmo)==typeid(MapCenterObj) ))
  3131 	{
  3132 		QString foname=((BranchObj*)lmo)->getSystemFlagName(p);
  3133 		if (!foname.isEmpty())
  3134 		{
  3135 			// systemFlag clicked
  3136 			selectInt (lmo);
  3137 			if (foname=="url") 
  3138 			{
  3139 				if (e->state() & Qt::ControlModifier)
  3140 					mainWindow->editOpenURLTab();
  3141 				else	
  3142 					mainWindow->editOpenURL();
  3143 			}	
  3144 			else if (foname=="vymLink")
  3145 			{
  3146 				mainWindow->editOpenVymLink();
  3147 				// tabWidget may change, better return now
  3148 				// before segfaulting...
  3149 			} else if (foname=="note")
  3150 				mainWindow->windowToggleNoteEditor();
  3151 			else if (foname=="hideInExport")		
  3152 				toggleHideExport();
  3153 			return;	
  3154 		} 
  3155 	} 
  3156 	// No system flag clicked, take care of modmodes
  3157 
  3158 	// Special case: CTRL is pressed
  3159 	if (e->state() & Qt::ControlModifier)
  3160 	{
  3161 		if (mainWindow->getModMode()==ModModeColor)
  3162 		{
  3163 				pickingColor=true;
  3164 				setCursor (pickColorCursor);
  3165 				return;
  3166 		} 
  3167 		if (mainWindow->getModMode()==ModModeXLink)
  3168 		{	
  3169 			BranchObj *bo_begin=NULL;
  3170 			if (lmo)
  3171 				bo_begin=(BranchObj*)(lmo);
  3172 			else	
  3173 				if (selection && 
  3174 					((typeid(*selection) == typeid(BranchObj)) || 
  3175 					(typeid(*selection) == typeid(MapCenterObj)))  )
  3176 				bo_begin=(BranchObj*)selection;
  3177 			if (bo_begin)	
  3178 			{
  3179 				drawingLink=true;
  3180 				linkingObj_src=bo_begin;
  3181 				tmpXLink=new XLinkObj (mapCanvas);
  3182 				tmpXLink->setBegin (bo_begin);
  3183 				tmpXLink->setEnd   (p);
  3184 				tmpXLink->setColor(defXLinkColor);
  3185 				tmpXLink->setWidth(defXLinkWidth);
  3186 				tmpXLink->updateXLink();
  3187 				tmpXLink->setVisibility (true);
  3188 				return;
  3189 			} 
  3190 		}
  3191 	}
  3192     if (lmo) 
  3193 	{	
  3194 		selectInt (lmo);
  3195 		// Left Button	    Move Branches
  3196 		if (e->button() == Qt::LeftButton )
  3197 		{
  3198 			movingObj_start.setX( p.x() - selection->x() );	
  3199 			movingObj_start.setY( p.y() - selection->y() );	
  3200 			movingObj_orgPos.setX (lmo->x() );
  3201 			movingObj_orgPos.setY (lmo->y() );
  3202 			movingObj_orgRelPos=lmo->getRelPos();
  3203 
  3204 			// If modMode==copy, then we want to "move" the _new_ object around
  3205 			// then we need the offset from p to the _old_ selection, because of tmp
  3206 			if (mainWindow->getModMode()==ModModeCopy &&
  3207 				e->state() & Qt::ControlModifier)
  3208 			{
  3209 				if (typeid(*selection)==typeid(BranchObj) )
  3210 				{
  3211 					copyingObj=true;
  3212 					mapCenter->addBranch ((BranchObj*)selection);
  3213 					unselect();
  3214 					selection=mapCenter->getLastBranch();
  3215 					selection->select();
  3216 					mapCenter->reposition();
  3217 				}
  3218 			}	
  3219 			movingObj=selection;	
  3220 		} else
  3221 			// Middle Button    Toggle Scroll
  3222 			// (On Mac OS X this won't work, but we still have 
  3223 			// a button in the toolbar)
  3224 			if (e->button() == Qt::MidButton )
  3225 				toggleScroll();
  3226 		updateActions();
  3227 	} else 
  3228 	{ // No MapObj found, we are on the Canvas itself
  3229 		// Left Button	    move Pos of CanvasView
  3230 		if (e->button() == Qt::LeftButton )
  3231 		{
  3232 			movingObj=NULL;	// move Content not Obj
  3233 			movingObj_start=e->globalPos();
  3234 			movingCont_start=QPoint (contentsX(), contentsY() );
  3235 			movingVec=QPoint(0,0);
  3236 			setCursor(handOpenCursor);
  3237 		} 
  3238     } 
  3239 }
  3240 
  3241 void MapEditor::contentsMouseMoveEvent(QMouseEvent* e)
  3242 {
  3243 	QPoint p = inverseWorldMatrix().map(e->pos());
  3244 
  3245     // Move the selected MapObj
  3246     if ( selection && movingObj) 
  3247     {	
  3248 		// To avoid jumping of the CanvasView, only 
  3249 		// ensureSelectionVisible, if not tmp linked
  3250 		if (!selection->hasParObjTmp())
  3251 			ensureSelectionVisible ();
  3252 		
  3253 		// Now move the selection, but add relative position 
  3254 		// (movingObj_start) where selection was chosen with 
  3255 		// mousepointer. (This avoids flickering resp. jumping 
  3256 		// of selection back to absPos)
  3257 		
  3258 		LinkableMapObj *lmosel;
  3259 		lmosel =  dynamic_cast <LinkableMapObj*> (selection);
  3260 
  3261 		// Check if we could link 
  3262 		LinkableMapObj* lmo=mapCenter->findMapObj(p, lmosel);
  3263 		
  3264 
  3265 		if (typeid(*selection) == typeid(FloatImageObj))
  3266 		{
  3267 			FloatObj *fo=(FloatObj*)selection;
  3268 			fo->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3269 			fo->setRelPos();
  3270 			fo->reposition();
  3271 
  3272 			// Relink float to new mapcenter or branch, if shift is pressed	
  3273 			// Only relink, if selection really has a new parent
  3274 			if ( (e->modifiers()==Qt::ShiftModifier) && lmo &&
  3275 				( (typeid(*lmo)==typeid(BranchObj)) ||
  3276 				  (typeid(*lmo)==typeid(MapCenterObj)) ) &&
  3277 				( lmo != fo->getParObj())  
  3278 				)
  3279 			{
  3280 				if (typeid(*fo) == typeid(FloatImageObj)) 
  3281 				{
  3282 					//TODO undocom
  3283 					saveStateComplete(QString("Relink %1 to %2").arg(getName(fo)).arg(getName(lmo) ) );
  3284 					FloatImageObj *fio=(FloatImageObj*)(fo);
  3285 					((BranchObj*)(lmo))->addFloatImage (fio);
  3286 					fio->unselect();
  3287 					((BranchObj*)(fio->getParObj()))->removeFloatImage (fio);
  3288 					fio=((BranchObj*)(lmo))->getLastFloatImage();
  3289 					fio->setRelPos();
  3290 					fio->reposition();
  3291 					selection=(LinkableMapObj*)(fio);
  3292 					selection->select();
  3293 					movingObj=(MapObj*)(fio);
  3294 				}	
  3295 			}
  3296 		} else	
  3297 		{	// selection != a FloatObj
  3298 			if (lmosel->getDepth()==0)
  3299 			{
  3300 				// Move MapCenter
  3301 				if (e->buttons()== Qt::LeftButton && e->modifiers()==Qt::ShiftModifier) 
  3302 					mapCenter->moveAll(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3303 				else	
  3304 					mapCenter->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3305 				mapCenter->updateRelPositions();	
  3306 			} else
  3307 			{	
  3308 				if (lmosel->getDepth()==1)
  3309 				{
  3310 					// Move mainbranch
  3311 					lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3312 					lmosel->setRelPos();
  3313 				} else
  3314 				{
  3315 					// Move ordinary branch
  3316 					if (lmosel->getOrientation() == OrientLeftOfCenter)
  3317 						// Add width of bbox here, otherwise alignRelTo will cause jumping around
  3318 						lmosel->move(p.x() -movingObj_start.x()+lmosel->getBBox().width(), 
  3319 							p.y()-movingObj_start.y() +lmosel->getTopPad() );		
  3320 					else	
  3321 						lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() -lmosel->getTopPad());
  3322 				} 
  3323 				// reposition subbranch
  3324 				lmosel->reposition();	
  3325 
  3326 				if (lmo && (lmo!=selection) &&  
  3327 					(typeid(*lmo) == typeid(BranchObj) ||
  3328 					(typeid(*lmo) == typeid(MapCenterObj) )
  3329 					) )
  3330 				{
  3331 					if (e->modifiers()==Qt::ControlModifier)
  3332 					{
  3333 						// Special case: CTRL to link below lmo
  3334 						lmosel->setParObjTmp (lmo,p,+1);
  3335 					}
  3336 					else if (e->modifiers()==Qt::ShiftModifier)
  3337 						lmosel->setParObjTmp (lmo,p,-1);
  3338 					else
  3339 						lmosel->setParObjTmp (lmo,p,0);
  3340 				} else	
  3341 				{
  3342 					lmosel->unsetParObjTmp();
  3343 				}		
  3344 			} // depth>0
  3345 
  3346 		} // no FloatImageObj
  3347 
  3348 		canvas()->update();
  3349 		return;
  3350 	} // selection && moving_obj
  3351 		
  3352 	// Draw a link from one branch to another
  3353 	if (drawingLink)
  3354 	{
  3355 		 tmpXLink->setEnd (p);
  3356 		 tmpXLink->updateXLink();
  3357 	}	 
  3358 	
  3359     // Move CanvasView 
  3360     if (!movingObj && !pickingColor &&!drawingLink) 
  3361 	{
  3362 		QPoint p=e->globalPos();
  3363 		movingVec.setX(-p.x() + movingObj_start.x() );
  3364 		movingVec.setY(-p.y() + movingObj_start.y() );
  3365 		setContentsPos( movingCont_start.x() + movingVec.x(),
  3366 	    movingCont_start.y() + movingVec.y());
  3367 
  3368 		updateViewCenter();
  3369     }
  3370 }
  3371 
  3372 
  3373 void MapEditor::contentsMouseReleaseEvent(QMouseEvent* e)
  3374 {
  3375 	LinkableMapObj *dst;
  3376 	// Have we been picking color?
  3377 	if (pickingColor)
  3378 	{
  3379 		pickingColor=false;
  3380 		setCursor (Qt::ArrowCursor);
  3381 		// Check if we are over another branch
  3382 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), NULL);
  3383 		if (dst && selection) 
  3384 		{	
  3385 			if (e->state() & Qt::ShiftModifier)
  3386 			{
  3387 				((BranchObj*)selection)->setColor (((BranchObj*)(dst))->getColor());
  3388 				((BranchObj*)selection)->setLinkColor ();
  3389 			}	
  3390 			else	
  3391 			{
  3392 				((BranchObj*)selection)->setColorChilds (((BranchObj*)(dst))->getColor());
  3393 				((BranchObj*)selection)->setLinkColor ();
  3394 			}	
  3395 		} 
  3396 		return;
  3397 	}
  3398 
  3399 	// Have we been drawing a link?
  3400 	if (drawingLink)
  3401 	{
  3402 		drawingLink=false;
  3403 		// Check if we are over another branch
  3404 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), NULL);
  3405 		if (dst && selection) 
  3406 		{	
  3407 			tmpXLink->setEnd ( ((BranchObj*)(dst)) );
  3408 			tmpXLink->updateXLink();
  3409 			tmpXLink->activate();
  3410 			saveStateComplete(QString("Activate xLink from %1 to %2").arg(getName(tmpXLink->getBegin())).arg(getName(tmpXLink->getEnd())) );	//TODO undoCommand
  3411 		} else
  3412 		{
  3413 			delete(tmpXLink);
  3414 			tmpXLink=NULL;
  3415 		}
  3416 		return;
  3417 	}
  3418 	
  3419     // Have we been moving something?
  3420     if ( selection && movingObj ) 
  3421     {	
  3422 		if(typeid(*selection)==typeid (FloatImageObj))
  3423 		{
  3424 			// Moved FloatObj. Maybe we need to reposition
  3425 			FloatImageObj *fo=(FloatImageObj*)selection;
  3426 		    QString pold=qpointToString(movingObj_orgRelPos);
  3427 		    QString pnow=qpointToString(fo->getRelPos());
  3428 			saveStateConstSelection(
  3429 				"moveRel "+pold,
  3430 				"moveRel "+pnow,
  3431 				QString("Move %1 to relativ position %2").arg(getName(selection)).arg(pnow));
  3432 
  3433 			// FIXME Why calling parObj here?
  3434 			selection->getParObj()->requestReposition();
  3435 			mapCenter->reposition();
  3436 		}	
  3437 
  3438 		// Check if we are over another branch, but ignore 
  3439 		// any found LMOs, which are FloatObjs
  3440 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), 
  3441 			((LinkableMapObj*)selection) );
  3442 
  3443 		if (dst && (typeid(*dst)!=typeid(BranchObj) && typeid(*dst)!=typeid(MapCenterObj))) 
  3444 			dst=NULL;
  3445 		
  3446 		if (typeid(*selection) == typeid(MapCenterObj)  )
  3447 		{	// The MapCenter was moved
  3448 			cout << "FIXME missing savestate...\n";	
  3449 		}
  3450 		
  3451 		if (typeid(*selection) == typeid(BranchObj)  )
  3452 		{	// A branch was moved
  3453 			
  3454 			// save the position in case we link to mapcenter
  3455 			QPoint savePos=QPoint (selection->x(),selection->y() );
  3456 
  3457 			// Reset the temporary drawn link to the original one
  3458 			((LinkableMapObj*)selection)->unsetParObjTmp();
  3459 
  3460 			// For Redo we may need to save original selection
  3461 			QString preSelStr=selection->getSelectString();
  3462 
  3463 			copyingObj=false;	
  3464 			if (dst ) 
  3465 			{
  3466 				BranchObj* bsel=(BranchObj*)selection;
  3467 				BranchObj* bdst=(BranchObj*)dst;
  3468 
  3469 				QString preParStr=(bsel->getParObj())->getSelectString();
  3470 				QString preNum=QString::number (bsel->getNum(),10);
  3471 				QString preDstParStr;
  3472 
  3473 				if (e->state() & Qt::ShiftModifier && dst->getParObj())
  3474 				{	// Link above dst
  3475 					preDstParStr=dst->getParObj()->getSelectString();
  3476 					bsel->moveBranchTo ( (BranchObj*)(bdst->getParObj()), bdst->getNum());
  3477 				} else 
  3478 				if (e->state() & Qt::ControlModifier && dst->getParObj())
  3479 				{
  3480 					// Link below dst
  3481 					preDstParStr=dst->getParObj()->getSelectString();
  3482 					bsel->moveBranchTo ( (BranchObj*)(bdst->getParObj()), bdst->getNum()+1);
  3483 				} else	
  3484 				{	// Append to dst
  3485 					preDstParStr=dst->getSelectString();
  3486 					bsel->moveBranchTo (bdst,-1);
  3487 					if (dst->getDepth()==0) bsel->move (savePos);
  3488 				} 
  3489 				QString postSelStr=selection->getSelectString();
  3490 				QString postNum=QString::number (bsel->getNum(),10);
  3491 
  3492 				QString undoCom="linkBranchToPos (\""+ 
  3493 					preParStr+ "\"," + preNum  +"," + 
  3494 					QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+ ")";
  3495 
  3496 				QString redoCom="linkBranchToPos (\""+ 
  3497 					preDstParStr + "\"," + postNum + "," +
  3498 					QString ("%1,%2").arg(savePos.x()).arg(savePos.y())+ ")";
  3499 
  3500 				saveState (
  3501 					postSelStr,undoCom,
  3502 					preSelStr, redoCom,
  3503 					QString("Relink %1 to %2").arg(getName(bsel)).arg(getName(dst)) );
  3504 			} else
  3505 				if (selection->getDepth()==1)
  3506 				{
  3507 					// The select string might be different _after_ moving around.
  3508 					// Therefor reposition and then use string of old selection, too
  3509 					mapCenter->reposition();
  3510 
  3511 					QString ps=qpointToString ( ((BranchObj*)selection)->getRelPos() );
  3512 					saveState(
  3513 						selection->getSelectString(), "moveRel "+qpointToString(movingObj_orgRelPos), 
  3514 						preSelStr, "moveRel "+ps, 
  3515 						QString("Move %1 to relative position %2").arg(getName(selection)).arg(ps));
  3516 			
  3517 				}
  3518 			// Draw the original link, before selection was moved around
  3519 			mapCenter->reposition();
  3520 		}
  3521 		// Finally resize canvas, if needed
  3522 		adjustCanvasSize();
  3523 		canvas()->update();
  3524 		movingObj=NULL;		
  3525 
  3526 		// Just make sure, that actions are still ok,e.g. the move branch up/down buttons...
  3527 		updateActions();
  3528 	} else 
  3529 		// maybe we moved View: set old cursor
  3530 		setCursor (Qt::ArrowCursor);
  3531     
  3532 }
  3533 
  3534 void MapEditor::contentsMouseDoubleClickEvent(QMouseEvent* e)
  3535 {
  3536 	if (e->button() == Qt::LeftButton )
  3537 	{
  3538 		QPoint p = inverseWorldMatrix().map(e->pos());
  3539 		LinkableMapObj *lmo=mapCenter->findMapObj(p, NULL);
  3540 		if (lmo) {	// MapObj was found
  3541 			// First select the MapObj than edit heading
  3542 			if (selection) selection->unselect();
  3543 			selection=lmo;
  3544 			selection->select();
  3545 			mainWindow->editHeading();
  3546 		}
  3547 	}
  3548 }
  3549 
  3550 void MapEditor::resizeEvent (QResizeEvent* e)
  3551 {
  3552 	Q3CanvasView::resizeEvent( e );
  3553 	adjustCanvasSize();
  3554 }
  3555 
  3556 void MapEditor::contentsDragEnterEvent(QDragEnterEvent *event) 
  3557 {
  3558 
  3559 //  for (unsigned int i=0;event->format(i);i++) // Debug mime type
  3560 //    cerr << event->format(i) << endl;
  3561 
  3562   if (selection && 
  3563       (typeid(*selection) == typeid(BranchObj)) || 
  3564       (typeid(*selection) == typeid(MapCenterObj))) {
  3565     
  3566     // If QImageDrag can decode mime type 
  3567     if (Q3ImageDrag::canDecode(event)) {
  3568       event->accept();
  3569       return;
  3570     }
  3571     
  3572     // If image are dragged from firefox 
  3573     if (event->provides("application/x-moz-file-promise-url") && 
  3574 	event->provides("application/x-moz-nativeimage")) {
  3575       event->accept(true);
  3576       return;
  3577     }
  3578 
  3579     // If QUriDrag can decode mime type 
  3580     if (Q3UriDrag::canDecode(event)) {
  3581       event->accept();
  3582       return;
  3583     }
  3584     
  3585 	// If Uri are dragged from firefox 
  3586     if (event->provides("_NETSCAPE_URL")){
  3587       event->accept();
  3588       return;
  3589     }
  3590 
  3591     // If QTextDrag can decode mime type
  3592     if (Q3TextDrag::canDecode(event)) {
  3593       event->accept();
  3594       return;
  3595     }
  3596 
  3597   }
  3598   event->ignore();
  3599 }
  3600 
  3601 bool isUnicode16(const QByteArray &d) 
  3602 {
  3603   // TODO: make more precise check for unicode 16.
  3604   // Guess unicode16 if any of second bytes are zero
  3605   unsigned int length = max(0,d.size()-2)/2;
  3606   for (unsigned int i = 0; i<length ; i++)
  3607     if (d.at(i*2+1)==0) return true;
  3608   return false;
  3609 }
  3610       
  3611 void MapEditor::contentsDropEvent(QDropEvent *event) 
  3612 {
  3613 	if (selection && 
  3614       (typeid(*selection) == typeid(BranchObj)) || 
  3615       (typeid(*selection) == typeid(MapCenterObj))) 
  3616 	{
  3617 		bool update=false;
  3618 		Q3StrList uris;
  3619 		QString heading;
  3620 		if (event->provides("image/png")) 
  3621 		{
  3622 			QPixmap pix;
  3623 			if (Q3ImageDrag::decode(event, pix)) 
  3624 			{
  3625 				addFloatImage(pix);
  3626 				event->accept();
  3627 				update=true;
  3628 			} else
  3629 				event->ignore();
  3630 
  3631 		} else if (event->provides("application/x-moz-file-promise-url") && 
  3632 			 event->provides("application/x-moz-nativeimage")) 
  3633 		{
  3634 			// Contains url to the img src in unicode16
  3635 			QByteArray d = event->encodedData("application/x-moz-file-promise-url");
  3636 			QString url = QString((const QChar*)d.data(),d.size()/2);
  3637 			fetchImage(url);
  3638 			event->accept();
  3639 			update=true;
  3640 		} else if (event->provides ("text/uri-list"))
  3641 		{	// Uris provided e.g. by konqueror
  3642 			Q3UriDrag::decode (event,uris);
  3643 		} else if (event->provides ("_NETSCAPE_URL"))
  3644 		{	// Uris provided by Mozilla
  3645 		  QStringList l = QStringList::split("\n", event->encodedData("_NETSCAPE_URL"));
  3646 		  uris.append(l[0]);
  3647 		  heading = l[1];
  3648 		} else if (event->provides("text/html")) {
  3649 
  3650 		  // Handels text mime types
  3651 		  // Look like firefox allways handle text as unicode16 (2 bytes per char.)
  3652 		  QByteArray d = event->encodedData("text/html");
  3653 		  QString text;
  3654 		  if (isUnicode16(d)) 
  3655 		    text = QString((const QChar*)d.data(),d.size()/2);
  3656 		  else 
  3657 		    text = QString(d);
  3658 
  3659 		  textEditor->setText(text);
  3660 
  3661 		  event->accept();
  3662 		  update=true;
  3663 		} else if (event->provides("text/plain")) {
  3664 		  QByteArray d = event->encodedData("text/plain");
  3665 		  QString text;
  3666 		  if (isUnicode16(d))
  3667 		    text = QString((const QChar*)d.data(),d.size()/2);
  3668 		  else 
  3669 		    text = QString(d);
  3670 
  3671 		  textEditor->setText(text);
  3672 		  
  3673 		  event->accept();
  3674 		  update= true;
  3675 		}
  3676 
  3677 		if (uris.count()>0)
  3678 		{
  3679 			QStringList files;
  3680 			QStringList urls;
  3681 			QString s;
  3682 			BranchObj *bo;
  3683 			for (const char* u=uris.first(); u; u=uris.next())
  3684 			{
  3685 				bo=((BranchObj*)selection)->addBranch();
  3686 				if (bo)
  3687 				{
  3688 					s=Q3UriDrag::uriToLocalFile(u);
  3689 					if (!s.isEmpty()) 
  3690 					{
  3691                        QString file = QDir::convertSeparators(s);
  3692                        heading = QFileInfo(file).baseName();
  3693                        files.append(file);
  3694                        if (file.endsWith(".vym", false))
  3695                            bo->setVymLink(file);
  3696                        else
  3697                            bo->setURL(u);
  3698                    } else 
  3699 				   {
  3700                        urls.append (u);
  3701                        bo->setURL(u);
  3702                    }
  3703 
  3704                    if (!heading.isEmpty())
  3705                        bo->setHeading(heading);
  3706                    else
  3707                        bo->setHeading(u);
  3708 				}
  3709 			}
  3710 			update=true;
  3711 		}
  3712 
  3713 		if (update) 
  3714 		{
  3715 			//FIXME saveState has to be called earlier for each of the drops...
  3716 			saveStateComplete("Drop Event");	//TODO undo Command
  3717 			mapCenter->reposition();
  3718 			adjustCanvasSize();
  3719 			canvas()->update();
  3720 		}	
  3721 	}	
  3722 }
  3723 
  3724 void MapEditor::addFloatImage(const QPixmap &img) 
  3725 {
  3726   if (selection && 
  3727       (typeid(*selection) == typeid(BranchObj)) || 
  3728       (typeid(*selection) == typeid(MapCenterObj))  )
  3729   {
  3730     BranchObj *bo=((BranchObj*)selection);
  3731     saveStatePart(selection,QString("Add floatimage to %1").arg(getName(bo)));
  3732     //QString fn=fd->selectedFile();
  3733     //lastImageDir=fn.left(fn.findRev ("/"));
  3734     bo->addFloatImage();
  3735     // FIXME check if load was successful
  3736     bo->getLastFloatImage()->load(img);
  3737     //bo->getLastFloatImage()->setOriginalFilename(fn);
  3738     mapCenter->reposition();
  3739     adjustCanvasSize();
  3740     canvas()->update();
  3741   }
  3742 }
  3743 
  3744 
  3745 void MapEditor::imageDataFetched(const QByteArray &a, Q3NetworkOperation */*nop*/) 
  3746 {
  3747   if (!imageBuffer) imageBuffer = new QBuffer();
  3748   if (!imageBuffer->isOpen()) {
  3749     imageBuffer->open(QIODevice::WriteOnly | QIODevice::Append);
  3750   }
  3751   imageBuffer->at(imageBuffer->at()+imageBuffer->writeBlock(a));
  3752 }
  3753 
  3754 
  3755 void MapEditor::imageDataFinished(Q3NetworkOperation *nop) 
  3756 {
  3757 	if (nop->state()==Q3NetworkProtocol::StDone) {
  3758 		QPixmap img(imageBuffer->buffer());
  3759 		addFloatImage(img);
  3760 	}
  3761 
  3762 	if (imageBuffer) {
  3763 		imageBuffer->close();
  3764 		if (imageBuffer) {
  3765 			imageBuffer->close();
  3766 			delete imageBuffer;
  3767 			imageBuffer = 0;
  3768 		}
  3769 	}
  3770 }
  3771 
  3772 void MapEditor::fetchImage(const QString &url) 
  3773 {
  3774   if (urlOperator) {
  3775     urlOperator->stop();
  3776     disconnect(urlOperator);
  3777     delete urlOperator;
  3778   }
  3779   
  3780   urlOperator = new Q3UrlOperator(url);
  3781   connect(urlOperator, SIGNAL(finished(Q3NetworkOperation *)), 
  3782 	  this, SLOT(imageDataFinished(Q3NetworkOperation*)));
  3783 
  3784   connect(urlOperator, SIGNAL(data(const QByteArray &, Q3NetworkOperation *)),
  3785 	  this, SLOT(imageDataFetched(const QByteArray &, Q3NetworkOperation *)));
  3786   urlOperator->get();
  3787 }