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