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