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