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