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