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