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