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