mapeditor.cpp
author insilmaril
Tue, 31 Jan 2006 15:56:28 +0000
changeset 200 451cab91e350
parent 199 202572375c98
child 205 30c4a6c7ff10
permissions -rw-r--r--
Bugfixes for including images in tree
     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.setFile(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 %1\nexists already. Do you want to overwrite it?").arg(fd->selectedFile()),
  1119 			QMessageBox::Warning,
  1120 			QMessageBox::Yes | QMessageBox::Default,
  1121 			QMessageBox::Cancel | QMessageBox::Escape,
  1122 			QMessageBox::NoButton );
  1123 
  1124 			mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
  1125 			mb.setButtonText( QMessageBox::No, tr("Cancel"));
  1126 			ExportLaTeX ex;
  1127 			switch( mb.exec() ) 
  1128 			{
  1129 				case QMessageBox::Yes:
  1130 					// save 
  1131 					break;;
  1132 				case QMessageBox::Cancel:
  1133 					// do nothing
  1134 					return;
  1135 					break;
  1136 			}
  1137 		}
  1138 		ExportLaTeX ex;
  1139 		ex.setFile (fd->selectedFile() );
  1140 		ex.setMapCenter(mapCenter);
  1141 		ex.exportLaTeX();
  1142 	}
  1143 }
  1144 
  1145 void MapEditor::exportOOPresentation(const QString &fn, const QString &cf)
  1146 {
  1147 	ExportOO ex;
  1148 	ex.setFile (fn);
  1149 	ex.setMapCenter(mapCenter);
  1150 	if (ex.setConfigFile(cf)) ex.exportPresentation();
  1151 }
  1152 
  1153 
  1154 
  1155 void MapEditor::exportXML(const QString &dir)
  1156 {
  1157 	// Create subdirectories
  1158 	makeSubDirs (dir);
  1159 
  1160 	// write to directory
  1161 	QString saveFile=saveToDir (dir,mapName+"-",true,mapCenter->getTotalBBox().topLeft() ,NULL);
  1162 	QFile file;
  1163 
  1164 	file.setName ( dir + "/"+mapName+".xml");
  1165 	if ( !file.open( IO_WriteOnly ) )
  1166 	{
  1167 		// This should neverever happen
  1168 		QMessageBox::critical (0,tr("Critical Export Error"),tr("MapEditor::exportXML couldn't open %1").arg(file.name()));
  1169 		return;
  1170 	}	
  1171 
  1172 	// Write it finally, and write in UTF8, no matter what 
  1173 	QTextStream ts( &file );
  1174 	ts.setEncoding (QTextStream::UnicodeUTF8);
  1175 	ts << saveFile;
  1176 	file.close();
  1177 
  1178 	// Now write image, too
  1179 	exportImage (dir+"/images/"+mapName+".png");
  1180 }
  1181 
  1182 void MapEditor::clear()
  1183 {
  1184 	if (selection)
  1185 	{
  1186 		selection->unselect();
  1187 		selection=NULL;
  1188 	}	
  1189 
  1190 	mapCenter->clear();
  1191 }
  1192 
  1193 void MapEditor::copy()
  1194 {
  1195 	// Finish open lineEdits
  1196 	if (lineedit) finishedLineEditNoSave();
  1197 
  1198 	if (selection) 
  1199 	{
  1200 		// write to directory
  1201 		QString clipfile="part";
  1202 		QString saveFile=saveToDir (fileDir,clipfile+"-",true,QPoint(),selection);
  1203 		QFile file;
  1204 
  1205 		file.setName ( clipboardDir + "/"+clipfile+".xml");
  1206 		if ( !file.open( IO_WriteOnly ) )
  1207 		{
  1208 			// This should neverever happen
  1209 			QMessageBox::critical (0,tr("Critical Export Error"),tr("MapEditor::exportXML couldn't open %1").arg(file.name()));
  1210 			return;
  1211 		}	
  1212 
  1213 		// Write it finally, and write in UTF8, no matter what 
  1214 		QTextStream ts( &file );
  1215 		ts.setEncoding (QTextStream::UnicodeUTF8);
  1216 		ts << saveFile;
  1217 		file.close();
  1218 
  1219 		clipboardEmpty=false;
  1220 		updateActions();
  1221 	}	    
  1222 }
  1223 
  1224 void MapEditor::redo()
  1225 {
  1226 	// Finish open lineEdits
  1227 	if (lineedit) finishedLineEditNoSave();
  1228 
  1229 	blockSaveState=true;
  1230 	
  1231 	// Find out current undo directory
  1232 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(undoNum));
  1233 
  1234 	// Restore variables
  1235 	QString undoCommand;
  1236 	QString undoSelection;
  1237 	QString redoCommand;
  1238 	QString redoSelection;
  1239 	SimpleSettings set;
  1240 	set.readSettings(QString(bakMapDir+"/commands"));
  1241 	undoCommand=set.readEntry ("undoCommand");
  1242 	undoSelection=set.readEntry ("undoSelection");
  1243 	redoCommand=set.readEntry ("redoCommand");
  1244 	redoSelection=set.readEntry ("redoSelection");
  1245 
  1246 	// select  object before redo
  1247 	if (!redoSelection.isEmpty())
  1248 		select (redoSelection);
  1249 
  1250 /* TODO remove testing
  1251 	cout << "ME::redo() begin\n";
  1252 	cout << "    undosTotal="<<undosTotal<<endl;
  1253 	cout << "    undosAvail="<<undosAvail<<endl;
  1254 	cout << "       undoNum="<<undoNum<<endl;
  1255 	cout << "    ---------------------------"<<endl;
  1256 	cout << "    undoCom="<<undoCommand<<endl;
  1257 	cout << "    undoSel="<<undoSelection<<endl;
  1258 	cout << "    ---------------------------"<<endl;
  1259 	cout << "    redoCom="<<redoCommand<<endl;
  1260 	cout << "    redoSel="<<redoSelection<<endl;
  1261 	cout << "    ---------------------------"<<endl;
  1262 */
  1263 	parseAtom (undoCommand);
  1264 	mapCenter->reposition();
  1265 
  1266 	//if (!redoSelection.isEmpty())
  1267 	//	select (redoSelection);
  1268 
  1269 	undosAvail--;
  1270 	if (undosAvail<1)
  1271 		// Undo not longer available now
  1272 		actionEditUndo->setEnabled (false);
  1273 	else	
  1274 		undoNum--; if (undoNum<1) undoNum=undosTotal;
  1275 
  1276 	blockSaveState=false;
  1277 /* TODO remove testing
  1278 	cout << "ME::redo() end\n";
  1279 	cout << "    undosAvail="<<undosAvail<<endl;
  1280 	cout << "       undoNum="<<undoNum<<endl;
  1281 	cout << "    ---------------------------"<<endl<<endl;
  1282 */	
  1283 }
  1284 
  1285 void MapEditor::undo()
  1286 {
  1287 	// Finish open lineEdits
  1288 	if (lineedit) finishedLineEditNoSave();
  1289 
  1290 	blockSaveState=true;
  1291 	
  1292 	// Find out current undo directory
  1293 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(undoNum));
  1294 
  1295 	// Restore variables
  1296 	QString undoCommand;
  1297 	QString undoSelection;
  1298 	QString redoCommand;
  1299 	QString redoSelection;
  1300 	SimpleSettings set;
  1301 	set.readSettings(QString(bakMapDir+"/commands"));
  1302 	undoCommand=  set.readEntry ("undoCommand");
  1303 	undoSelection=set.readEntry ("undoSelection");
  1304 	redoCommand=  set.readEntry ("redoCommand");
  1305 	redoSelection=set.readEntry ("redoSelection");
  1306 
  1307 	// select  object before undo
  1308 	if (!undoSelection.isEmpty())
  1309 		select (undoSelection);
  1310 
  1311 /* TODO testing
  1312 	cout << "ME::undo() begin\n";
  1313 	cout << "    undosTotal="<<undosTotal<<endl;
  1314 	cout << "    undosAvail="<<undosAvail<<endl;
  1315 	cout << "       undoNum="<<undoNum<<endl;
  1316 	cout << "    ---------------------------"<<endl;
  1317 	cout << "    undoCom="<<undoCommand<<endl;
  1318 	cout << "    undoSel="<<undoSelection<<endl;
  1319 	cout << "    ---------------------------"<<endl;
  1320 	cout << "    redoCom="<<redoCommand<<endl;
  1321 	cout << "    redoSel="<<redoSelection<<endl;
  1322 	cout << "    ---------------------------"<<endl;
  1323 */	
  1324 	parseAtom (undoCommand);
  1325 	mapCenter->reposition();
  1326 
  1327 	//if (!redoSelection.isEmpty())
  1328 	//	select (redoSelection);
  1329 
  1330 	undosAvail--;
  1331 	if (undosAvail<1)
  1332 		// Undo not longer available now
  1333 		actionEditUndo->setEnabled (false);
  1334 	else	
  1335 		undoNum--; if (undoNum<1) undoNum=undosTotal;
  1336 
  1337 	blockSaveState=false;
  1338 /* TODO remove testing
  1339 	cout << "ME::undo() end\n";
  1340 	cout << "    undosAvail="<<undosAvail<<endl;
  1341 	cout << "       undoNum="<<undoNum<<endl;
  1342 	cout << "    ---------------------------"<<endl<<endl;
  1343 */
  1344 }
  1345 
  1346 void MapEditor::undoXML(const QString &undoSel, const QString &bakMapPath)
  1347 {
  1348 	QString bakMapDir=bakMapPath.left(bakMapPath.findRev("/"));
  1349 	QDir d(bakMapDir);
  1350 	QFile file (bakMapPath);
  1351 
  1352 	if (d.exists() )
  1353 	{
  1354 		// We need to parse saved XML data
  1355 		mapBuilderHandler handler;
  1356 		QXmlInputSource source( file);
  1357 		QXmlSimpleReader reader;
  1358 		reader.setContentHandler( &handler );
  1359 		reader.setErrorHandler( &handler );
  1360 		handler.setMapEditor( this );
  1361 		handler.setTmpDir ( bakMapDir );	// needed to load files with rel. path
  1362 		if (undoSel.isEmpty())
  1363 		{
  1364 			unselect();
  1365 			mapCenter->clear();
  1366 			handler.setLoadMode (NewMap);
  1367 		} else	
  1368 		{
  1369 			select (undoSel);
  1370 			handler.setLoadMode (ImportReplace);
  1371 		}	
  1372 		blockReposition=true;
  1373 		bool ok = reader.parse( source );
  1374 		blockReposition=false;
  1375 		if (! ok ) 
  1376 		{	
  1377 			// This should never ever happen
  1378 			QMessageBox::critical( 0, tr( "Critical Parse Error by reading backupFile" ),
  1379 								   tr( handler.errorProtocol() )+" in "+bakMapDir );
  1380 		}
  1381 	} else	
  1382 	{
  1383 		QMessageBox::critical( 0, tr( "Critical Error" ),
  1384 			tr("Temporary directory %1 used for undo is gone. \n"
  1385 			"I will create a new one, but at the moment no undo is available.\n"
  1386 			"Maybe you want to reload your original data.\n\n"
  1387 			"Sorry for any inconveniences.").arg(bakMapDir) );
  1388 		makeTmpDirs();	
  1389 	}							
  1390 }
  1391 
  1392 void MapEditor::pasteNoSave()
  1393 {
  1394 	// Finish open lineEdits
  1395 	if (lineedit) finishedLineEditNoSave();
  1396 
  1397 	load (clipboardDir+"/part.xml",ImportAdd);
  1398 }
  1399 
  1400 void MapEditor::cutNoSave()
  1401 {
  1402 	copy();
  1403 	deleteSelection();
  1404 }
  1405 
  1406 void MapEditor::paste()
  1407 {   
  1408 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  1409 				      typeid(*selection) == typeid(MapCenterObj))) 
  1410 	{
  1411 		saveState(selection);
  1412 		pasteNoSave();
  1413 		mapCenter->reposition();
  1414 		adjustCanvasSize();
  1415 	}
  1416 }
  1417 
  1418 void MapEditor::cut()
  1419 {
  1420 	saveState(selection->getParObj());
  1421 	copy();
  1422 	cutNoSave();
  1423 	mapCenter->reposition();
  1424 	adjustCanvasSize();
  1425 }
  1426 
  1427 void MapEditor::move(const int &x, const int &y)
  1428 {
  1429 	// TODO no saveState, because this is only internal at undo so far
  1430 	if (selection) selection->move(x,y);
  1431 	if (typeid(*selection) == typeid(FloatImageObj))
  1432 		((FloatImageObj*)selection)->setRelPos();
  1433 }
  1434 
  1435 void MapEditor::moveBranchUp()
  1436 {
  1437 	// Finish open lineEdits
  1438 	if (lineedit) finishedLineEditNoSave();
  1439 
  1440 	BranchObj* bo;
  1441 	BranchObj* par;
  1442 	if (typeid(*selection) == typeid(BranchObj)  ) 
  1443 	{
  1444 		bo=(BranchObj*)selection;
  1445 		par=(BranchObj*)(bo->getParObj());
  1446 		selection->unselect();
  1447 		selection=par->moveBranchUp (bo);
  1448 		selection->select();
  1449 		saveState("moveBranchDown ()",bo);
  1450 		mapCenter->reposition();
  1451 		ensureSelectionVisible();
  1452 	}
  1453 }
  1454 
  1455 void MapEditor::moveBranchDown()
  1456 {
  1457 	// Finish open lineEdits
  1458 	if (lineedit) finishedLineEditNoSave();
  1459 
  1460 	BranchObj* bo;
  1461 	BranchObj* par;
  1462 	if (typeid(*selection) == typeid(BranchObj)  ) 
  1463 	{
  1464 		bo=(BranchObj*)selection;
  1465 		par=(BranchObj*)(bo->getParObj());
  1466 		selection->unselect(); 
  1467 		selection=par->moveBranchDown(bo);
  1468 		selection->select();
  1469 		saveState("moveBranchUp ()",bo);
  1470 		mapCenter->reposition();
  1471 		ensureSelectionVisible();
  1472 	}	
  1473 }
  1474 
  1475 void MapEditor::editHeading()
  1476 {
  1477 	// Finish open lineEdits
  1478 	if (lineedit) finishedLineEditNoSave();
  1479 
  1480 	if (selection  &&  
  1481 		 (typeid(*selection) == typeid(BranchObj) || 
  1482 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1483 	{
  1484 		editingBO=(BranchObj*)selection;
  1485 		saveState("setHeading (\""+((BranchObj*)selection)->getHeading()+"\")",editingBO );
  1486 
  1487 		ensureSelectionVisible();
  1488 		QPoint p = worldMatrix().map(QPoint (editingBO->x(),editingBO->y()));
  1489 		lineedit->setGeometry(p.x()-contentsX(),p.y()-contentsY(),200,25);
  1490 		QString s=editingBO->getHeading();
  1491 		lineedit->setText(s);
  1492 		lineedit->setCursorPosition(1);
  1493 		if (actionSettingsAutoselectText->isOn() && !s.isEmpty() && actionSettingsPasteNewHeading->isOn() )
  1494 			lineedit->selectAll();
  1495 		lineedit->show();
  1496 		lineedit->grabKeyboard();
  1497 		lineedit->setFocus();
  1498 	}				
  1499 }
  1500 
  1501 void MapEditor::setHeading(const QString &s)
  1502 {
  1503 	// Internal function, no saveState needed
  1504 	if (selection  &&  
  1505 		 (typeid(*selection) == typeid(BranchObj) || 
  1506 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1507 	{
  1508 		((BranchObj*)selection)->setHeading(s);
  1509 		mapCenter->reposition();
  1510 		adjustCanvasSize();
  1511 		ensureSelectionVisible();
  1512 	}
  1513 }
  1514 
  1515 void MapEditor::setURL (const QString &s)
  1516 {
  1517 	// Internal function, no saveState needed
  1518 	if (selection  &&  
  1519 		 (typeid(*selection) == typeid(BranchObj) || 
  1520 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1521 	{
  1522 		((BranchObj*)selection)->setURL(s);
  1523 		mapCenter->reposition();
  1524 		adjustCanvasSize();
  1525 		ensureSelectionVisible();
  1526 	}
  1527 }
  1528 
  1529 void MapEditor::setVymLink (const QString &s)
  1530 {
  1531 	// Internal function, no saveState needed
  1532 	if (selection  &&  
  1533 		 (typeid(*selection) == typeid(BranchObj) || 
  1534 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1535 	{
  1536 		((BranchObj*)selection)->setVymLink(s);
  1537 		mapCenter->reposition();
  1538 		adjustCanvasSize();
  1539 		ensureSelectionVisible();
  1540 	}
  1541 }
  1542 
  1543 void MapEditor::addNewBranch(int pos)
  1544 {
  1545 	// Finish open lineEdits
  1546 	if (lineedit) finishedLineEditNoSave();
  1547 
  1548 	if (selection  &&  
  1549 		 (typeid(*selection) == typeid(BranchObj) || 
  1550 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1551 	{
  1552 		saveState(selection);	//TODO undoCommand
  1553 
  1554 		BranchObj* bo1 = (BranchObj*) selection;
  1555 		bool wasScrolled=false;
  1556 		BranchObj *newbo=NULL;
  1557 		if (pos==0)
  1558 		{
  1559 			// save scroll state. If scrolled, automatically select
  1560 			// new branch in order to tmp unscroll parent...
  1561 			wasScrolled=bo1->isScrolled();
  1562 			newbo=bo1->addBranch();
  1563 		}	else 
  1564 		{
  1565 			BranchObj *parbo=(BranchObj*)(selection->getParObj());
  1566 			if (parbo)
  1567 			{
  1568 				if (pos<0)
  1569 					// add above selection
  1570 					newbo=parbo->insertBranch(bo1->getNum());
  1571 				else
  1572 					// add below selection
  1573 					newbo=parbo->insertBranch(bo1->getNum()+1);
  1574 			} else
  1575 				// This should not happen...
  1576 				return;
  1577 			
  1578 		}	
  1579 
  1580 		LinkableMapObj *oldselection=selection;
  1581 
  1582 		mapCenter->reposition();
  1583 		adjustCanvasSize();
  1584 		if (actionSettingsAutoedit->isOn() ||
  1585 			actionSettingsAutoselectHeading->isOn() )
  1586 		{
  1587 			selection->unselect();
  1588 			selection=newbo;
  1589 			selection->select();
  1590 			if (actionSettingsPasteNewHeading->isOn() )
  1591 			{
  1592 				BranchObj *bo2= (BranchObj*)selection;
  1593 				bo2->setHeading("");
  1594 			}	
  1595 			if (actionSettingsAutoedit->isOn() )
  1596 				editHeading();
  1597 			if (!actionSettingsAutoselectHeading->isOn()
  1598 				&& !wasScrolled)
  1599 			{
  1600 				selection->unselect();
  1601 				selection=oldselection;
  1602 				selection->select();
  1603 			}
  1604 		}	
  1605 	}	
  1606 }
  1607 
  1608 
  1609 void MapEditor::addNewBranchHere()
  1610 {
  1611 	// Finish open lineEdits
  1612 	if (lineedit) finishedLineEditNoSave();
  1613 
  1614 	if (selection  &&  
  1615 		 (typeid(*selection) == typeid(BranchObj) ) )
  1616 	{
  1617 		saveState(selection);
  1618 
  1619 		BranchObj* bo1 = (BranchObj*) selection;
  1620 		bool wasScrolled=false;
  1621 		BranchObj *newbo=NULL;
  1622 		BranchObj *parbo=(BranchObj*)(selection->getParObj());
  1623 		if (parbo)
  1624 		{
  1625 			// add below selection
  1626 			newbo=parbo->insertBranch(bo1->getNum()+1);
  1627 		} 
  1628 
  1629 		LinkableMapObj *oldselection=selection;
  1630 		((BranchObj*)selection)->moveBranchTo (newbo,-1);
  1631 
  1632 		mapCenter->reposition();
  1633 		adjustCanvasSize();
  1634 		if (actionSettingsAutoedit->isOn() ||
  1635 			actionSettingsAutoselectHeading->isOn() )
  1636 		{
  1637 			selection->unselect();
  1638 			selection=newbo;
  1639 			selection->select();
  1640 			if (actionSettingsPasteNewHeading->isOn() )
  1641 			{
  1642 				BranchObj *bo2= (BranchObj*)selection;
  1643 				bo2->setHeading("");
  1644 			}	
  1645 			if (actionSettingsAutoedit->isOn() )
  1646 				editHeading();
  1647 			if (!actionSettingsAutoselectHeading->isOn()
  1648 				&& !wasScrolled)
  1649 			{
  1650 				selection->unselect();
  1651 				selection=oldselection;
  1652 				selection->select();
  1653 			}
  1654 		}	
  1655 	}	
  1656 }
  1657 
  1658 void MapEditor::deleteSelection()
  1659 {
  1660 	// Finish open lineEdits
  1661 	if (lineedit) finishedLineEditNoSave();
  1662 
  1663 	if (selection  && typeid(*selection) ==typeid(BranchObj) ) 
  1664 	{
  1665 		if (selection->getDepth()>1)
  1666 			// Normal branch, save parent with childs
  1667 			saveState(selection->getParObj());
  1668 		else
  1669 			// Mainbranch, save whole map
  1670 			// TODO Better would be to insert mainbranch again at pos
  1671 			// But undoCommand is missing right now
  1672 			saveState();
  1673 		BranchObj* bo=dynamic_cast <BranchObj*> (selection);
  1674 		BranchObj* par=(BranchObj*)(bo->getParObj());
  1675 		bo->unselect();
  1676 		selection=NULL;
  1677 		par->removeBranch(bo);
  1678 		selection=par;
  1679 		selection->select();
  1680 		ensureSelectionVisible();
  1681 		mapCenter->reposition();
  1682 		adjustCanvasSize();
  1683 	}
  1684 	if (selection  && typeid(*selection) ==typeid(FloatImageObj) ) 
  1685 	{
  1686 		saveState(selection->getParObj());
  1687 		FloatImageObj* fio=dynamic_cast <FloatImageObj*> (selection);
  1688 		BranchObj* par=(BranchObj*)(fio->getParObj());
  1689 		fio->unselect();
  1690 		selection=NULL;
  1691 		par->removeFloatImage(fio);
  1692 		selection=par;
  1693 		selection->select();
  1694 		ensureSelectionVisible();
  1695 		mapCenter->reposition();
  1696 		adjustCanvasSize();
  1697 	}
  1698 }
  1699 
  1700 LinkableMapObj* MapEditor::getSelection()
  1701 {
  1702 	return selection;
  1703 }
  1704 
  1705 bool MapEditor::select (const QString &s)
  1706 {
  1707 	LinkableMapObj *lmo=mapCenter->findObjBySelect(s);
  1708 
  1709 	// Finally select the found object
  1710 	if (lmo)
  1711 	{
  1712 		if (selection) unselect();
  1713 		selection=lmo;
  1714 		selection->select();
  1715 		adjustCanvasSize();
  1716 		ensureSelectionVisible();
  1717 		return true;
  1718 	} 
  1719 	return false;
  1720 }
  1721 
  1722 void MapEditor::unselect()
  1723 {
  1724 	if (selection) 
  1725 	{
  1726 		selectionLast=selection;
  1727 		selection->unselect();
  1728 		selection=NULL;
  1729 	}
  1730 }	
  1731 
  1732 void MapEditor::reselect()
  1733 {
  1734 	if (selectionLast)
  1735 	{
  1736 		selection=selectionLast;
  1737 		selection->select();
  1738 		selectionLast=NULL;
  1739 	}
  1740 }	
  1741 
  1742 void MapEditor::selectNextBranch()
  1743 {
  1744 	// Increase number of branch
  1745 	if (selection)
  1746 	{
  1747 		QString s=selection->getSelectString();
  1748 		QString part;
  1749 		QString typ;
  1750 		QString num;
  1751 
  1752 		// Where am I? 
  1753 		part=s.section(",",-1);
  1754 		typ=part.left (3);
  1755 		num=part.right(part.length() - 3);
  1756 
  1757 		s=s.left (s.length() -num.length());
  1758 
  1759 		// Go to next lmo
  1760 		num=QString ("%1").arg(num.toUInt()+1);
  1761 
  1762 		s=s+num;
  1763 		
  1764 		// Try to select this one
  1765 		if (select (s)) return;
  1766 
  1767 		// We have no direct successor, 
  1768 		// try to increase the parental number in order to
  1769 		// find a successor with same depth
  1770 
  1771 		int d=selection->getDepth();
  1772 		int oldDepth=d;
  1773 		int i;
  1774 		bool found=false;
  1775 		bool b;
  1776 		while (!found && d>0)
  1777 		{
  1778 			s=s.section (",",0,d-1);
  1779 			// replace substring of current depth in s with "1"
  1780 			part=s.section(",",-1);
  1781 			typ=part.left (3);
  1782 			num=part.right(part.length() - 3);
  1783 
  1784 			if (d>1)
  1785 			{	
  1786 				// increase number of parent
  1787 				num=QString ("%1").arg(num.toUInt()+1);
  1788 				s=s.section (",",0,d-2) + ","+ typ+num;
  1789 			} else
  1790 			{
  1791 				// Special case, look at orientation
  1792 				if (selection->getOrientation()==OrientRightOfCenter)
  1793 					num=QString ("%1").arg(num.toUInt()+1);
  1794 				else	
  1795 					num=QString ("%1").arg(num.toUInt()-1);
  1796 				s=typ+num;
  1797 			}	
  1798 
  1799 			if (select (s))
  1800 				// pad to oldDepth, select the first branch for each depth
  1801 				for (i=d;i<oldDepth;i++)
  1802 				{
  1803 					b=select (s);
  1804 					if (b)
  1805 					{	
  1806 						if ( ((BranchObj*)selection)->countBranches()>0)
  1807 							s+=",bo:0";
  1808 						else	
  1809 							break;
  1810 					} else
  1811 						break;
  1812 				}	
  1813 
  1814 			// try to select the freshly built string
  1815 			found=select(s);
  1816 			d--;
  1817 		}
  1818 		return;
  1819 	}	
  1820 }
  1821 
  1822 void MapEditor::selectPrevBranch()
  1823 {
  1824 	// Decrease number of branch
  1825 	if (selection)
  1826 	{
  1827 		QString s=selection->getSelectString();
  1828 		QString part;
  1829 		QString typ;
  1830 		QString num;
  1831 
  1832 		// Where am I? 
  1833 		part=s.section(",",-1);
  1834 		typ=part.left (3);
  1835 		num=part.right(part.length() - 3);
  1836 
  1837 		s=s.left (s.length() -num.length());
  1838 
  1839 		// Go to next lmo
  1840 		num=QString ("%1").arg(num.toUInt()-1);
  1841 
  1842 		s=s+num;
  1843 		
  1844 		// Try to select this one
  1845 		if (select (s)) return;
  1846 
  1847 		// We have no direct precessor, 
  1848 		// try to decrease the parental number in order to
  1849 		// find a precessor with same depth
  1850 
  1851 		int d=selection->getDepth();
  1852 		int oldDepth=d;
  1853 		int i;
  1854 		bool found=false;
  1855 		bool b;
  1856 		while (!found && d>0)
  1857 		{
  1858 			s=s.section (",",0,d-1);
  1859 			// replace substring of current depth in s with "1"
  1860 			part=s.section(",",-1);
  1861 			typ=part.left (3);
  1862 			num=part.right(part.length() - 3);
  1863 
  1864 			if (d>1)
  1865 			{
  1866 				// decrease number of parent
  1867 				num=QString ("%1").arg(num.toUInt()-1);
  1868 				s=s.section (",",0,d-2) + ","+ typ+num;
  1869 			} else
  1870 			{
  1871 				// Special case, look at orientation
  1872 				if (selection->getOrientation()==OrientRightOfCenter)
  1873 					num=QString ("%1").arg(num.toUInt()-1);
  1874 				else	
  1875 					num=QString ("%1").arg(num.toUInt()+1);
  1876 				s=typ+num;
  1877 			}	
  1878 
  1879 			if (select(s))
  1880 				// pad to oldDepth, select the last branch for each depth
  1881 				for (i=d;i<oldDepth;i++)
  1882 				{
  1883 					b=select (s);
  1884 					if (b)
  1885 						if ( ((BranchObj*)selection)->countBranches()>0)
  1886 							s+=",bo:"+ QString ("%1").arg( ((BranchObj*)selection)->countBranches()-1 );
  1887 						else	
  1888 							break;
  1889 					else
  1890 						break;
  1891 				}	
  1892 			
  1893 			// try to select the freshly built string
  1894 			found=select(s);
  1895 			d--;
  1896 		}
  1897 		return;
  1898 	}	
  1899 }
  1900 
  1901 void MapEditor::selectUpperBranch()
  1902 {
  1903 	// Finish open lineEdits
  1904 	if (lineedit) finishedLineEditNoSave();
  1905 
  1906 	if (selection) 
  1907 	{
  1908 		if (typeid(*selection) == typeid(BranchObj))
  1909 		{
  1910 			if (selection->getOrientation()==OrientRightOfCenter)
  1911 				selectPrevBranch();
  1912 			else
  1913 				if (selection->getDepth()==1)
  1914 					selectNextBranch();
  1915 				else
  1916 					selectPrevBranch();
  1917 		}		
  1918 	}
  1919 }
  1920 
  1921 void MapEditor::selectLowerBranch()
  1922 {
  1923 	// Finish open lineEdits
  1924 	if (lineedit) finishedLineEditNoSave();
  1925 
  1926 	if (selection) 
  1927 	{
  1928 		if (typeid(*selection) == typeid(BranchObj))
  1929 		{
  1930 			if (selection->getOrientation()==OrientRightOfCenter)
  1931 				selectNextBranch();
  1932 			else
  1933 				if (selection->getDepth()==1)
  1934 					selectPrevBranch();
  1935 				else
  1936 					selectNextBranch();
  1937 		}		
  1938 	}
  1939 }
  1940 
  1941 
  1942 void MapEditor::selectLeftBranch()
  1943 {
  1944 	// Finish open lineEdits
  1945 	if (lineedit) finishedLineEditNoSave();
  1946 
  1947 	BranchObj* bo;
  1948 	BranchObj* par;
  1949 	if (selection) 
  1950 	{
  1951 		if (typeid(*selection) == typeid(MapCenterObj))
  1952 		{
  1953 			par=  (BranchObj*) selection;
  1954 			bo=par->getLastSelectedBranch();
  1955 			if (bo)
  1956 			{
  1957 				// Workaround for reselecting on left and right side
  1958 				if (bo->getOrientation()==OrientRightOfCenter)
  1959 				{
  1960 					bo=par->getLastBranch();
  1961 				}	
  1962 				if (bo)
  1963 				{
  1964 					par->unselect();
  1965 					selection=bo;
  1966 					selection->select();
  1967 					adjustCanvasSize();
  1968 					ensureSelectionVisible();
  1969 				}
  1970 			}	
  1971 		} else
  1972 		{
  1973 			par=(BranchObj*)(selection->getParObj());
  1974 			if (selection->getOrientation()==OrientRightOfCenter)
  1975 			{
  1976 				if (typeid(*selection) == typeid(BranchObj) ||
  1977 					typeid(*selection) == typeid(FloatImageObj))
  1978 				{
  1979 					selection->unselect();
  1980 					selection=par;
  1981 					selection->select();
  1982 					adjustCanvasSize();
  1983 					ensureSelectionVisible();
  1984 				}
  1985 			} else
  1986 			{
  1987 				if (typeid(*selection) == typeid(BranchObj) )
  1988 				{
  1989 					bo=((BranchObj*)selection)->getLastSelectedBranch();
  1990 					if (bo) 
  1991 					{
  1992 						selection->unselect();
  1993 						selection=bo;
  1994 						selection->select();
  1995 						adjustCanvasSize();
  1996 						ensureSelectionVisible();
  1997 					}
  1998 				}
  1999 			}
  2000 		}	
  2001 	}
  2002 }
  2003 
  2004 void MapEditor::selectRightBranch()
  2005 {
  2006 	// Finish open lineEdits
  2007 	if (lineedit) finishedLineEditNoSave();
  2008 
  2009 	BranchObj* bo;
  2010 	BranchObj* par;
  2011 
  2012 	if (selection) 
  2013 	{
  2014 		if (typeid(*selection) == typeid(MapCenterObj))
  2015 		{
  2016 			par=  (BranchObj*) selection;
  2017 			bo=par->getLastSelectedBranch();
  2018 			if (bo)
  2019 			{
  2020 				// Workaround for relecting on left and right side
  2021 				if (bo->getOrientation()==OrientLeftOfCenter)
  2022 					bo=par->getFirstBranch();
  2023 				if (bo)
  2024 				{
  2025 					par->unselect();
  2026 					selection=bo;
  2027 					selection->select();
  2028 					ensureSelectionVisible();
  2029 				}
  2030 			}
  2031 		} else
  2032 		{
  2033 			par=(BranchObj*)(selection->getParObj());
  2034 			if (selection->getOrientation()==OrientLeftOfCenter)
  2035 			{
  2036 				if (typeid(*selection) == typeid(BranchObj) ||
  2037 					typeid(*selection) == typeid(FloatImageObj))
  2038 				{
  2039 					selection->unselect();
  2040 					selection=par;
  2041 					selection->select();
  2042 					adjustCanvasSize();
  2043 					ensureSelectionVisible();
  2044 				}
  2045 			} else
  2046 			{
  2047 				if (typeid(*selection) == typeid(BranchObj) )
  2048 				{
  2049 					bo=((BranchObj*)selection)->getLastSelectedBranch();
  2050 					if (bo) 
  2051 					{
  2052 						selection->unselect();
  2053 						selection=bo;
  2054 						selection->select();
  2055 						adjustCanvasSize();
  2056 						ensureSelectionVisible();
  2057 					}
  2058 				}
  2059 			}
  2060 		}
  2061 	}
  2062 }
  2063 
  2064 void MapEditor::selectFirstBranch()
  2065 {
  2066 	// Finish open lineEdits
  2067 	if (lineedit) finishedLineEditNoSave();
  2068 
  2069 	BranchObj *bo1;
  2070 	BranchObj *bo2;
  2071 	BranchObj* par;
  2072 	if (selection) {
  2073 		if (typeid(*selection) == typeid(BranchObj))
  2074 		{
  2075 			bo1=  (BranchObj*) selection;
  2076 			par=(BranchObj*)(bo1->getParObj());
  2077 			bo2=par->getFirstBranch();
  2078 			if (bo2) {
  2079 				bo1->unselect();
  2080 				selection=bo2;
  2081 				selection->select();
  2082 				ensureSelectionVisible();
  2083 			}
  2084 		}		
  2085 		adjustCanvasSize();
  2086 	}
  2087 }
  2088 
  2089 void MapEditor::selectLastBranch()
  2090 {
  2091 	// Finish open lineEdits
  2092 	if (lineedit) finishedLineEditNoSave();
  2093 
  2094 	BranchObj *bo1;
  2095 	BranchObj *bo2;
  2096 	BranchObj* par;
  2097 	if (selection) {
  2098 		if (typeid(*selection) == typeid(BranchObj))
  2099 		{
  2100 			bo1=  (BranchObj*) selection;
  2101 			par=(BranchObj*)(bo1->getParObj());
  2102 			bo2=par->getLastBranch();
  2103 			if (bo2) {
  2104 				bo1->unselect();
  2105 				selection=bo2;
  2106 				selection->select();
  2107 				ensureSelectionVisible();
  2108 			}
  2109 		}		
  2110 		adjustCanvasSize();
  2111 	}
  2112 }
  2113 
  2114 void MapEditor::setColor(QColor c)
  2115 {
  2116 	actColor=c;
  2117 }
  2118 
  2119 void MapEditor::selectBackgroundColor()
  2120 {
  2121 	// Finish open lineEdits
  2122 	if (lineedit) finishedLineEditNoSave();
  2123 
  2124 	QColor col = QColorDialog::getColor( mapCanvas->backgroundColor(), this );
  2125 	if ( !col.isValid() ) return;
  2126 	setBackgroundColor( col );
  2127 	saveState();
  2128 }
  2129 
  2130 void MapEditor::setBackgroundColor(QColor c)
  2131 {
  2132 	mapCanvas->setBackgroundColor (c);
  2133 }
  2134 
  2135 QColor MapEditor::pickColor()
  2136 {
  2137 	if (selection) 
  2138 	{
  2139 		if (typeid(*selection) == typeid(BranchObj) ||
  2140 			typeid(*selection) == typeid(MapCenterObj))
  2141 		{
  2142 			BranchObj *bo=(BranchObj*)selection;
  2143 			actColor=bo->getColor(); 
  2144 		}    
  2145 	}
  2146 	return actColor;
  2147 }
  2148 
  2149 void MapEditor::colorItem()
  2150 {
  2151 	if (selection) 
  2152 	{
  2153 		if (typeid(*selection) == typeid(BranchObj) ||
  2154 			typeid(*selection) == typeid(MapCenterObj))
  2155 		{
  2156 			saveState(selection);	//TODO undoCommand
  2157 			BranchObj *bo=(BranchObj*)selection;
  2158 			bo->setColor(actColor, false); // color links, color childs
  2159 		}    
  2160 	}
  2161 }
  2162 
  2163 void MapEditor::colorBranch()
  2164 {
  2165 	if (selection) 
  2166 	{
  2167 		if (typeid(*selection) == typeid(BranchObj) ||
  2168 			typeid(*selection) == typeid(MapCenterObj))
  2169 		{
  2170 			saveState(selection);	//TODO undoCommand
  2171 			BranchObj *bo=(BranchObj*)selection;
  2172 			bo->setColor(actColor, true); // color links, color childs
  2173 		}    
  2174 	}
  2175 }
  2176 
  2177 
  2178 void MapEditor::toggleStandardFlag(QString f)
  2179 {
  2180 	if (selection)
  2181 	{
  2182 		saveState(selection);// TODO undoCommand	
  2183 		((BranchObj*)selection)->toggleStandardFlag (f,actionSettingsUseFlagGroups);
  2184 	}	
  2185 }
  2186 
  2187 void MapEditor::setViewCenter()
  2188 {
  2189 	// transform to CanvasView Coord:
  2190 	QPoint p=worldMatrix().map(movingCenter);
  2191 	center ( p.x(), p.y());
  2192 }
  2193 
  2194 
  2195 BranchObj* MapEditor::findText (QString s, bool cs)
  2196 {
  2197 	if (!itFind) 
  2198 	{	// Nothing found or new find process
  2199 		if (EOFind)
  2200 			// nothing found, start again
  2201 			EOFind=false;
  2202 		itFind=mapCenter->first();
  2203 	}	
  2204 	bool searching=true;
  2205 	bool foundNote=false;
  2206 	while (searching && !EOFind)
  2207 	{
  2208 		if (itFind)
  2209 		{
  2210 			// Searching in Note
  2211 			if (itFind->getNote().contains(s,cs))
  2212 			{
  2213 				if (selection!=itFind) 
  2214 				{
  2215 					if (selection) ((BranchObj*)selection)->unselect();
  2216 					selection=itFind;
  2217 					selection->select();
  2218 					adjustCanvasSize();
  2219 					ensureSelectionVisible();
  2220 				}
  2221 				if (textEditor->findText(s,cs)) 
  2222 				{
  2223 					searching=false;
  2224 					foundNote=true;
  2225 				}	
  2226 			}
  2227 			// Searching in Heading
  2228 			if (searching && itFind->getHeading().contains (s,cs) ) 
  2229 			{
  2230 				if (selection) ((BranchObj*)selection)->unselect();
  2231 				selection=itFind;
  2232 				selection->select();
  2233 				adjustCanvasSize();
  2234 				ensureSelectionVisible();
  2235 				searching=false;
  2236 			}
  2237 		}	
  2238 		if (!foundNote)
  2239 		{
  2240 			itFind=itFind->next();
  2241 			if (!itFind) EOFind=true;
  2242 		}
  2243 	}	
  2244 	if (!searching)
  2245 	{
  2246 		adjustCanvasSize();
  2247 		return (BranchObj*)selection;
  2248 	}	else
  2249 		return NULL;
  2250 }
  2251 
  2252 void MapEditor::findReset()
  2253 {	// Necessary if text to find changes during a find process
  2254 	itFind=NULL;
  2255 	EOFind=false;
  2256 }
  2257 
  2258 void MapEditor::openURL()
  2259 {
  2260 	if (selection )
  2261 	{
  2262 		if (typeid(*selection) == typeid(BranchObj) ||
  2263 			typeid(*selection) == typeid(MapCenterObj))
  2264 		{
  2265 			QString url=((BranchObj*)selection)->getURL();
  2266 
  2267 			QProcess *proc = new QProcess( this );
  2268 
  2269 			proc->addArgument( settings.readEntry("/vym/mainwindow/readerURL" ));
  2270 			proc->addArgument( url);
  2271 
  2272 			if ( !proc->start() ) 
  2273 				// error handling
  2274 				if (mainWindow->settingsURL() ) 
  2275 					openURL();
  2276 		}	
  2277 	}	
  2278 }
  2279 
  2280 void MapEditor::editURL()
  2281 {
  2282 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2283 			typeid(*selection) == typeid(MapCenterObj)) )
  2284 	{		
  2285 		bool ok;
  2286 		BranchObj *bo=(BranchObj*)selection;
  2287 		QString text = QInputDialog::getText(
  2288 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2289 				bo->getURL(), &ok, this );
  2290 		if ( ok) 
  2291 		{
  2292 			// user entered something and pressed OK
  2293 			saveState("setURL (\""+bo->getURL()+"\")","setURL (\""+text+"\")");	
  2294 			bo->setURL (text);
  2295 			updateActions();
  2296 		}	
  2297 	}
  2298 }
  2299 
  2300 void MapEditor::editHeading2URL()
  2301 {
  2302 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2303 			typeid(*selection) == typeid(MapCenterObj)) )
  2304 	{		
  2305 		BranchObj *bo=(BranchObj*)selection;
  2306 		saveState("setURL (\""+bo->getURL()+"\")","setURL (\""+bo->getHeading()+"\")");	
  2307 		bo->setURL (bo->getHeading());
  2308 		updateActions();
  2309 	}
  2310 }	
  2311 
  2312 void MapEditor::editBugzilla2URL()
  2313 {
  2314 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2315 			typeid(*selection) == typeid(MapCenterObj)) )
  2316 	{		
  2317 		BranchObj *bo=(BranchObj*)selection;
  2318 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
  2319 		saveState("setURL (\""+bo->getURL()+"\")","setURL (\""+url+"\")");	
  2320 		bo->setURL (url);
  2321 		updateActions();
  2322 	}
  2323 }	
  2324 
  2325 void MapEditor::editFATE2URL()
  2326 {
  2327 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2328 			typeid(*selection) == typeid(MapCenterObj)) )
  2329 	{		
  2330 		BranchObj *bo=(BranchObj*)selection;
  2331 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
  2332 		saveState("setURL (\""+bo->getURL()+"\")","setURL (\""+url+"\")");	
  2333 		bo->setURL (url);
  2334 		updateActions();
  2335 	}
  2336 }	
  2337 
  2338 void MapEditor::editVymLink()
  2339 {
  2340 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2341 			typeid(*selection) == typeid(MapCenterObj)) )
  2342 	{		
  2343 		BranchObj *bo=(BranchObj*)selection;
  2344 		QFileDialog *fd=new QFileDialog( this,__VYM " - " +tr("Link to another map"));
  2345 		fd->addFilter (QString (tr("vym map") + " (*.vym)"));
  2346 		fd->setCaption(__VYM " - " +tr("Link to another map"));
  2347 		if (! bo->getVymLink().isEmpty() )
  2348 			fd->setSelection( bo->getVymLink() );
  2349 		fd->show();
  2350 
  2351 		QString fn;
  2352 		if ( fd->exec() == QDialog::Accepted )
  2353 		{
  2354 			saveState("setVymLink (\""+bo->getVymLink()+"\")","setVymLink (\""+fd->selectedFile()+"\")");	
  2355 			bo->setVymLink (fd->selectedFile() );
  2356 			updateActions();
  2357 			mapCenter->reposition();
  2358 			adjustCanvasSize();
  2359 			canvas()->update();
  2360 		}
  2361 	}
  2362 }
  2363 
  2364 void MapEditor::deleteVymLink()
  2365 {
  2366 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2367 			typeid(*selection) == typeid(MapCenterObj)) )
  2368 	{		
  2369 		BranchObj *bo=(BranchObj*)selection;
  2370 		saveState("setVymLink (\""+bo->getVymLink()+"\")","setVymLink (\"\")");	
  2371 		bo->setVymLink ("" );
  2372 		updateActions();
  2373 		mapCenter->reposition();
  2374 		adjustCanvasSize();
  2375 		canvas()->update();
  2376 	}
  2377 }
  2378 
  2379 QString MapEditor::getVymLink()
  2380 {
  2381 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2382 			typeid(*selection) == typeid(MapCenterObj)) )
  2383 	{		
  2384 		return ((BranchObj*)selection)->getVymLink();
  2385 	}
  2386 	return "";
  2387 	
  2388 }
  2389 
  2390 void MapEditor::removeBranchHere()
  2391 {
  2392 	if (selection && (typeid(*selection) == typeid(BranchObj) ))
  2393 	{		
  2394 		BranchObj* bo=(BranchObj*)selection;
  2395 		BranchObj* par=(BranchObj*)(bo->getParObj());
  2396 		if (bo->getDepth()==1)
  2397 			saveState();
  2398 		else	
  2399 			saveState(selection->getParObj());	// TODO undoCommand
  2400 		QString sel=selection->getSelectString();
  2401 		unselect();
  2402 		par->removeBranchHere(bo);
  2403 		mapCenter->reposition();
  2404 		select (sel);
  2405 	}	
  2406 }
  2407 
  2408 void MapEditor::removeChilds()
  2409 {
  2410 	if (selection && (typeid(*selection) == typeid(BranchObj) ))
  2411 	{		
  2412 		saveState(selection->getParObj());
  2413 		((BranchObj*)selection)->removeChilds();
  2414 		mapCenter->reposition();
  2415 	}	
  2416 }
  2417 
  2418 void MapEditor::editMapInfo()
  2419 {
  2420 	ExtraInfoDialog dia;
  2421 	dia.setMapName (getFileName() );
  2422 	dia.setAuthor (mapCenter->getAuthor() );
  2423 	dia.setComment(mapCenter->getComment() );
  2424 
  2425 	// Calc some stats
  2426 	QString stats;
  2427     int i=0;
  2428     QCanvasItemList l=canvas()->allItems();
  2429     for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) 
  2430         i++;
  2431     stats+=QString ("%1 items on canvas\n").arg (i,6);
  2432 
  2433 	uint b=0;
  2434 	uint f=0;
  2435 	uint n=0;
  2436 	uint xl=0;
  2437 	BranchObj *bo;
  2438 	bo=mapCenter->first();
  2439 	while (bo) 
  2440 	{
  2441 		if (!bo->getNote().isEmpty() ) n++;
  2442 		f+= bo->countFloatImages();
  2443 		b++;
  2444 		xl+=bo->countXLinks();
  2445 		bo=bo->next();
  2446 	}
  2447     stats+=QString ("%1 branches\n").arg (b-1,6);
  2448     stats+=QString ("%1 xLinks \n").arg (xl,6);
  2449     stats+=QString ("%1 notes\n").arg (n,6);
  2450     stats+=QString ("%1 images\n").arg (f,6);
  2451 	dia.setStats (stats);
  2452 
  2453 	// Finally show dialog
  2454 	if (dia.exec() == QDialog::Accepted)
  2455 	{
  2456 		saveState();	//TODO undoCommand
  2457 		mapCenter->setAuthor (dia.getAuthor() );
  2458 		mapCenter->setComment (dia.getComment() );
  2459 	}
  2460 }
  2461 
  2462 void MapEditor::updateActions()
  2463 {
  2464 	QAction *a;
  2465 	if (getLinkColorHint()==HeadingColor) 
  2466 		actionFormatLinkColorHint->setOn(true);
  2467 	else	
  2468 		actionFormatLinkColorHint->setOn(false);
  2469 
  2470 	switch (linkstyle)
  2471 	{
  2472 		case StyleLine: 
  2473 			actionFormatLinkStyleLine->setOn(true);
  2474 			break;
  2475 		case StyleParabel:
  2476 			actionFormatLinkStyleParabel->setOn(true);
  2477 			break;
  2478 		case StylePolyLine:	
  2479 			actionFormatLinkStylePolyLine->setOn(true);
  2480 			break;
  2481 		case StylePolyParabel:	
  2482 			actionFormatLinkStylePolyParabel->setOn(true);
  2483 			break;
  2484 		default:
  2485 			break;
  2486 	}	
  2487 
  2488 	QPixmap pix( 16, 16 );
  2489     pix.fill( mapCanvas->backgroundColor() );
  2490     actionFormatBackColor->setIconSet( pix );
  2491     pix.fill( defLinkColor );
  2492     actionFormatLinkColor->setIconSet( pix );
  2493 
  2494 	actionEditUndo->setEnabled( mapChanged );
  2495 	actionFileSave->setEnabled( mapUnsaved );
  2496 
  2497 	if (selection)
  2498 	{
  2499 		if ( (typeid(*selection) == typeid(BranchObj)) || 
  2500 			(typeid(*selection) == typeid(MapCenterObj))  )
  2501 		{
  2502 			BranchObj *bo=(BranchObj*)selection;
  2503 			// Take care of links
  2504 			if (bo->countXLinks()==0)
  2505 			{
  2506 				branchLinksContextMenu->clear();
  2507 				branchLinksContextMenu->insertItem ("No xLink available");
  2508 				branchLinksContextMenuDup->clear();
  2509 				branchLinksContextMenuDup->insertItem ("No xLink available");
  2510 				
  2511 			} else
  2512 			{
  2513 				BranchObj *bot;
  2514 				QString s;
  2515 				branchLinksContextMenu->clear();
  2516 				branchLinksContextMenuDup->clear();
  2517 				for (int i=0; i<=bo->countXLinks();i++)
  2518 				{
  2519 					bot=bo->XLinkTargetAt(i);
  2520 					if (bot)
  2521 					{
  2522 						s=bot->getHeading();
  2523 						if (s.length()>25)
  2524 							s=s.left(25)+"...";
  2525 						branchLinksContextMenu->insertItem (s);
  2526 						branchLinksContextMenuDup->insertItem (s);
  2527 					}	
  2528 				}
  2529 			}
  2530 
  2531 			standardFlagsDefault->setEnabled (true);
  2532 
  2533 			if ( bo->getURL().isEmpty() )
  2534 				actionEditOpenURL->setEnabled (false);
  2535 			else	
  2536 				actionEditOpenURL->setEnabled (true);
  2537 
  2538 			if ( bo->getVymLink().isEmpty() )
  2539 			{
  2540 				actionEditOpenVymLink->setEnabled (false);
  2541 				actionEditDeleteVymLink->setEnabled (false);
  2542 			} else	
  2543 			{
  2544 				actionEditOpenVymLink->setEnabled (true);
  2545 				actionEditDeleteVymLink->setEnabled (true);
  2546 			}	
  2547 
  2548 			actionEditCopy->setEnabled (true);	
  2549 			actionEditCut->setEnabled (true);	
  2550 			if (!clipboardEmpty)
  2551 				actionEditPaste->setEnabled (true);	
  2552 			else	
  2553 				actionEditPaste->setEnabled (false);	
  2554 			for (a=actionListBranches.first();a;a=actionListBranches.next())
  2555 				a->setEnabled(true);
  2556 			actionEditDelete->setEnabled (true);
  2557 			actionEditToggleFloatExport->setEnabled (false);
  2558 			switch (selection->getFrameType())
  2559 			{
  2560 				case NoFrame: 
  2561 					actionFormatFrameNone->setOn(true);
  2562 					break;
  2563 				case Rectangle:
  2564 					actionFormatFrameRectangle->setOn(true);
  2565 					break;
  2566 				default:
  2567 					break;
  2568 			}	
  2569 			actionFormatIncludeImagesVer->setOn
  2570 				( ((BranchObj*)selection)->getIncludeImagesVer());
  2571 			actionFormatIncludeImagesHor->setOn
  2572 				( ((BranchObj*)selection)->getIncludeImagesHor());
  2573 			actionFormatHideLinkUnselected->setOn
  2574 				(selection->getHideLinkUnselected());
  2575 		}
  2576 		if ( (typeid(*selection) == typeid(FloatImageObj)) )
  2577 		{
  2578 			standardFlagsDefault->setEnabled (false);
  2579 
  2580 			actionEditOpenURL->setEnabled (false);
  2581 			actionEditOpenVymLink->setEnabled (false);
  2582 			actionEditDeleteVymLink->setEnabled (false);	
  2583 
  2584 			actionEditCopy->setEnabled (true);
  2585 			actionEditCut->setEnabled (true);	
  2586 			actionEditPaste->setEnabled (false);	//FIXME
  2587 			for (a=actionListBranches.first();a;a=actionListBranches.next())
  2588 				a->setEnabled(false);
  2589 			actionEditDelete->setEnabled (true);
  2590 			actionEditToggleFloatExport->setOn
  2591 				( ((FloatImageObj*)selection)->getFloatExport() );
  2592 			actionFormatHideLinkUnselected->setOn
  2593 				( selection->getHideLinkUnselected());
  2594 		}
  2595 
  2596 	} else
  2597 	{
  2598 		standardFlagsDefault->setEnabled (false);
  2599 
  2600 		actionEditCopy->setEnabled (false);	
  2601 		actionEditCut->setEnabled (false);	
  2602 		actionEditPaste->setEnabled (false);	
  2603 		for (a=actionListBranches.first();a;a=actionListBranches.next())
  2604 			a->setEnabled(false);
  2605 
  2606 		actionEditOpenURL->setEnabled (false);
  2607 		actionEditOpenVymLink->setEnabled (false);
  2608 		actionEditDeleteVymLink->setEnabled (false);	
  2609 		actionEditHeading2URL->setEnabled (false);	
  2610 		actionEditDelete->setEnabled (false);
  2611 		actionEditToggleFloatExport->setEnabled (false);
  2612 	}	
  2613 }
  2614 
  2615 void MapEditor::updateNoteFlag()
  2616 {
  2617 	if (selection)
  2618 		if ( (typeid(*selection) == typeid(BranchObj)) || 
  2619 			(typeid(*selection) == typeid(MapCenterObj))  )
  2620 			((BranchObj*)selection)->updateNoteFlag();
  2621 }
  2622 
  2623 void MapEditor::setLinkStyle (LinkStyle ls)
  2624 {
  2625 	linkstyle=ls;
  2626 
  2627 	saveState();	// TODO undoCommand
  2628 	BranchObj *bo;
  2629 	bo=mapCenter->first();
  2630 	bo=bo->next();
  2631 	while (bo) 
  2632 	{
  2633 		bo->setLinkStyle(bo->getDefLinkStyle());
  2634 		bo=bo->next();
  2635 	}
  2636 	mapCenter->reposition();
  2637 }
  2638 
  2639 LinkStyle MapEditor::getLinkStyle ()
  2640 {
  2641 	return linkstyle;
  2642 }	
  2643 
  2644 void MapEditor::setLinkColor(QColor c)
  2645 {
  2646 	defLinkColor=c;
  2647 	updateActions();
  2648 }
  2649 
  2650 void MapEditor::setLinkColorHint()
  2651 {
  2652 	// called from setLinkColorHint(lch) or at end of parse
  2653 	BranchObj *bo;
  2654 	bo=mapCenter->first();
  2655 	while (bo) 
  2656 	{
  2657 		bo->setLinkColor();
  2658 		bo=bo->next();
  2659 	}
  2660 }
  2661 
  2662 void MapEditor::setLinkColorHint(LinkColorHint lch)
  2663 {
  2664 	linkcolorhint=lch;
  2665 	setLinkColorHint();
  2666 }
  2667 
  2668 void MapEditor::toggleLinkColorHint()
  2669 {
  2670 	if (linkcolorhint==HeadingColor)
  2671 		linkcolorhint=DefaultColor;
  2672 	else	
  2673 		linkcolorhint=HeadingColor;
  2674 	BranchObj *bo;
  2675 	bo=mapCenter->first();
  2676 	while (bo) 
  2677 	{
  2678 		bo->setLinkColor();
  2679 		bo=bo->next();
  2680 	}
  2681 }
  2682 
  2683 LinkColorHint MapEditor::getLinkColorHint()
  2684 {
  2685 	return linkcolorhint;
  2686 }
  2687 
  2688 QColor MapEditor::getDefLinkColor()
  2689 {
  2690 	return defLinkColor;
  2691 }
  2692 
  2693 void MapEditor::setDefXLinkColor(QColor col)
  2694 {
  2695 	defXLinkColor=col;
  2696 }
  2697 
  2698 QColor MapEditor::getDefXLinkColor()
  2699 {
  2700 	return defXLinkColor;
  2701 }
  2702 
  2703 void MapEditor::setDefXLinkWidth (int w)
  2704 {
  2705 	defXLinkWidth=w;
  2706 }
  2707 
  2708 int MapEditor::getDefXLinkWidth()
  2709 {
  2710 	return defXLinkWidth;
  2711 }
  2712 
  2713 void MapEditor::selectLinkColor()
  2714 {
  2715 	// Finish open lineEdits
  2716 	if (lineedit) finishedLineEditNoSave();
  2717 
  2718 	QColor col = QColorDialog::getColor( defLinkColor, this );
  2719 	if ( !col.isValid() ) return;
  2720 	setLinkColor( col );
  2721 	saveState();	//TODO undoCommand
  2722 
  2723 }
  2724 
  2725 void MapEditor::toggleScroll()
  2726 {
  2727 	if (selection && (typeid(*selection) == typeid(BranchObj)) )
  2728 	{
  2729 		BranchObj *bo=((BranchObj*)selection);
  2730 		if (bo->countBranches()==0) return;
  2731 		if (bo->getDepth()==0) return;
  2732 		saveState(selection);
  2733 		bo->toggleScroll();
  2734 		adjustCanvasSize();
  2735 		canvas()->update();
  2736 	}
  2737 }
  2738 
  2739 void MapEditor::unScrollAll()
  2740 {
  2741 	BranchObj *bo;
  2742 	bo=mapCenter->first();
  2743 	while (bo) 
  2744 	{
  2745 		if (bo->isScrolled()) bo->toggleScroll();
  2746 		bo=bo->next();
  2747 	}
  2748 }
  2749 
  2750 void MapEditor::loadFloatImage ()
  2751 {
  2752 	if (selection && 
  2753 		(typeid(*selection) == typeid(BranchObj)) || 
  2754 		(typeid(*selection) == typeid(MapCenterObj))  )
  2755 	{
  2756 		BranchObj *bo=((BranchObj*)selection);
  2757 
  2758 		QFileDialog *fd=new QFileDialog( this,QString ("vym - ")+tr("Load image"));
  2759 		fd->setMode (QFileDialog::ExistingFiles);
  2760 		fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  2761 		ImagePreview *p =new ImagePreview (fd);
  2762 		fd->setContentsPreviewEnabled( TRUE );
  2763 		fd->setContentsPreview( p, p );
  2764 		fd->setPreviewMode( QFileDialog::Contents );
  2765 		fd->setCaption(__VYM " - " +tr("Load image"));
  2766 		fd->setDir (lastImageDir);
  2767 		fd->show();
  2768 
  2769 		QString fn;
  2770 		if ( fd->exec() == QDialog::Accepted )
  2771 		{
  2772 			saveState(selection);
  2773 			lastImageDir=fn.left(fn.findRev ("/"));
  2774 			QStringList flist = fd->selectedFiles();
  2775 			QStringList::Iterator it = flist.begin();
  2776 			while( it != flist.end() ) 
  2777 			{
  2778 				fn = *it;
  2779 				bo->addFloatImage();
  2780 				// TODO check if load was successful
  2781 				bo->getLastFloatImage()->load(*it);
  2782 				bo->getLastFloatImage()->setOriginalFilename(fn);
  2783 				++it;
  2784 			}
  2785 
  2786 			mapCenter->reposition();
  2787 			adjustCanvasSize();
  2788 			canvas()->update();
  2789 		}
  2790 	}
  2791 }
  2792 
  2793 void MapEditor::saveFloatImage (int item)
  2794 {
  2795 	if (selection && 
  2796 		(typeid(*selection) == typeid(FloatImageObj)) )
  2797 	{
  2798 		FloatImageObj *fio=((FloatImageObj*)selection);
  2799 		const char* fmt = saveImageFormatMenu->text(item);
  2800 
  2801 		QFileDialog *fd=new QFileDialog( this, tr("vym - save image as") + fmt);
  2802 		fd->addFilter ("PNG (*.png)");
  2803 		fd->addFilter ("BMP (*.bmp)");
  2804 		fd->addFilter ("XBM (*.xbm)");
  2805 		fd->addFilter ("JPG (*.jpg)");
  2806 		fd->addFilter ("XPM (*.xpm)");
  2807 		fd->addFilter ("GIF (*.gif)");
  2808 		fd->addFilter ("PNM (*.pnm)");
  2809 		fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  2810 		fd->setCaption(__VYM " - " +tr("Save image as %1").arg(fmt));
  2811 		fd->setMode( QFileDialog::AnyFile );
  2812 		fd->setSelection (fio->getOriginalFilename());
  2813 		fd->show();
  2814 
  2815 		QString fn;
  2816 		if ( fd->exec() == QDialog::Accepted )
  2817 		{
  2818 			if (QFile (fd->selectedFile()).exists() )
  2819 			{
  2820 				QMessageBox mb( __VYM,
  2821 					tr("The file %1 exists already.\n"
  2822 					"Do you want to overwrite it?").arg(fd->selectedFile()),
  2823 				QMessageBox::Warning,
  2824 				QMessageBox::Yes | QMessageBox::Default,
  2825 				QMessageBox::Cancel | QMessageBox::Escape,
  2826 				QMessageBox::QMessageBox::NoButton );
  2827 
  2828 				mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
  2829 				mb.setButtonText( QMessageBox::No, tr("Cancel"));
  2830 				switch( mb.exec() ) 
  2831 				{
  2832 					case QMessageBox::Yes:
  2833 						// save 
  2834 						break;;
  2835 					case QMessageBox::Cancel:
  2836 						// do nothing
  2837 						return;
  2838 						break;
  2839 				}
  2840 			}
  2841 			fio->save (fd->selectedFile(),fmt);
  2842 		}
  2843 	}
  2844 }
  2845 
  2846 void MapEditor::toggleFloatExport()
  2847 {
  2848 	if (selection && 
  2849 		(typeid(*selection) == typeid(FloatImageObj))|| 
  2850 		(typeid(*selection) == typeid(FloatObj)) )
  2851 	{
  2852 		FloatImageObj *fio=((FloatImageObj*)selection);
  2853 		fio->setFloatExport (actionEditToggleFloatExport->isOn() );
  2854 	}
  2855 }
  2856 
  2857 void MapEditor::setFrame(const FrameType &t)
  2858 {
  2859 	if (selection && 
  2860 		(typeid(*selection) == typeid(BranchObj)) || 
  2861 		(typeid(*selection) == typeid(MapCenterObj))  )
  2862 	{
  2863 		selection->setFrameType (t);
  2864 		mapCenter->reposition();
  2865 		selection->updateLink();
  2866 	}
  2867 }
  2868 
  2869 void MapEditor::setIncludeImagesVer(bool b)
  2870 {
  2871 	if (selection && 
  2872 		(typeid(*selection) == typeid(BranchObj)) || 
  2873 		(typeid(*selection) == typeid(MapCenterObj))  )
  2874 		((BranchObj*)selection)->setIncludeImagesVer(b);
  2875 		mapCenter->reposition();
  2876 }
  2877 
  2878 void MapEditor::setIncludeImagesHor(bool b)
  2879 {
  2880 	if (selection && 
  2881 		(typeid(*selection) == typeid(BranchObj)) || 
  2882 		(typeid(*selection) == typeid(MapCenterObj))  )
  2883 		((BranchObj*)selection)->setIncludeImagesHor(b);
  2884 		mapCenter->reposition();
  2885 }
  2886 
  2887 void MapEditor::setHideLinkUnselected (bool b)
  2888 {
  2889 	if (selection && 
  2890 		(typeid(*selection) == typeid(BranchObj)) || 
  2891 		(typeid(*selection) == typeid(MapCenterObj))  ||
  2892 		(typeid(*selection) == typeid(FloatImageObj)) )
  2893 		selection->setHideLinkUnselected(b);
  2894 }
  2895 
  2896 void MapEditor::importDir(BranchObj *dst, QDir d)
  2897 {
  2898 	if (selection && 
  2899 		(typeid(*selection) == typeid(BranchObj)) || 
  2900 		(typeid(*selection) == typeid(MapCenterObj))  )
  2901 	{
  2902 		BranchObj *bo;
  2903 		
  2904 		// Traverse directories
  2905 		d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
  2906 		const QFileInfoList *dirlist = d.entryInfoList();
  2907 		QFileInfoListIterator itdir( *dirlist );
  2908 		QFileInfo *fi;
  2909 
  2910 		while ( (fi = itdir.current()) != 0 ) 
  2911 		{
  2912 			if (fi->fileName() != "." && fi->fileName() != ".." )
  2913 			{
  2914 				dst->addBranch();
  2915 				bo=dst->getLastBranch();
  2916 				bo->setHeading (fi->fileName() );
  2917 				bo->setColor (QColor("blue"),false);
  2918 				bo->toggleScroll();
  2919 				if ( !d.cd(fi->fileName()) ) 
  2920 					QMessageBox::critical (0,tr("Critical Import Error"),tr("Cannot find the directory %1").arg(fi->fileName()));
  2921 				else 
  2922 				{
  2923 					// Recursively add subdirs
  2924 					importDir (bo,d);
  2925 					d.cdUp();
  2926 				}
  2927 			}	
  2928 			++itdir;
  2929 		}		
  2930 		// Traverse files
  2931 		d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
  2932 		const QFileInfoList *filelist = d.entryInfoList();
  2933 		QFileInfoListIterator itfile( *filelist );
  2934 
  2935 		while ( (fi = itfile.current()) != 0 ) 
  2936 		{
  2937 			dst->addBranch();
  2938 			bo=dst->getLastBranch();
  2939 			bo->setHeading (fi->fileName() );
  2940 			bo->setColor (QColor("black"),false);
  2941 			if (fi->fileName().right(4) == ".vym" )
  2942 				bo->setVymLink (fi->filePath());
  2943 
  2944 			++itfile;
  2945 		}	
  2946 	}		
  2947 }
  2948 
  2949 void MapEditor::importDir()
  2950 {
  2951 	if (selection && 
  2952 		(typeid(*selection) == typeid(BranchObj)) || 
  2953 		(typeid(*selection) == typeid(MapCenterObj))  )
  2954 	{
  2955 		QFileDialog *fd=new QFileDialog( this,__VYM " - " +tr("Choose directory structure to import"));
  2956 		fd->setMode (QFileDialog::DirectoryOnly);
  2957 		fd->addFilter (QString (tr("vym map") + " (*.vym)"));
  2958 		fd->setCaption(__VYM " - " +tr("Choose directory structure to import"));
  2959 		fd->show();
  2960 
  2961 		QString fn;
  2962 		if ( fd->exec() == QDialog::Accepted )
  2963 		{
  2964 			BranchObj *bo=((BranchObj*)selection);
  2965 			importDir (bo,QDir(fd->selectedFile()) );
  2966 			mapCenter->reposition();
  2967 			adjustCanvasSize();
  2968 			canvas()->update();
  2969 		}
  2970 	}	
  2971 }
  2972 
  2973 void MapEditor::followXLink(int i)
  2974 {
  2975 	if (selection && 
  2976 		(typeid(*selection) == typeid(BranchObj)) || 
  2977 		(typeid(*selection) == typeid(MapCenterObj))  )
  2978 	{
  2979 		BranchObj *bo=((BranchObj*)selection)->XLinkTargetAt(i);
  2980 		if (bo) 
  2981 		{
  2982 			selection->unselect();
  2983 			selection=bo;
  2984 			selection->select();
  2985 			ensureSelectionVisible();
  2986 		}
  2987 	}
  2988 }
  2989 
  2990 void MapEditor::editXLink(int i)
  2991 {
  2992 	if (selection && 
  2993 		(typeid(*selection) == typeid(BranchObj)) || 
  2994 		(typeid(*selection) == typeid(MapCenterObj))  )
  2995 	{
  2996 		XLinkObj *xlo=((BranchObj*)selection)->XLinkAt(i);
  2997 		if (xlo) 
  2998 		{
  2999 			EditXLinkDialog dia;
  3000 			dia.setXLink (xlo);
  3001 			dia.setSelection(selection);
  3002 			if (dia.exec() == QDialog::Accepted)
  3003 			{
  3004 				if (dia.useSettingsGlobal() )
  3005 				{
  3006 					setDefXLinkColor (xlo->getColor() );
  3007 					setDefXLinkWidth (xlo->getWidth() );
  3008 				}
  3009 				if (dia.deleteXLink())
  3010 					((BranchObj*)selection)->deleteXLinkAt(i);
  3011 				saveState();	//TODO undoCommand
  3012 			}
  3013 		}	
  3014 	}
  3015 }
  3016 
  3017 void MapEditor::testFunction()
  3018 {
  3019 	cout << "MapEditor::testFunction() called\n";
  3020 	if (selection && (typeid(*selection) == typeid(BranchObj)))
  3021 	{
  3022 		cout << "Note:\n"<<((BranchObj*)selection)->getNoteOpenDoc()<<endl;
  3023 	}
  3024 }
  3025 
  3026 void MapEditor::ensureSelectionVisible()
  3027 {
  3028 	if (selection)
  3029 	{
  3030 		LinkableMapObj* lmo= dynamic_cast <LinkableMapObj*> (selection);
  3031 		QPoint p;
  3032 		if (selection->getOrientation() == OrientLeftOfCenter)
  3033 			p= worldMatrix().map(QPoint (lmo->x(),lmo->y()));
  3034 		else	
  3035 			p= worldMatrix().map(QPoint (lmo->x()+lmo->width(),lmo->y()+lmo->height()));
  3036 		ensureVisible (p.x(), p.y() );
  3037 	}
  3038 
  3039 }
  3040 
  3041 void MapEditor::updateViewCenter()
  3042 {
  3043 	// Update movingCenter, so that we can zoom comfortably later
  3044 	QRect rc = QRect( contentsX(), contentsY(),
  3045 				  visibleWidth(), visibleHeight() );
  3046 	QRect canvasRect = inverseWorldMatrix().mapRect(rc);
  3047 	movingCenter.setX((canvasRect.right() + canvasRect.left())/2);
  3048 	movingCenter.setY((canvasRect.top() + canvasRect.bottom())/2);
  3049 }
  3050 
  3051 void MapEditor::contentsContextMenuEvent ( QContextMenuEvent * e )
  3052 {
  3053 	// Lineedits are already closed by preceding
  3054 	// mouseEvent, we don't need to close here.
  3055 
  3056     QPoint p = inverseWorldMatrix().map(e->pos());
  3057     LinkableMapObj* lmo=mapCenter->findMapObj(p, NULL);
  3058 	
  3059     if (lmo) 
  3060 	{	// MapObj was found
  3061 		if (selection != lmo)
  3062 		{
  3063 			// select the MapObj
  3064 			if (selection) selection->unselect();
  3065 			selection=lmo;
  3066 			selection->select();
  3067 			adjustCanvasSize();
  3068 		}
  3069 		// Context Menu 
  3070 		if (selection) 
  3071 		{
  3072 			if (typeid(*selection)==typeid(BranchObj) ||
  3073 				typeid(*selection)==typeid(MapCenterObj) )
  3074 			{
  3075 				// Context Menu on branch or mapcenter
  3076 				updateActions();
  3077 				branchContextMenu->popup(e->globalPos() );
  3078 			}	
  3079 			if (typeid(*selection)==typeid(FloatImageObj))
  3080 			{
  3081 				// Context Menu on floatimage
  3082 				updateActions();
  3083 				floatimageContextMenu->popup(e->globalPos() );
  3084 			}	
  3085 		}	
  3086 	} else 
  3087 	{ // No MapObj found, we are on the Canvas itself
  3088 		// Context Menu on Canvas
  3089 		updateActions();
  3090 		canvasContextMenu->popup(e->globalPos() );
  3091     } 
  3092 }
  3093 
  3094 void MapEditor::contentsMousePressEvent(QMouseEvent* e)
  3095 {
  3096 	// Finish open lineEdits
  3097 	if (lineedit) finishedLineEditNoSave();
  3098 	
  3099     QPoint p = inverseWorldMatrix().map(e->pos());
  3100     LinkableMapObj* lmo=mapCenter->findMapObj(p, NULL);
  3101 	
  3102 	// Special case: CTRL is pressed
  3103 	if (e->state() & QMouseEvent::ControlButton)
  3104 	{
  3105 		if (actionModModeColor->isOn())
  3106 		{
  3107 			if (e->state() & QMouseEvent::ControlButton)
  3108 			{
  3109 				pickingColor=true;
  3110 				setCursor (pickColorCursor);
  3111 				return;
  3112 			}
  3113 		} 
  3114 		if (actionModModeLink->isOn())
  3115 		{	
  3116 			BranchObj *bo_begin=NULL;
  3117 			if (lmo)
  3118 				bo_begin=(BranchObj*)(lmo);
  3119 			else	
  3120 				if (selection && 
  3121 					((typeid(*selection) == typeid(BranchObj)) || 
  3122 					(typeid(*selection) == typeid(MapCenterObj)))  )
  3123 				bo_begin=(BranchObj*)selection;
  3124 			if (bo_begin)	
  3125 			{
  3126 				drawingLink=true;
  3127 				linkingObj_src=bo_begin;
  3128 				tmpXLink=new XLinkObj (mapCanvas);
  3129 				tmpXLink->setBegin (bo_begin);
  3130 				tmpXLink->setEnd   (p);
  3131 				tmpXLink->setColor(defXLinkColor);
  3132 				tmpXLink->setWidth(defXLinkWidth);
  3133 				tmpXLink->updateXLink();
  3134 				tmpXLink->setVisibility (true);
  3135 				return;
  3136 			} 
  3137 		}	
  3138 	}
  3139 
  3140     if (lmo) 
  3141 	{	// MapObj was found
  3142 		if (selection != lmo)
  3143 		{
  3144 			// select the MapObj
  3145 			if (selection) selection->unselect();
  3146 			selection=lmo;
  3147 			selection->select();
  3148 				
  3149 			adjustCanvasSize();
  3150 		}
  3151 
  3152 		// Check, if systemFlag clicked
  3153 		if (typeid(*selection)==typeid(BranchObj) ||
  3154 			typeid(*selection)==typeid(MapCenterObj) )
  3155 		{
  3156 			QString foname=((BranchObj*)selection)->getSystemFlagName(p);
  3157 			if (!foname.isEmpty())
  3158 			{
  3159 				// Do not move, if systemFlag clicked
  3160 				if (foname=="url") 
  3161 					openURL();
  3162 				else
  3163 					if (foname=="vymLink")
  3164 					{
  3165 						mainWindow->editOpenVymLink();
  3166 						// tabWidget may change, better return now
  3167 						// before segfaulting...
  3168 						return;
  3169 					} else
  3170 						if (foname=="note")
  3171 							mainWindow->windowToggleNoteEditor();
  3172 			}			
  3173 		}	
  3174 			
  3175 		// Left Button	    Move Branches
  3176 		if (e->button() == QMouseEvent::LeftButton )
  3177 		{
  3178 			movingObj_start.setX( p.x() - selection->x() );	
  3179 			movingObj_start.setY( p.y() - selection->y() );	
  3180 			movingObj_orgPos.setX (lmo->x() );
  3181 			movingObj_orgPos.setY (lmo->y() );
  3182 
  3183 			// If modMode==copy, then we want to "move" the _new_ object around
  3184 			// then we need the offset from p to the _old_ selection, because of tmp
  3185 			if (actionModModeCopy->isOn() &&
  3186 				e->state() & QMouseEvent::ControlButton)
  3187 			{
  3188 				if (typeid(*selection)==typeid(BranchObj) )
  3189 				{
  3190 					copyingObj=true;
  3191 					mapCenter->addBranch ((BranchObj*)selection);
  3192 					unselect();
  3193 					selection=mapCenter->getLastBranch();
  3194 					selection->select();
  3195 					mapCenter->reposition();
  3196 				}
  3197 			}	
  3198 			movingObj=selection;	
  3199 		} else
  3200 			// Middle Button    Toggle Scroll
  3201 			// (On Mac OS X this won't work, but we still have 
  3202 			// a button in the toolbar)
  3203 			if (e->button() == QMouseEvent::MidButton )
  3204 				toggleScroll();
  3205 		updateActions();
  3206 	} else 
  3207 	{ // No MapObj found, we are on the Canvas itself
  3208 		// Left Button	    move Pos of CanvasView
  3209 		if (e->button() == QMouseEvent::LeftButton )
  3210 		{
  3211 			movingObj=NULL;	// move Content not Obj
  3212 			movingObj_start=e->globalPos();
  3213 			movingCont_start=QPoint (contentsX(), contentsY() );
  3214 			movingVec=QPoint(0,0);
  3215 			setCursor(handOpenCursor);
  3216 		} 
  3217     } 
  3218 }
  3219 
  3220 void MapEditor::contentsMouseMoveEvent(QMouseEvent* e)
  3221 {
  3222 	QPoint p = inverseWorldMatrix().map(e->pos());
  3223 
  3224     // Move the selected MapObj
  3225     if ( selection && movingObj) 
  3226     {	
  3227 		// To avoid jumping of the CanvasView, only 
  3228 		// ensureSelectionVisible, if not tmp linked
  3229 		if (!selection->hasParObjTmp())
  3230 			ensureSelectionVisible ();
  3231 		
  3232 		// Now move the selection, but add relative position 
  3233 		// (movingObj_start) where selection was chosen with 
  3234 		// mousepointer. (This avoids flickering resp. jumping 
  3235 		// of selection back to absPos)
  3236 		
  3237 		LinkableMapObj *lmosel;
  3238 		lmosel =  dynamic_cast <LinkableMapObj*> (selection);
  3239 
  3240 		// Check if we could link 
  3241 		LinkableMapObj* lmo=mapCenter->findMapObj(p, lmosel);
  3242 		
  3243 
  3244 		if (typeid(*selection) == typeid(FloatImageObj))
  3245 		{
  3246 			FloatObj *fo=(FloatObj*)selection;
  3247 			saveState("move "+qpointToString(movingObj_orgPos),fo->getSelectString() );
  3248 			fo->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3249 			fo->setRelPos();
  3250 			fo->reposition();
  3251 
  3252 			// Relink float to new mapcenter or branch, if shift is pressed	
  3253 			// Only relink, if selection really has a new parent
  3254 			if ( (e->state() & QMouseEvent::ShiftButton) && lmo &&
  3255 				( (typeid(*lmo)==typeid(BranchObj)) ||
  3256 				  (typeid(*lmo)==typeid(MapCenterObj)) ) &&
  3257 				( lmo != fo->getParObj())  
  3258 				)
  3259 			{
  3260 				if (typeid(*fo) == typeid(FloatImageObj)) 
  3261 				{
  3262 					saveState();
  3263 					FloatImageObj *fio=(FloatImageObj*)(fo);
  3264 					((BranchObj*)(lmo))->addFloatImage (fio);
  3265 					fio->unselect();
  3266 					((BranchObj*)(fio->getParObj()))->removeFloatImage (fio);
  3267 					fio=((BranchObj*)(lmo))->getLastFloatImage();
  3268 					fio->setRelPos();
  3269 					fio->reposition();
  3270 					selection=(LinkableMapObj*)(fio);
  3271 					selection->select();
  3272 					movingObj=(MapObj*)(fio);
  3273 				}	
  3274 			}
  3275 		} else	// selection != a FloatObj
  3276 		{
  3277 			if (lmosel->getDepth()==0)
  3278 			{
  3279 				if (e->state() == (LeftButton | !ShiftButton)) 
  3280 					// If mapCenter is moved, move all the rest by default, too.
  3281 					mapCenter->moveAll(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3282 				else	
  3283 					mapCenter->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3284 			} else
  3285 			{	
  3286 				if (lmosel->getDepth()==1)
  3287 				{
  3288 					// depth==1, mainbranch
  3289 					lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3290 				} else
  3291 				{
  3292 					// depth>1
  3293 					if (lmosel->getOrientation() == OrientLeftOfCenter)
  3294 						// Add width of bbox here, otherwise alignRelTo will cause jumping around
  3295 						lmosel->move(p.x() -movingObj_start.x()+lmosel->getBBox().width(), 
  3296 							p.y()-movingObj_start.y() +lmosel->getTopPad() );		
  3297 					else	
  3298 						lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() -lmosel->getTopPad());
  3299 				} 
  3300 				// reposition subbranch
  3301 				lmosel->reposition();	
  3302 				//ensureSelectionVisible();
  3303 
  3304 				if (lmo && (lmo!=selection) &&  
  3305 					(typeid(*lmo) == typeid(BranchObj) ||
  3306 					(typeid(*lmo) == typeid(MapCenterObj) )
  3307 					) )
  3308 				{
  3309 					if (e->state() & QMouseEvent::ControlButton)
  3310 					{
  3311 						// Special case: CTRL to link below lmo
  3312 						lmosel->setParObjTmp (lmo,p,+1);
  3313 					}
  3314 					else if (e->state() & QMouseEvent::ShiftButton)
  3315 						lmosel->setParObjTmp (lmo,p,-1);
  3316 					else
  3317 						lmosel->setParObjTmp (lmo,p,0);
  3318 				} else	
  3319 				{
  3320 					lmosel->unsetParObjTmp();
  3321 					/* FIXME not needed anymore?
  3322 					if (lmo &&(lmo==selection))   
  3323 						// Could link to myself (happens sometimes...)
  3324 						lmosel->unsetParObjTmp();
  3325 					if (!lmo)  
  3326 						// no Obj under selection, go back to original Parent
  3327 						lmosel->unsetParObjTmp();
  3328 					*/	
  3329 				}		
  3330 			} // depth>0
  3331 
  3332 		} // no FloatImageObj
  3333 
  3334 		canvas()->update();
  3335 		return;
  3336 	} // selection && moving_obj
  3337 		
  3338 	// Draw a link from one branch to another
  3339 	if (drawingLink)
  3340 	{
  3341 		 tmpXLink->setEnd (p);
  3342 		 tmpXLink->updateXLink();
  3343 	}	 
  3344 	
  3345     // Move CanvasView 
  3346     if (!movingObj && !pickingColor &&!drawingLink) 
  3347 	{
  3348 		QPoint p=e->globalPos();
  3349 		movingVec.setX(-p.x() + movingObj_start.x() );
  3350 		movingVec.setY(-p.y() + movingObj_start.y() );
  3351 		setContentsPos( movingCont_start.x() + movingVec.x(),
  3352 	    movingCont_start.y() + movingVec.y());
  3353 
  3354 		updateViewCenter();
  3355     }
  3356 }
  3357 
  3358 
  3359 void MapEditor::contentsMouseReleaseEvent(QMouseEvent* e)
  3360 {
  3361 	LinkableMapObj *dst;
  3362 	// Have we been picking color?
  3363 	if (pickingColor)
  3364 	{
  3365 		pickingColor=false;
  3366 		setCursor (ArrowCursor);
  3367 		// Check if we are over another branch
  3368 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), NULL);
  3369 		if (dst && selection) 
  3370 		{	
  3371 			if (e->state() & QMouseEvent::ShiftButton)
  3372 			{
  3373 				((BranchObj*)selection)->setColor (((BranchObj*)(dst))->getColor(),false);
  3374 				((BranchObj*)selection)->setLinkColor ();
  3375 			}	
  3376 			else	
  3377 			{
  3378 				((BranchObj*)selection)->setColor (((BranchObj*)(dst))->getColor(),true);
  3379 				((BranchObj*)selection)->setLinkColor ();
  3380 			}	
  3381 		} 
  3382 		return;
  3383 	}
  3384 
  3385 	// Have we been drawing a link?
  3386 	if (drawingLink)
  3387 	{
  3388 		drawingLink=false;
  3389 		// Check if we are over another branch
  3390 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), NULL);
  3391 		if (dst && selection) 
  3392 		{	
  3393 			tmpXLink->setEnd ( ((BranchObj*)(dst)) );
  3394 			tmpXLink->updateXLink();
  3395 			tmpXLink->activate();
  3396 			saveState();	//TODO undoCommand
  3397 		} else
  3398 		{
  3399 			delete(tmpXLink);
  3400 			tmpXLink=NULL;
  3401 		}
  3402 		return;
  3403 	}
  3404 	
  3405     // Have we been moving something?
  3406     if ( selection && movingObj ) 
  3407     {	
  3408 		// Moved FloatObj? Maybe we need to reposition
  3409 		if(typeid(*selection)==typeid (FloatImageObj))
  3410 		{
  3411 			selection->getParObj()->requestReposition();
  3412 			mapCenter->reposition();
  3413 		}	
  3414 
  3415 		// Check if we are over another branch, but ignore 
  3416 		// any found LMOs, which are FloatObjs
  3417 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), 
  3418 			((LinkableMapObj*)selection) );
  3419 
  3420 		if (dst &&
  3421 		(typeid(*dst)!=typeid(BranchObj)&&typeid(*dst)!=typeid(MapCenterObj))) 
  3422 			dst=NULL;
  3423 		
  3424 		// Now check, if we have been moving a branch 
  3425 		if (typeid(*selection) == typeid(BranchObj)  )
  3426 		{
  3427 			// save the position in case we link to mapcenter
  3428 			QPoint savePos=QPoint (selection->x(),selection->y() );
  3429 
  3430 			// Reset the temporary drawn link to the original one
  3431 			((LinkableMapObj*)selection)->unsetParObjTmp();
  3432 
  3433 
  3434 			copyingObj=false;	
  3435 			if (dst ) 
  3436 			{
  3437 				BranchObj* bs=((BranchObj*)selection);
  3438 				QString undoCom="linkBranchToPos (\""+ 
  3439 					(bs->getParObj())->getSelectString()+
  3440 					"\","+
  3441 					QString("%1").arg(bs->getNum())+
  3442 					","+
  3443 					QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+
  3444 					")";
  3445 				// TODO we also could check, if dest and src are on same branch,
  3446 				// then it would be sufficient to saveState of this branch
  3447 
  3448 				// Modifiers allow to insert above/below dst
  3449 				if (e->state() & QMouseEvent::ShiftButton)
  3450 				{
  3451 					bs->moveBranchTo ( (BranchObj*)(dst->getParObj()), ((BranchObj*)(dst))->getNum());
  3452 				} else 
  3453 				if (e->state() & QMouseEvent::ControlButton)
  3454 			{
  3455 					bs->moveBranchTo ( (BranchObj*)(dst->getParObj()), ((BranchObj*)(dst))->getNum()+1);
  3456 				} else	
  3457 				{
  3458 					bs->moveBranchTo ((BranchObj*)(dst),-1);
  3459 					if (dst->getDepth()==0) 
  3460 						bs->move (savePos);
  3461 				} 
  3462 				saveState (undoCom,bs->getSelectString() );
  3463 			} else
  3464 				if (selection->getDepth()==1)
  3465 					// If we have moved mainbranch only save endposition
  3466 					saveState("move "+qpointToString(movingObj_orgPos), selection->getSelectString() );
  3467 			
  3468 			// Draw the original link, before selection was moved around
  3469 			mapCenter->reposition();
  3470 		}
  3471 		// Finally resize canvas, if needed
  3472 		adjustCanvasSize();
  3473 		canvas()->update();
  3474 		movingObj=NULL;		
  3475 	} else 
  3476 		// maybe we moved View: set old cursor
  3477 		setCursor (ArrowCursor);
  3478     
  3479 }
  3480 
  3481 void MapEditor::contentsMouseDoubleClickEvent(QMouseEvent* e)
  3482 {
  3483 	// Finish open lineEdits
  3484 	if (lineedit) finishedLineEditNoSave();
  3485 	
  3486 	if (e->button() == QMouseEvent::LeftButton )
  3487 	{
  3488 		QPoint p = inverseWorldMatrix().map(e->pos());
  3489 		LinkableMapObj *lmo=mapCenter->findMapObj(p, NULL);
  3490 		if (lmo) {	// MapObj was found
  3491 			// First select the MapObj than edit heading
  3492 			if (selection) selection->unselect();
  3493 			selection=lmo;
  3494 			selection->select();
  3495 			saveState(selection);
  3496 			editHeading();
  3497 		}
  3498 	}
  3499 }
  3500 
  3501 void MapEditor::resizeEvent (QResizeEvent* e)
  3502 {
  3503 	QCanvasView::resizeEvent( e );
  3504 	adjustCanvasSize();
  3505 }
  3506 
  3507 void MapEditor::contentsDragEnterEvent(QDragEnterEvent *event) 
  3508 {
  3509 
  3510 //  for (unsigned int i=0;event->format(i);i++) // Debug mime type
  3511 //    cerr << event->format(i) << endl;
  3512 
  3513   if (selection && 
  3514       (typeid(*selection) == typeid(BranchObj)) || 
  3515       (typeid(*selection) == typeid(MapCenterObj))) {
  3516     
  3517     // If QImageDrag can decode mime type 
  3518     if (QImageDrag::canDecode(event)) {
  3519       event->accept();
  3520       return;
  3521     }
  3522     
  3523     // If image are dragged from firefox 
  3524     if (event->provides("application/x-moz-file-promise-url") && 
  3525 	event->provides("application/x-moz-nativeimage")) {
  3526       event->accept(true);
  3527       return;
  3528     }
  3529 
  3530     // If QUriDrag can decode mime type 
  3531     if (QUriDrag::canDecode(event)) {
  3532       event->accept();
  3533       return;
  3534     }
  3535     
  3536 	// If Uri are dragged from firefox 
  3537     if (event->provides("_NETSCAPE_URL")){
  3538       event->accept();
  3539       return;
  3540     }
  3541 
  3542     // If QTextDrag can decode mime type
  3543     if (QTextDrag::canDecode(event)) {
  3544       event->accept();
  3545       return;
  3546     }
  3547 
  3548   }
  3549   event->ignore();
  3550 }
  3551 
  3552 bool isUnicode16(const QByteArray &d) 
  3553 {
  3554   // TODO: make more precise check for unicode 16.
  3555   // Guess unicode16 if any of second bytes are zero
  3556   unsigned int length = max(0,d.size()-2)/2;
  3557   for (unsigned int i = 0; i<length ; i++)
  3558     if (d.at(i*2+1)==0) return true;
  3559   return false;
  3560 }
  3561       
  3562 void MapEditor::contentsDropEvent(QDropEvent *event) 
  3563 {
  3564 	if (selection && 
  3565       (typeid(*selection) == typeid(BranchObj)) || 
  3566       (typeid(*selection) == typeid(MapCenterObj))) 
  3567 	{
  3568 		bool update=false;
  3569 		QStrList uris;
  3570 		QString heading;
  3571 		if (event->provides("image/png")) 
  3572 		{
  3573 			QPixmap pix;
  3574 			if (QImageDrag::decode(event, pix)) 
  3575 			{
  3576 				addFloatImage(pix);
  3577 				event->accept();
  3578 				update=true;
  3579 			} else
  3580 				event->ignore();
  3581 
  3582 		} else if (event->provides("application/x-moz-file-promise-url") && 
  3583 			 event->provides("application/x-moz-nativeimage")) 
  3584 		{
  3585 			// Contains url to the img src in unicode16
  3586 			QByteArray d = event->encodedData("application/x-moz-file-promise-url");
  3587 			QString url = QString((const QChar*)d.data(),d.size()/2);
  3588 			fetchImage(url);
  3589 			event->accept();
  3590 			update=true;
  3591 		} else if (event->provides ("text/uri-list"))
  3592 		{	// Uris provided e.g. by konqueror
  3593 			QUriDrag::decode (event,uris);
  3594 		} else if (event->provides ("_NETSCAPE_URL"))
  3595 		{	// Uris provided by Mozilla
  3596 		  QStringList l = QStringList::split("\n", event->encodedData("_NETSCAPE_URL"));
  3597 		  uris.append(l[0]);
  3598 		  heading = l[1];
  3599 		} else if (event->provides("text/html")) {
  3600 
  3601 		  // Handels text mime types
  3602 		  // Look like firefox allways handle text as unicode16 (2 bytes per char.)
  3603 		  QByteArray d = event->encodedData("text/html");
  3604 		  QString text;
  3605 		  if (isUnicode16(d)) 
  3606 		    text = QString((const QChar*)d.data(),d.size()/2);
  3607 		  else 
  3608 		    text = QString(d);
  3609 
  3610 		  textEditor->setText(text);
  3611 
  3612 		  event->accept();
  3613 		  update=true;
  3614 		} else if (event->provides("text/plain")) {
  3615 		  QByteArray d = event->encodedData("text/plain");
  3616 		  QString text;
  3617 		  if (isUnicode16(d))
  3618 		    text = QString((const QChar*)d.data(),d.size()/2);
  3619 		  else 
  3620 		    text = QString(d);
  3621 
  3622 		  textEditor->setText(text);
  3623 		  
  3624 		  event->accept();
  3625 		  update= true;
  3626 		}
  3627 
  3628 		if (uris.count()>0)
  3629 		{
  3630 			QStringList files;
  3631 			QStringList urls;
  3632 			QString s;
  3633 			BranchObj *bo;
  3634 			for (const char* u=uris.first(); u; u=uris.next())
  3635 			{
  3636 				bo=((BranchObj*)selection)->addBranch();
  3637 				if (bo)
  3638 				{
  3639 					s=QUriDrag::uriToLocalFile(u);
  3640 					if (s) {
  3641                        QString file = QDir::convertSeparators(s);
  3642                        heading = QFileInfo(file).baseName();
  3643                        files.append(file);
  3644                        if (file.endsWith(".vym", false))
  3645                            bo->setVymLink(file);
  3646                        else
  3647                            bo->setURL(u);
  3648                    } else {
  3649                        urls.append (u);
  3650                        bo->setURL(u);
  3651                    }
  3652 
  3653                    if (heading)
  3654                        bo->setHeading(heading);
  3655                    else
  3656                        bo->setHeading(u);
  3657 				}
  3658 			}
  3659 			update=true;
  3660 		}
  3661 
  3662 		if (update) 
  3663 		{
  3664 			saveState();	//TODO undo Command
  3665 			mapCenter->reposition();
  3666 			adjustCanvasSize();
  3667 			canvas()->update();
  3668 		}	
  3669 	}	
  3670 }
  3671 
  3672 void MapEditor::addFloatImage(const QPixmap &img) 
  3673 {
  3674   if (selection && 
  3675       (typeid(*selection) == typeid(BranchObj)) || 
  3676       (typeid(*selection) == typeid(MapCenterObj))  )
  3677   {
  3678     BranchObj *bo=((BranchObj*)selection);
  3679     saveState(selection);
  3680     //QString fn=fd->selectedFile();
  3681     //lastImageDir=fn.left(fn.findRev ("/"));
  3682     bo->addFloatImage();
  3683     // FIXME check if load was successful
  3684     bo->getLastFloatImage()->load(img);
  3685     //bo->getLastFloatImage()->setOriginalFilename(fn);
  3686     mapCenter->reposition();
  3687     adjustCanvasSize();
  3688     canvas()->update();
  3689   }
  3690 }
  3691 
  3692 
  3693 void MapEditor::imageDataFetched(const QByteArray &a, QNetworkOperation */*nop*/) 
  3694 {
  3695   if (!imageBuffer) imageBuffer = new QBuffer();
  3696   if (!imageBuffer->isOpen()) {
  3697     imageBuffer->open(IO_WriteOnly | IO_Append);
  3698   }
  3699   imageBuffer->at(imageBuffer->at()+imageBuffer->writeBlock(a));
  3700 }
  3701 
  3702 
  3703 void MapEditor::imageDataFinished(QNetworkOperation *nop) 
  3704 {
  3705 	if (nop->state()==QNetworkProtocol::StDone) {
  3706 		QPixmap img(imageBuffer->buffer());
  3707 		addFloatImage(img);
  3708 	}
  3709 
  3710 	if (imageBuffer) {
  3711 		imageBuffer->close();
  3712 		if (imageBuffer) {
  3713 			imageBuffer->close();
  3714 			delete imageBuffer;
  3715 			imageBuffer = 0;
  3716 		}
  3717 	}
  3718 }
  3719 
  3720 void MapEditor::fetchImage(const QString &url) 
  3721 {
  3722   if (urlOperator) {
  3723     urlOperator->stop();
  3724     disconnect(urlOperator);
  3725     delete urlOperator;
  3726   }
  3727   
  3728   urlOperator = new QUrlOperator(url);
  3729   connect(urlOperator, SIGNAL(finished(QNetworkOperation *)), 
  3730 	  this, SLOT(imageDataFinished(QNetworkOperation*)));
  3731 
  3732   connect(urlOperator, SIGNAL(data(const QByteArray &, QNetworkOperation *)),
  3733 	  this, SLOT(imageDataFetched(const QByteArray &, QNetworkOperation *)));
  3734   urlOperator->get();
  3735 }