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