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