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