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