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