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