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