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