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