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