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