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