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