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