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