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