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