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