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