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