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