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