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