mapeditor.cpp
author insilmaril
Thu, 21 Jan 2010 11:56:57 +0000
changeset 821 4a84d7e444d8
parent 820 735c7ea1d2a9
child 823 0bba81dde1bc
permissions -rw-r--r--
Various fixes, including combined progress bar for loading maps
     1 #include "mapeditor.h"
     2 
     3 #include <iostream>
     4 #include <cstdlib>
     5 #include <typeinfo>
     6 
     7 #include <QObject>
     8 
     9 #include "branchitem.h"
    10 #include "geometry.h"
    11 #include "mainwindow.h"
    12 #include "misc.h"
    13 #include "warningdialog.h"
    14 #include "xlinkitem.h"
    15 
    16 
    17 extern int statusbarTime;
    18 extern Main *mainWindow;
    19 extern QString tmpVymDir;
    20 extern QString clipboardDir;
    21 extern QString clipboardFile;
    22 extern bool clipboardEmpty;
    23 extern bool debug;
    24 
    25 extern QMenu* branchContextMenu;
    26 extern QMenu* floatimageContextMenu;
    27 extern QMenu* canvasContextMenu;
    28 
    29 extern Settings settings;
    30 extern QString iconPath;
    31 
    32 ///////////////////////////////////////////////////////////////////////
    33 ///////////////////////////////////////////////////////////////////////
    34 MapEditor::MapEditor( VymModel *vm) 
    35 {
    36 	//cout << "Constructor ME "<<this<<endl;
    37 	mapScene= new QGraphicsScene(NULL);
    38 	mapScene->setBackgroundBrush (QBrush(Qt::white, Qt::SolidPattern));
    39 
    40 	zoomFactor=zoomFactorTarget=1;
    41 
    42 	model=vm;
    43 	model->setScene (mapScene);
    44 	model->registerEditor(this);
    45 	model->makeDefault();	// No changes in model so far
    46 
    47     setScene (mapScene);
    48 
    49     printer=NULL;
    50 
    51 	// Create bitmap cursors, platform dependant
    52 	HandOpenCursor=QCursor (QPixmap(iconPath+"cursorhandopen.png"),1,1);		
    53 	PickColorCursor=QCursor ( QPixmap(iconPath+"cursorcolorpicker.png"), 5,27 ); 
    54 	CopyCursor=QCursor ( QPixmap(iconPath+"cursorcopy.png"), 1,1 ); 
    55 	XLinkCursor=QCursor ( QPixmap(iconPath+"cursorxlink.png"), 1,7 ); 
    56 
    57 	//setFocusPolicy (Qt::StrongFocus);	//FIXME-3
    58 
    59 	pickingColor=false;
    60 	drawingLink=false;
    61 	copyingObj=false;
    62 	objectMoved=false;
    63 
    64     editingBO=NULL;
    65     movingObj=NULL;
    66 
    67 	printFrame=true;
    68 	printFooter=true;
    69 
    70 	setAcceptDrops (true);	
    71 
    72 	//model->reposition();	//FIXME-3 really still needed?
    73 
    74 
    75 	// Shortcuts and actions
    76 	QAction *a;
    77     a = new QAction("Select upper branch", this);
    78 	a->setShortcut (Qt::Key_Up );
    79 	a->setShortcutContext (Qt::WidgetShortcut);
    80 	addAction (a);
    81     connect( a, SIGNAL( triggered() ), this, SLOT( cursorUp() ) );
    82 
    83     a = new QAction( "Select lower branch",this);
    84 	a->setShortcut ( Qt::Key_Down );
    85 	a->setShortcutContext (Qt::WidgetShortcut);
    86 	addAction (a);
    87     connect( a, SIGNAL( triggered() ), this, SLOT( cursorDown() ) );
    88 
    89     a = new QAction( "Select left branch", this);
    90 	a->setShortcut (Qt::Key_Left );
    91 //	a->setShortcutContext (Qt::WindowShortcut);
    92 	a->setShortcutContext (Qt::WidgetWithChildrenShortcut);
    93 	addAction (a);
    94     connect( a, SIGNAL( triggered() ), this, SLOT( cursorLeft() ) );
    95 
    96     a = new QAction( "Select child branch", this);
    97 	a->setShortcut (Qt::Key_Right);
    98 	a->setShortcutContext (Qt::WidgetWithChildrenShortcut);
    99 	addAction (a);
   100     connect( a, SIGNAL( triggered() ), this, SLOT( cursorRight() ) );
   101 
   102     a = new QAction(  "Select first branch", this);
   103 	a->setShortcut (Qt::Key_Home );
   104 	a->setShortcutContext (Qt::WidgetWithChildrenShortcut);
   105 	addAction (a);
   106     connect( a, SIGNAL( triggered() ), this, SLOT( cursorFirst() ) );
   107 
   108     a = new QAction( "Select last branch",this);
   109 	a->setShortcut ( Qt::Key_End );
   110 	a->setShortcutContext (Qt::WidgetWithChildrenShortcut);
   111 	addAction (a);
   112     connect( a, SIGNAL( triggered() ), this, SLOT( cursorLast() ) );
   113 
   114 	// Action to embed LineEdit for heading in Scene
   115 	editingHeading=false;
   116 	lineEdit=NULL;
   117 
   118 	a = new QAction( tr( "Edit heading","MapEditor" ), this);
   119 	a->setShortcut ( Qt::Key_Return );					//Edit heading
   120 	a->setShortcutContext (Qt::WidgetShortcut);
   121 	addAction (a);
   122     connect( a, SIGNAL( triggered() ), this, SLOT( editHeading() ) );
   123 	a = new QAction( tr( "Edit heading","MapEditor" ), this);
   124 	a->setShortcut ( Qt::Key_Enter);					//Edit heading
   125 	addAction (a);
   126     connect( a, SIGNAL( triggered() ), this, SLOT( editHeading() ) );
   127 
   128 	// Selections
   129 	selectionColor =QColor (255,255,0);
   130 	
   131 
   132 	// Attributes	//FIXME-2 testing only...
   133 	QString k;
   134 	AttributeDef *ad;
   135 	attrTable= new AttributeTable();
   136 	k="A - StringList";
   137 	ad=attrTable->addKey (k,StringList);
   138 	if (ad)
   139 	{
   140 		QStringList sl;
   141 		sl <<"val 1"<<"val 2"<< "val 3";
   142 		ad->setValue (QVariant (sl));
   143 	}
   144 	//attrTable->addValue ("Key A","P 1");
   145 	//attrTable->addValue ("Key A","P 2");
   146 	//attrTable->addValue ("Key A","P 3");
   147 	//attrTable->addValue ("Key A","P 4");
   148 	k="B - FreeString";
   149 	ad=attrTable->addKey (k,FreeString);
   150 	if (ad)
   151 	{
   152 		//attrTable->addValue ("Key B","w1");
   153 		//attrTable->addValue ("Key B","w2");
   154 	}
   155 	k="C - UniqueString";
   156 	ad=attrTable->addKey (k,UniqueString);
   157 	if (ad)
   158 	{
   159 	//attrTable->addKey ("Key Prio");
   160 	//attrTable->addValue ("Key Prio","Prio 1");
   161 	//attrTable->addValue ("Key Prio","Prio 2");
   162 	}
   163 }
   164 
   165 MapEditor::~MapEditor()
   166 {
   167 	//cout <<"Destructor MapEditor for "<<model->getMapName().toStdString()<<endl;
   168 	model->unregisterEditor(this);
   169 }
   170 
   171 VymModel* MapEditor::getModel()
   172 {
   173     return model;
   174 }
   175 
   176 QGraphicsScene * MapEditor::getScene()
   177 {
   178     return mapScene;
   179 }
   180 
   181 void MapEditor::scrollTo (const QModelIndex &index)	
   182 {
   183 	if (index.isValid())
   184 	{
   185 		LinkableMapObj* lmo=NULL;
   186 		TreeItem *ti= static_cast<TreeItem*>(index.internalPointer());
   187 		if (ti->getType()==TreeItem::Image ||ti->isBranchLikeType() )
   188 			lmo=((MapItem*)ti)->getLMO();
   189 		if (lmo) 
   190 		{
   191 			QRectF r=lmo->getBBox();
   192 			setScrollBarPosTarget (r);
   193 		}	
   194 	}
   195 }
   196 
   197 void MapEditor::setScrollBarPosTarget (const QRectF &rect)
   198 {
   199 	// Code copied from Qt sources
   200 	int xmargin=50;
   201 	int ymargin=50;
   202 
   203     qreal width = viewport()->width();
   204     qreal height = viewport()->height();
   205     QRectF viewRect = matrix().mapRect(rect);
   206 
   207     qreal left = horizontalScrollBar()->value();
   208     qreal right = left + width;
   209     qreal top = verticalScrollBar()->value();
   210     qreal bottom = top + height;
   211 
   212 	scrollBarPosTarget=getScrollBarPos();
   213 
   214     if (viewRect.left() <= left + xmargin) {
   215         // need to scroll from the left
   216   //      if (!d->leftIndent)
   217             scrollBarPosTarget.setX(int(viewRect.left() - xmargin - 0.5));
   218     }
   219     if (viewRect.right() >= right - xmargin) {
   220         // need to scroll from the right
   221 //        if (!d->leftIndent)
   222             scrollBarPosTarget.setX(int(viewRect.right() - width + xmargin + 0.5));
   223     }
   224     if (viewRect.top() <= top + ymargin) {
   225         // need to scroll from the top
   226    //     if (!d->topIndent)
   227             scrollBarPosTarget.setY(int(viewRect.top() - ymargin - 0.5));
   228     }
   229     if (viewRect.bottom() >= bottom - ymargin) {
   230         // need to scroll from the bottom
   231 //        if (!d->topIndent)
   232             scrollBarPosTarget.setY(int(viewRect.bottom() - height + ymargin + 0.5));
   233     }
   234 
   235 	if (scrollBarPosTarget==getScrollBarPos()) return;
   236 
   237 	if (scrollBarPosAnimation.state()==QtAbstractAnimation::Running)
   238 		scrollBarPosAnimation.stop();
   239 	
   240 	if (settings.value ("/animation/use/",true).toBool() )
   241 	{
   242 		scrollBarPosAnimation.setTargetObject (this);
   243 		scrollBarPosAnimation.setPropertyName ("scrollBarPos");
   244 		scrollBarPosAnimation.setDuration(1000);
   245 		scrollBarPosAnimation.setEasingCurve ( QtEasingCurve::OutQuint);
   246 		scrollBarPosAnimation.setStartValue(
   247 			QPointF (horizontalScrollBar()->value() ,
   248 					 verticalScrollBar()->value() ) );
   249 		scrollBarPosAnimation.setEndValue(scrollBarPosTarget);
   250 		scrollBarPosAnimation.start();
   251 	} else
   252 		setScrollBarPos (scrollBarPosTarget);
   253 }
   254 
   255 QPointF MapEditor::getScrollBarPosTarget()
   256 {
   257     return scrollBarPosTarget;
   258 }
   259 
   260 
   261 void MapEditor::setScrollBarPos(const QPointF &p)
   262 {
   263     scrollBarPos=p;
   264 	horizontalScrollBar()->setValue(int(p.x()));
   265 	verticalScrollBar()->setValue(int(p.y()));
   266 }
   267 
   268 QPointF MapEditor::getScrollBarPos()
   269 {
   270 	return QPointF (horizontalScrollBar()->value(),verticalScrollBar()->value());
   271     //return scrollBarPos;
   272 }
   273 
   274 void MapEditor::setZoomFactorTarget (const qreal &zft)
   275 {
   276 	zoomFactorTarget=zft;
   277 	if (zoomAnimation.state()==QtAbstractAnimation::Running)
   278 		zoomAnimation.stop();
   279 	if (settings.value ("/animation/use/",true).toBool() )
   280 	{
   281 		//zoomAnimation=QPropertyAnimation(this, "zoomFactor");
   282 		zoomAnimation.setTargetObject (this);
   283 		zoomAnimation.setPropertyName ("zoomFactor");
   284 		zoomAnimation.setDuration(1000);
   285 		zoomAnimation.setEasingCurve ( QtEasingCurve::OutQuint);
   286 		zoomAnimation.setStartValue(zoomFactor);
   287 		zoomAnimation.setEndValue(zft);
   288 		zoomAnimation.start();
   289 	} else
   290 		setZoomFactor (zft);
   291 }
   292 
   293 qreal MapEditor::getZoomFactorTarget()
   294 {
   295     return zoomFactorTarget;
   296 }
   297 
   298 
   299 void MapEditor::setZoomFactor(const qreal &zf)
   300 {
   301     zoomFactor=zf;
   302 	setMatrix (QMatrix(zf, 0, 0, zf, 0, 0),false );
   303 }
   304 
   305 qreal MapEditor::getZoomFactor()
   306 {
   307     return zoomFactor;
   308 }
   309 
   310 void MapEditor::print()
   311 {
   312 	if ( !printer ) 
   313 	{
   314 		printer = new QPrinter;
   315 		printer->setColorMode (QPrinter::Color);
   316 		printer->setPrinterName (settings.value("/mainwindow/printerName",printer->printerName()).toString());
   317 		printer->setOutputFormat((QPrinter::OutputFormat)settings.value("/mainwindow/printerFormat",printer->outputFormat()).toInt());
   318 		printer->setOutputFileName(settings.value("/mainwindow/printerFileName",printer->outputFileName()).toString());
   319 	}
   320 
   321 	QRectF totalBBox=getTotalBBox();
   322 
   323 	// Try to set orientation automagically
   324 	// Note: Interpretation of generated postscript is amibiguous, if 
   325 	// there are problems with landscape mode, see
   326 	// http://sdb.suse.de/de/sdb/html/jsmeix_print-cups-landscape-81.html
   327 
   328 	if (totalBBox.width()>totalBBox.height())
   329 		// recommend landscape
   330 		printer->setOrientation (QPrinter::Landscape);
   331 	else	
   332 		// recommend portrait
   333 		printer->setOrientation (QPrinter::Portrait);
   334 
   335 	if ( printer->setup(this) ) 
   336 	// returns false, if printing is canceled
   337 	{
   338 		QPainter pp(printer);
   339 
   340 		pp.setRenderHint(QPainter::Antialiasing,true);
   341 
   342 		// Don't print the visualisation of selection
   343 		model->unselect();
   344 
   345 		QRectF mapRect=totalBBox;
   346 		QGraphicsRectItem *frame=NULL;
   347 
   348 		if (printFrame) 
   349 		{
   350 			// Print frame around map
   351 			mapRect.setRect (totalBBox.x()-10, totalBBox.y()-10, 
   352 				totalBBox.width()+20, totalBBox.height()+20);
   353 			frame=mapScene->addRect (mapRect, QPen(Qt::black),QBrush(Qt::NoBrush));
   354 			frame->setZValue(0);
   355 			frame->show();    
   356 		}		
   357 
   358 
   359 		double paperAspect = (double)printer->width()   / (double)printer->height();
   360 		double   mapAspect = (double)mapRect.width() / (double)mapRect.height();
   361 		int viewBottom;
   362 		if (mapAspect>=paperAspect)
   363 		{
   364 			// Fit horizontally to paper width
   365 			//pp.setViewport(0,0, printer->width(),(int)(printer->width()/mapAspect) );	
   366 			viewBottom=(int)(printer->width()/mapAspect);	
   367 		}	else
   368 		{
   369 			// Fit vertically to paper height
   370 			//pp.setViewport(0,0,(int)(printer->height()*mapAspect),printer->height());	
   371 			viewBottom=printer->height();	
   372 		}	
   373 		
   374 		if (printFooter) 
   375 		{
   376 			// Print footer below map
   377 			QFont font;		
   378 			font.setPointSize(10);
   379 			pp.setFont (font);
   380 			QRectF footerBox(0,viewBottom,printer->width(),15);
   381 			// FIXME-3 fileName not any longer available here: pp.drawText ( footerBox,Qt::AlignLeft,"VYM - " +fileName);
   382 			pp.drawText ( footerBox, Qt::AlignRight, QDate::currentDate().toString(Qt::TextDate));
   383 		}
   384 		mapScene->render (
   385 			&pp, 
   386 			QRectF (0,0,printer->width(),printer->height()-15),
   387 			QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height())
   388 		);
   389 		
   390 		// Viewport has paper dimension
   391 		if (frame)  delete (frame);
   392 
   393 		// Restore selection
   394 		model->reselect();
   395 
   396 		// Save settings in vymrc
   397 		settings.writeEntry("/mainwindow/printerName",printer->printerName());
   398 		settings.writeEntry("/mainwindow/printerFormat",printer->outputFormat());
   399 		settings.writeEntry("/mainwindow/printerFileName",printer->outputFileName());
   400 	}
   401 }
   402 
   403 QRectF MapEditor::getTotalBBox()	
   404 {
   405 	QPen pen;
   406 	pen.setWidth (1);
   407 	pen.setCapStyle ( Qt::RoundCap );
   408 
   409 	QRectF rt;
   410 	BranchObj *bo;
   411 	BranchItem *cur=NULL;
   412 	BranchItem *prev=NULL;
   413 	model->nextBranch(cur,prev);
   414 	while (cur) 
   415 	{
   416 		if (!cur->hasHiddenExportParent())
   417 		{
   418 			bo=(BranchObj*)(cur->getLMO());
   419 			if (bo && bo->isVisibleObj())
   420 			{
   421 				bo->calcBBoxSizeWithChildren();
   422 				// FIXME-3 testing
   423 				//QRectF r1=bo->getBBoxSizeWithChildren();
   424 				QRectF r1=bo->getBBox();
   425 				//pen.setColor ( QColor(qrand()%32*8,qrand()%32*8,qrand()%32*8));
   426 				//mapScene->addRect (r1,pen);
   427 
   428 				if (rt.isNull()) rt=r1;
   429 				rt=addBBox (r1, rt);
   430 				//FIXME-2 cout <<"ME: r1="<<r1<<"  "<<cur->getHeadingStd()<<endl;
   431 				//cout <<"    rt="<<rt<<endl;
   432 			}
   433 		}
   434 		model->nextBranch(cur,prev);
   435 	}
   436 	return rt;	
   437 }
   438 
   439 
   440 QImage MapEditor::getImage()
   441 {
   442 	QRectF mapRect=getTotalBBox();
   443 	int w=mapRect.width()+2;
   444 	int h=mapRect.height()+2;
   445 	
   446 	QImage pix (w,h,QImage::Format_RGB32);
   447 
   448 	QPainter pp (&pix);
   449 
   450 	pp.setRenderHints(renderHints());
   451 	mapScene->render (	&pp, 
   452 		QRectF(0,0,w,h),
   453 		QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
   454 	return pix;
   455 }
   456 
   457 
   458 void MapEditor::setAntiAlias (bool b)
   459 {
   460 	setRenderHint(QPainter::Antialiasing,b);
   461 }
   462 
   463 void MapEditor::setSmoothPixmap(bool b)
   464 {
   465 	setRenderHint(QPainter::SmoothPixmapTransform,b);
   466 }
   467 
   468 void MapEditor::setHideTmp (bool b)	// FIXME-4 better use signals
   469 {
   470 /*
   471 	if (b)
   472 	{
   473 		setHideTmpMode (HideExport);
   474 		mapCenter->calcBBoxSizeWithChilds();
   475 		QRectF totalBBox=mapCenter->getTotalBBox();
   476 		//QRectF mapRect=totalBBox;
   477 		cout << "  map has =("<<totalBBox.x()<<","<<totalBBox.y()<<","<<totalBBox.width()<<","<<totalBBox.height()<<")\n";
   478 	
   479 		mapRect.setRect (totalBBox.x(), totalBBox.y(), 
   480 			totalBBox.width(), totalBBox.height());
   481 			
   482 		QCanvasRectangle *frame=new QCanvasRectangle (mapRect,mapScene);
   483 		frame->setBrush (QColor(white));
   484 		frame->setPen (QColor(black));
   485 		frame->setZValue(0);
   486 		frame->show();    
   487 		
   488 	}	
   489 	else	
   490 	{
   491 		setHideTmpMode (HideNone);
   492 	}	
   493 	cout <<"  hidemode="<<hidemode<<endl;
   494 */
   495 /*
   496 	// Toggle hidemode
   497 	if (hidemode==HideExport)
   498 		setHideTmpMode (HideNone);
   499 	else	
   500 		setHideTmpMode (HideExport);
   501 */		
   502 }
   503 
   504 TreeItem* MapEditor::findMapItem (QPointF p,TreeItem *exclude)
   505 {
   506 	// Start with mapcenter, no images allowed at rootItem
   507 	int i=0;
   508 	BranchItem *bi=model->getRootItem()->getFirstBranch();
   509 	TreeItem *found=NULL;
   510 	while (bi)
   511 	{
   512 		found=bi->findMapItem (p, exclude);
   513 		if (found) return found;
   514 		i++;
   515 		bi=model->getRootItem()->getBranchNum(i);
   516 	}
   517 	return NULL;
   518 }
   519 
   520 AttributeTable* MapEditor::attributeTable()
   521 {
   522 	return attrTable;
   523 }
   524 
   525 void MapEditor::testFunction1()
   526 {
   527 	cout << "ME::test1  selected TI="<<model->getSelectedItem()<<endl;
   528 	model->setExportMode (true);
   529 
   530 	/*
   531 	// Code copied from Qt sources
   532 	QRectF rect=model->getSelectedBranchObj()->getBBox();
   533 	int xmargin=50;
   534 	int ymargin=50;
   535 
   536     qreal width = viewport()->width();
   537     qreal height = viewport()->height();
   538     QRectF viewRect = matrix().mapRect(rect);
   539 
   540     qreal left = horizontalScrollBar()->value();
   541     qreal right = left + width;
   542     qreal top = verticalScrollBar()->value();
   543     qreal bottom = top + height;
   544 
   545     if (viewRect.left() <= left + xmargin) {
   546         // need to scroll from the left
   547   //      if (!d->leftIndent)
   548             horizontalScrollBar()->setValue(int(viewRect.left() - xmargin - 0.5));
   549     }
   550     if (viewRect.right() >= right - xmargin) {
   551         // need to scroll from the right
   552 //        if (!d->leftIndent)
   553             horizontalScrollBar()->setValue(int(viewRect.right() - width + xmargin + 0.5));
   554     }
   555     if (viewRect.top() <= top + ymargin) {
   556         // need to scroll from the top
   557    //     if (!d->topIndent)
   558             verticalScrollBar()->setValue(int(viewRect.top() - ymargin - 0.5));
   559     }
   560     if (viewRect.bottom() >= bottom - ymargin) {
   561         // need to scroll from the bottom
   562 //        if (!d->topIndent)
   563             verticalScrollBar()->setValue(int(viewRect.bottom() - height + ymargin + 0.5));
   564     }
   565 	cout << "test1:  hor="<<horizontalScrollBar()->value()<<endl;
   566 	cout << "test1:  ver="<<verticalScrollBar()->value()<<endl;
   567 }
   568 
   569 */
   570 /*
   571 	 QtPropertyAnimation *animation=new QtPropertyAnimation(this, "sceneRect");
   572 	 animation->setDuration(5000);
   573 	 //animation->setEasingCurve ( QtEasingCurve::OutElastic);
   574 	 animation->setEasingCurve ( QtEasingCurve::OutQuint);
   575 	 animation->setStartValue(sceneRect() );
   576 	 animation->setEndValue(QRectF(50, 50, 1000, 1000));
   577 
   578 	 animation->start();
   579 */	 
   580 /*
   581 	QDialog *dia= new QDialog (this);
   582 	dia->setGeometry (50,50,10,10);
   583 
   584      dia->show();
   585      dia ->raise();
   586 
   587 	 QtPropertyAnimation *animation=new QtPropertyAnimation(dia, "geometry");
   588 	 animation->setDuration(1000);
   589 	 //animation->setEasingCurve ( QtEasingCurve::OutElastic);
   590 	 animation->setEasingCurve ( QtEasingCurve::OutQuint);
   591 	 animation->setStartValue(QRect(50, 50, 10, 10));
   592 	 animation->setEndValue(QRect(250, 250, 100, 100));
   593 
   594 	 animation->start();
   595  */
   596 
   597 }
   598 	
   599 void MapEditor::testFunction2()
   600 {
   601 	model->setExportMode (false);
   602 	return;
   603 
   604 	// Create list with all bounding polygons
   605 	QList <LinkableMapObj*> mapobjects;
   606 	QList <ConvexPolygon> polys; 
   607 	ConvexPolygon p;
   608 	QList <Vector> vectors;
   609 	QList <Vector> orgpos;
   610 	QStringList headings;	//FIXME-3 testing only
   611 	Vector v;
   612 	BranchItem *bi;
   613 	BranchItem *bi2;
   614 	BranchObj *bo;
   615 
   616 	// Outer loop: Iterate until we no more changes in orientation 
   617 	bool orientationChanged=true;
   618 	while (orientationChanged)
   619 	{
   620 		BranchItem *ri=model->getRootItem();
   621 		for (int i=0;i<ri->branchCount();++i)
   622 		{
   623 			bi=ri->getBranchNum (i);
   624 			bo=(BranchObj*)bi->getLMO();
   625 			if (bo)
   626 			{
   627 				mapobjects.append (bo);
   628 				p=bo->getBoundingPolygon();
   629 				p.calcCentroid();
   630 				polys.append(p);
   631 				vectors.append (QPointF(0,0));
   632 				orgpos.append (p.at(0));
   633 				headings.append (bi->getHeading());
   634 			}
   635 			for (int j=0;j<bi->branchCount();++j)
   636 			{
   637 				bi2=bi->getBranchNum (j);
   638 				bo=(BranchObj*)bi2->getLMO();
   639 				if (bo)
   640 				{
   641 					mapobjects.append (bo);
   642 					p=bo->getBoundingPolygon();
   643 					p.calcCentroid();
   644 					polys.append(p);
   645 					vectors.append (QPointF(0,0));
   646 					orgpos.append (p.at(0));
   647 					headings.append (bi2->getHeading());
   648 				}	
   649 			}
   650 		}
   651 
   652 		// Iterate moving bounding polygons until we have no more collisions
   653 		int collisions=1;
   654 		while (collisions>0)
   655 		{
   656 			collisions=0;
   657 			for (int i=0; i<polys.size()-1; ++i)
   658 			{
   659 				for (int j=i+1; j<polys.size();++j)
   660 				{
   661 					if (polygonCollision (polys.at(i),polys.at(j), QPointF(0,0)).intersect )
   662 					{
   663 						collisions++;
   664 						//cout << "Collision: "<<headings[i].toStdString()<<" - "<<headings[j].toStdString()<<endl;
   665 						v=polys.at(j).centroid()-polys.at(i).centroid();
   666 						// Move also away if centroids are identical
   667 						if (v.isNull()) 
   668 						{
   669 							//cout << "v==0="<<polys[i].centroid()<<polys[j].centroid()<<" "<<v<<endl;
   670 							v.setX (rand()%200 -100);
   671 							v.setY (rand()%200 -100);
   672 							//cout << v;
   673 						}
   674 						v.normalize();
   675 						v.scale (2);
   676 						//cout <<  "  v="<<v<<endl;
   677 						vectors[j]=v;
   678 						vectors[i]=v;
   679 						vectors[i].invert();
   680 					}  
   681 				}
   682 			}
   683 			for (int i=0;i<vectors.size();i++)
   684 			{
   685 				//cout << " v="<<vectors[i]<<" "<<headings[i].toStdString()<<endl;
   686 				polys[i].translate (vectors[i]);
   687 			}
   688 			cout << "Collisions: "<<collisions<<endl;
   689 			//collisions=0;
   690 		}	
   691 
   692 		// Finally move the real objects and update 
   693 		QList <LinkableMapObj::Orientation> orients;
   694 		for (int i=0;i<polys.size();i++)
   695 		{
   696 			Vector v=polys[i].at(0)-orgpos[i];
   697 			orients.append (mapobjects[i]->getOrientation());
   698 			mapobjects[i]->moveBy(v.x(),v.y() );
   699 			mapobjects[i]->setRelPos();
   700 		}	
   701 		model->reposition();	
   702 		orientationChanged=false;
   703 		for (int i=0;i<polys.size();i++)
   704 			if (orients[i]!=mapobjects[i]->getOrientation())
   705 			{
   706 				orientationChanged=true;
   707 				break;
   708 			}
   709 		cout << "Final: orientChanged="<<orientationChanged<<endl;
   710 		break;
   711 		//orientationChanged=false;
   712 	} // loop if orientation has changed
   713 
   714 	model->emitSelectionChanged();
   715 }
   716 
   717 BranchItem* MapEditor::getBranchDirectAbove (BranchItem *bi)
   718 {
   719 	if (bi)
   720 	{
   721 		int i=bi->num();
   722 		if (i>0) return bi->parent()->getBranchNum(i-1);
   723 	}
   724 	return NULL;
   725 }
   726 
   727 BranchItem* MapEditor::getBranchAbove (BranchItem *selbi)
   728 {
   729 	if (selbi)
   730 	{
   731 		int dz=selbi->depth();	// original depth
   732 		bool invert=false;
   733 		if (selbi->getLMO()->getOrientation()==LinkableMapObj::LeftOfCenter)
   734 			invert=true;
   735 
   736 		BranchItem *bi;
   737 
   738 		// Look for branch with same parent but directly above
   739 		if (dz==1 && invert)
   740 			bi=getBranchDirectBelow(selbi);
   741 		else
   742 			bi=getBranchDirectAbove (selbi);
   743 
   744 		if (bi) 
   745 			// direct predecessor
   746 			return bi;
   747 
   748 		// Go towards center and look for predecessor
   749 		while (selbi->depth()>0)
   750 		{
   751 			selbi=(BranchItem*)(selbi->parent());
   752 			if (selbi->depth()==1 && invert)
   753 				bi=getBranchDirectBelow (selbi);
   754 			else
   755 				bi=getBranchDirectAbove (selbi);
   756 			if (bi)
   757 			{
   758 				// turn 
   759 				selbi=bi;
   760 				while (selbi->depth()<dz)
   761 				{
   762 					// try to get back to original depth dz
   763 					bi=selbi->getLastBranch();
   764 					if (!bi) 
   765 					{
   766 						return selbi;
   767 					}
   768 					selbi=bi;
   769 				}
   770 				return selbi;
   771 			}
   772 		}
   773 	}
   774 	return NULL;
   775 }
   776 
   777 BranchItem* MapEditor::getBranchDirectBelow(BranchItem *bi)
   778 {
   779 	if (bi)
   780 	{
   781 		int i=bi->num();
   782 		if (i+1<bi->parent()->branchCount()) return bi->parent()->getBranchNum(i+1);
   783 	}
   784 	return NULL;
   785 }
   786 
   787 BranchItem* MapEditor::getBranchBelow (BranchItem *selbi)
   788 {
   789 	if (selbi)
   790 	{
   791 		BranchItem *bi;
   792 		int dz=selbi->depth();	// original depth
   793 		bool invert=false;
   794 		if (selbi->getLMO()->getOrientation()==LinkableMapObj::LeftOfCenter)
   795 			invert=true;
   796 
   797 
   798 		// Look for branch with same parent but directly below
   799 		if (dz==1 && invert)
   800 			bi=getBranchDirectAbove (selbi);
   801 		else
   802 			bi=getBranchDirectBelow (selbi);
   803 		if (bi) 
   804 			// direct successor
   805 			return bi;
   806 
   807 
   808 		// Go towards center and look for neighbour
   809 		while (selbi->depth()>0)
   810 		{
   811 			selbi=(BranchItem*)(selbi->parent());
   812 			if (selbi->depth()==1 && invert)
   813 				bi=getBranchDirectAbove (selbi);
   814 			else
   815 				bi=getBranchDirectBelow (selbi);
   816 			if (bi)
   817 			{
   818 				// turn 
   819 				selbi=bi;
   820 				while (selbi->depth()<dz)
   821 				{
   822 					// try to get back to original depth dz
   823 					bi=selbi->getFirstBranch();
   824 					if (!bi) 
   825 					{
   826 						return selbi;
   827 					}
   828 					selbi=bi;
   829 				}
   830 				return selbi;
   831 			}
   832 		}
   833 	}
   834 	return NULL;
   835 }
   836 
   837 BranchItem* MapEditor::getLeftBranch (BranchItem *bi)
   838 {
   839 	if (bi)
   840 	{
   841 		if (bi->depth()==0)
   842 			// Special case: use alternative selection index
   843 			return bi->getLastSelectedBranchAlt();	
   844 		if (bi->getBranchObj()->getOrientation()==LinkableMapObj::RightOfCenter)	
   845 			// right of center
   846 			return (BranchItem*)(bi->parent());
   847 		else
   848 			// left of center
   849 			if (bi->getType()== TreeItem::Branch )
   850 				return bi->getLastSelectedBranch();
   851 	}
   852 	return NULL;
   853 }
   854 
   855 BranchItem* MapEditor::getRightBranch(BranchItem *bi)
   856 {
   857 	if (bi)
   858 	{
   859 		if (bi->depth()==0) return bi->getLastSelectedBranch();	
   860 		if (bi->getBranchObj()->getOrientation()==LinkableMapObj::LeftOfCenter)	
   861 			// left of center
   862 			return (BranchItem*)(bi->parent());
   863 		else
   864 			// right of center
   865 			if (bi->getType()== TreeItem::Branch )
   866 				return (BranchItem*)bi->getLastSelectedBranch();
   867 	}
   868 	return NULL;
   869 }
   870 
   871 
   872 
   873 void MapEditor::cursorUp()
   874 {
   875 	BranchItem *bi=model->getSelectedBranch();
   876 	if (bi) model->select (getBranchAbove(bi));
   877 }
   878 
   879 void MapEditor::cursorDown()	
   880 
   881 {
   882 	BranchItem *bi=model->getSelectedBranch();
   883 	if (bi) model->select (getBranchBelow(bi));
   884 }
   885 
   886 void MapEditor::cursorLeft()
   887 {
   888 	BranchItem *bi=getLeftBranch (model->getSelectedBranch());
   889 	if (bi) model->select (bi);
   890 }
   891 
   892 void MapEditor::cursorRight()	
   893 {
   894 	BranchItem *bi=getRightBranch (model->getSelectedBranch());
   895 	if (bi) model->select (bi);
   896 }
   897 
   898 void MapEditor::cursorFirst()	
   899 {
   900 	model->selectFirstBranch();
   901 }
   902 
   903 void MapEditor::cursorLast()	
   904 {
   905 	model->selectLastBranch();
   906 }
   907 
   908 
   909 void MapEditor::editHeading()
   910 {
   911 	if (editingHeading)
   912 	{
   913 		editHeadingFinished();
   914 		return;
   915 	}
   916 	BranchObj *bo=model->getSelectedBranchObj();
   917 	BranchItem *bi=model->getSelectedBranch();
   918 	if (bo)	
   919 	{
   920 		model->setSelectionBlocked(true);
   921 
   922 		lineEdit=new QLineEdit;
   923 		QGraphicsProxyWidget *pw=scene()->addWidget (lineEdit);
   924 		pw->setZValue (Z_LINEEDIT);
   925 
   926 		lineEdit->setText (bi->getHeading());
   927 		QPoint p = mapTo (this,bo->getAbsPos().toPoint() );
   928 		lineEdit->setGeometry(p.x(),p.y(),230,25);
   929 		//lineEdit->selectAll();
   930 		//lineEdit->setCursorPosition (1);
   931 		lineEdit->show();
   932 		lineEdit->setFocus();
   933 		lineEdit->grabKeyboard();
   934 		editingHeading=true;
   935 	}
   936 
   937 }
   938 void MapEditor::editHeadingFinished()
   939 {
   940 	editingHeading=false;
   941 	lineEdit->releaseKeyboard();
   942 	lineEdit->clearFocus();
   943 	model->setHeading (lineEdit->text() );
   944 	model->setSelectionBlocked(false);
   945 	delete (lineEdit);
   946 
   947 	// Maybe reselect previous branch 
   948 	mainWindow->editHeadingFinished (model);
   949 }
   950 
   951 
   952 void MapEditor::contextMenuEvent ( QContextMenuEvent * e )
   953 {
   954 	// Lineedits are already closed by preceding
   955 	// mouseEvent, we don't need to close here.
   956 
   957     QPointF p = mapToScene(e->pos());
   958     TreeItem *ti=findMapItem (p, NULL);
   959     LinkableMapObj* lmo=NULL;
   960 	if (ti) lmo=((MapItem*)ti)->getLMO();
   961 	
   962     if (lmo) 
   963 	{	// MapObj was found
   964 		if (model->getSelectedLMO() != lmo)
   965 		{
   966 			// select the MapObj
   967 			model->select(lmo);
   968 		}
   969 		// Context Menu 
   970 		if (model->getSelectedBranchObj() ) 
   971 		{
   972 			// Context Menu on branch or mapcenter
   973 			branchContextMenu->popup(e->globalPos() );
   974 		} else
   975 		{
   976 			if (model->getSelectedImage() )
   977 			{
   978 				// Context Menu on floatimage
   979 				floatimageContextMenu->popup(e->globalPos() );
   980 			}	
   981 		}	
   982 	} else 
   983 	{ // No MapObj found, we are on the Canvas itself
   984 		// Context Menu on scene
   985 		
   986 		// Open context menu synchronously to position new mapcenter
   987 		model->setContextPos (p);
   988 		canvasContextMenu->exec(e->globalPos() );
   989 		model->unsetContextPos ();
   990     } 
   991 	e->accept();
   992 }
   993 
   994 void MapEditor::keyPressEvent(QKeyEvent* e)
   995 {
   996 	if (e->modifiers() & Qt::ControlModifier)
   997 	{
   998 		switch (mainWindow->getModMode())
   999 		{
  1000 			case Main::ModModeColor: 
  1001 				setCursor (PickColorCursor);
  1002 				break;
  1003 			case Main::ModModeCopy: 
  1004 				setCursor (CopyCursor);
  1005 				break;
  1006 			case Main::ModModeXLink: 
  1007 				setCursor (XLinkCursor);
  1008 				break;
  1009 			default :
  1010 				setCursor (Qt::ArrowCursor);
  1011 				break;
  1012 		} 
  1013 	}	
  1014 }
  1015 
  1016 void MapEditor::keyReleaseEvent(QKeyEvent* e)
  1017 {
  1018 	if (!(e->modifiers() & Qt::ControlModifier))
  1019 		setCursor (Qt::ArrowCursor);
  1020 }
  1021 
  1022 void MapEditor::mousePressEvent(QMouseEvent* e)
  1023 {
  1024 //cout << "ME::mousePressed\n"; //FIXME-3
  1025 	// Ignore right clicks, these will go to context menus
  1026 	if (e->button() == Qt::RightButton )
  1027 	{
  1028 		//cout << "  ME::ignoring right mouse event...\n";
  1029 		e->ignore();
  1030 		return;
  1031 	}
  1032 
  1033 	//Ignore clicks while editing heading
  1034 	if (model->isSelectionBlocked() ) 
  1035 	{
  1036 		//cout << "  ME::ignoring other mouse event...\n";
  1037 		e->ignore();
  1038 		return;
  1039 	}
  1040 
  1041     QPointF p = mapToScene(e->pos());
  1042     TreeItem *ti=findMapItem (p, NULL);
  1043     LinkableMapObj* lmo=NULL;
  1044 	if (ti) lmo=((MapItem*)ti)->getLMO();
  1045 	
  1046 	
  1047 	e->accept();
  1048 
  1049 	//Take care of  system flags _or_ modifier modes
  1050 	//
  1051 	if (lmo && ti->isBranchLikeType() )
  1052 	{
  1053 		QString foname=((BranchObj*)lmo)->getSystemFlagName(p);
  1054 		if (!foname.isEmpty())
  1055 		{
  1056 			// systemFlag clicked
  1057 			model->select (lmo);	
  1058 			if (foname=="system-url") 
  1059 			{
  1060 				if (e->state() & Qt::ControlModifier)
  1061 					mainWindow->editOpenURLTab();
  1062 				else	
  1063 					mainWindow->editOpenURL();
  1064 			}	
  1065 			else if (foname=="system-vymLink")
  1066 			{
  1067 				mainWindow->editOpenVymLink();
  1068 				// tabWidget may change, better return now
  1069 				// before segfaulting...
  1070 			} else if (foname=="system-note")
  1071 				mainWindow->windowToggleNoteEditor();
  1072 			else if (foname=="hideInExport")		
  1073 				model->toggleHideExport();
  1074 			// FIXME-3 needed? xelection.update();	
  1075 			return;	
  1076 		} else
  1077 		{
  1078 			// Take care of xLink
  1079 			if (ti->xlinkCount()>0 && lmo->getBBox().width()>30)
  1080 			{
  1081 				if ((lmo->getOrientation()!=LinkableMapObj::RightOfCenter && p.x() < lmo->getBBox().left()+20)  ||
  1082 				    (lmo->getOrientation()!=LinkableMapObj::LeftOfCenter && p.x() > lmo->getBBox().right()-20) ) 
  1083 				{
  1084 					// FIXME-4 if (ti->xlinkCount()>1)
  1085 					if (true)
  1086 					{
  1087 						QMenu menu;
  1088 						QList <QAction*> alist;
  1089 						for (int i=0;i<ti->xlinkCount();i++)
  1090 							alist.append (new QAction(ti->getXLinkNum(i)->getOtherBranch(ti)->getHeading(),&menu));
  1091 						menu.addActions (alist);	
  1092 						QAction *ra=menu.exec (e->globalPos() );
  1093 						if (ra)
  1094 							model->select (ti->getXLinkNum(alist.indexOf(ra))->getOtherBranch (ti));
  1095 						while (!alist.isEmpty())
  1096 						{
  1097 							QAction *a=alist.takeFirst();
  1098 							delete a;
  1099 						}	
  1100 						return;
  1101 					} else
  1102 					{
  1103 						model->select (ti->getXLinkNum(0)->getOtherBranch (ti));
  1104 						return;
  1105 					}
  1106 				}	
  1107 			}
  1108 		}
  1109 	}	
  1110 
  1111 	// No system flag clicked, take care of modmodes (CTRL-Click)
  1112 	if (e->state() & Qt::ControlModifier)
  1113 	{
  1114 		if (mainWindow->getModMode()==Main::ModModeColor)
  1115 		{
  1116 				pickingColor=true;
  1117 				setCursor (PickColorCursor);
  1118 				return;
  1119 		} 
  1120 		if (mainWindow->getModMode()==Main::ModModeXLink)
  1121 		{	
  1122 			BranchItem *bi_begin=model->getSelectedBranch();
  1123 			if (bi_begin)	
  1124 			{
  1125 				drawingLink=true;
  1126 				tmpXLink=model->createXLink(bi_begin,true);
  1127 				tmpXLink->setColor(model->getMapDefXLinkColor());
  1128 				tmpXLink->setWidth(model->getMapDefXLinkWidth());
  1129 				tmpXLink->setEnd   (p);
  1130 				tmpXLink->updateXLink();
  1131 				return;
  1132 			} 
  1133 		}
  1134 	}	// End of modmodes
  1135 
  1136     if (lmo) 
  1137 	{	
  1138 	/*
  1139 		cout << "ME::mouse pressed\n";
  1140 		cout << "  lmo="<<lmo<<endl;
  1141 		cout << "   ti="<<ti->getHeadingStd()<<endl;
  1142 	*/
  1143 		// Select the clicked object
  1144 
  1145 		// Get clicked LMO
  1146 		model->select (ti);
  1147 
  1148 		// Left Button	    Move Branches
  1149 		if (e->button() == Qt::LeftButton )
  1150 		{
  1151 			movingObj_start.setX( p.x() - lmo->x() );	
  1152 			movingObj_start.setY( p.y() - lmo->y() );	
  1153 			movingObj_orgPos.setX (lmo->x() );
  1154 			movingObj_orgPos.setY (lmo->y() );
  1155 			lmo->setRelPos();
  1156 			movingObj_orgRelPos=lmo->getRelPos();
  1157 
  1158 			// If modMode==copy, then we want to "move" the _new_ object around
  1159 			// then we need the offset from p to the _old_ selection, because of tmp
  1160 			if (mainWindow->getModMode()==Main::ModModeCopy &&
  1161 				e->state() & Qt::ControlModifier)
  1162 			{
  1163 				BranchItem *bi=model->getSelectedBranch();
  1164 				if (bi)
  1165 				{
  1166 					copyingObj=true;
  1167 					//FIXME-2   TreeItem::addBranch (BranchItem still missing) 
  1168 					//bi->addBranch (model->getSelectedBranch());
  1169 					model->unselect();
  1170 					model->select(bi->getLastBranch());
  1171 					model->reposition();
  1172 				}
  1173 			} 
  1174 
  1175 			movingObj=model->getSelectedLMO();	
  1176 		} else
  1177 			// Middle Button    Toggle Scroll
  1178 			// (On Mac OS X this won't work, but we still have 
  1179 			// a button in the toolbar)
  1180 			if (e->button() == Qt::MidButton )
  1181 				model->toggleScroll();
  1182 		// model->updateActions(); FIXME-3 needed?
  1183 		// FIXME-3 needed? xelection.update();
  1184 	} else 
  1185 	{ // No MapObj found, we are on the scene itself
  1186 		// Left Button	    move Pos of sceneView
  1187 		if (e->button() == Qt::LeftButton )
  1188 		{
  1189 			movingObj=NULL;	// move Content not Obj
  1190 			movingObj_start=e->globalPos();
  1191 			movingCont_start=QPointF (
  1192 				horizontalScrollBar()->value(),
  1193 				verticalScrollBar()->value());
  1194 			movingVec=QPointF(0,0);
  1195 			setCursor(HandOpenCursor);
  1196 		} 
  1197     } 
  1198 }
  1199 
  1200 void MapEditor::mouseMoveEvent(QMouseEvent* e)
  1201 {
  1202     QPointF p = mapToScene(e->pos());
  1203 	TreeItem *seli=model->getSelectedItem();
  1204 	LinkableMapObj* lmosel=NULL;	
  1205 	if (seli && (seli->isBranchLikeType() ||seli->getType()==TreeItem::Image))
  1206 		lmosel=((MapItem*)seli)->getLMO();
  1207 
  1208     // Move the selected MapObj
  1209     if ( lmosel && movingObj) 
  1210     {	
  1211 		objectMoved=true;
  1212 		// reset cursor if we are moving and don't copy
  1213 		if (mainWindow->getModMode()!=Main::ModModeCopy)
  1214 			setCursor (Qt::ArrowCursor);
  1215 
  1216 		// To avoid jumping of the sceneView, only 
  1217 		// show selection, if not tmp linked
  1218 		/* FIXME-2 if (!lmosel->hasParObjTmp())
  1219 			model->emitShowSelection();
  1220 			*/
  1221 		
  1222 		// Now move the selection, but add relative position 
  1223 		// (movingObj_start) where selection was chosen with 
  1224 		// mousepointer. (This avoids flickering resp. jumping 
  1225 		// of selection back to absPos)
  1226 		
  1227 		// Check if we could link 
  1228 		TreeItem *ti=findMapItem (p, seli);
  1229 		BranchItem *dsti=NULL;
  1230 		LinkableMapObj* dst=NULL;
  1231 		if (ti && ti!=seli && ti->isBranchLikeType())
  1232 		{
  1233 			dsti=(BranchItem*)ti;
  1234 			dst=dsti->getLMO(); 
  1235 		} else
  1236 			dsti=NULL;
  1237 		
  1238 
  1239 		if (lmosel && seli->getType()==TreeItem::Image)	
  1240 		{
  1241 			FloatObj *fio=(FloatImageObj*)lmosel;
  1242 			fio->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  1243 			fio->setRelPos();
  1244 			fio->updateLinkGeometry(); //no need for reposition, if we update link here
  1245 			model->emitSelectionChanged();	// position has changed
  1246 
  1247 			// Relink float to new mapcenter or branch, if shift is pressed	
  1248 			// Only relink, if selection really has a new parent
  1249 			if ( e->modifiers()==Qt::ShiftModifier && dsti &&  dsti != seli->parent()  )
  1250 			{
  1251 				// Also save the move which was done so far
  1252 				QString pold=qpointFToString(movingObj_orgRelPos);
  1253 				QString pnow=qpointFToString(fio->getRelPos());
  1254 				model->saveState(
  1255 					seli,
  1256 					"moveRel "+pold,
  1257 					seli,
  1258 					"moveRel "+pnow,
  1259 					QString("Move %1 to relative position %2").arg(model->getObjectName(fio)).arg(pnow));
  1260 				fio->getParObj()->requestReposition();
  1261 				model->reposition();
  1262 
  1263 				model->relinkImage ((ImageItem*) seli,dsti);
  1264 				model->select (seli);
  1265 				//movingObj=lmosel;	//FIXME-3
  1266 				//movingObj_orgRelPos=lmosel->getRelPos();	
  1267 
  1268 				model->reposition();
  1269 			}
  1270 		} else	
  1271 		{	// selection != a FloatObj
  1272 			if (seli->depth()==0)		
  1273 			{
  1274 				// Move mapcenter
  1275 				lmosel->move   (p-movingObj_start);		
  1276 				if (e->buttons()== Qt::LeftButton && e->modifiers()==Qt::ShiftModifier) 
  1277 				{
  1278 					// Move only mapcenter, leave its children where they are
  1279 					QPointF v;
  1280 					v=lmosel->getAbsPos();
  1281 					for (int i=0; i<seli->branchCount(); ++i)
  1282 					{
  1283 						seli->getBranchObjNum(i)->setRelPos();
  1284 						seli->getBranchObjNum(i)->setOrientation();
  1285 					}
  1286 				}	
  1287 			} else
  1288 			{	
  1289 				if (seli->depth()==1)
  1290 				{
  1291 					// Move mainbranch
  1292 					if (!lmosel->hasParObjTmp())
  1293 						lmosel->move(p-movingObj_start);		
  1294 					lmosel->setRelPos();
  1295 				} else
  1296 				{
  1297 					// Move ordinary branch
  1298 					if (lmosel->getOrientation() == LinkableMapObj::LeftOfCenter)
  1299 						// Add width of bbox here, otherwise alignRelTo will cause jumping around
  1300 						lmosel->move(p.x() -movingObj_start.x() , //lmosel->getBBox().width(), 
  1301 							p.y()-movingObj_start.y() +lmosel->getTopPad() );		
  1302 					else	
  1303 						lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() -lmosel->getTopPad());
  1304 					lmosel->setRelPos();	
  1305 				} 
  1306 
  1307 			} // depth>0
  1308 				// Maybe we can relink temporary?
  1309 				if (dsti)
  1310 				{
  1311 					if (e->modifiers()==Qt::ControlModifier)
  1312 					{
  1313 						// Special case: CTRL to link below dst
  1314 						lmosel->setParObjTmp (dst,p,+1);
  1315 					} else if (e->modifiers()==Qt::ShiftModifier)
  1316 						lmosel->setParObjTmp (dst,p,-1);
  1317 					else
  1318 						lmosel->setParObjTmp (dst,p,0);
  1319 				} else	
  1320 				{
  1321 					lmosel->unsetParObjTmp();
  1322 				}		
  1323 				// reposition subbranch
  1324 				lmosel->reposition();	
  1325 
  1326 			QItemSelection sel=model->getSelectionModel()->selection();
  1327 			updateSelection(sel,sel);	// position has changed
  1328 
  1329 		} // no FloatImageObj
  1330 
  1331 		scene()->update();
  1332 		return;
  1333 	} // selection && moving_obj
  1334 		
  1335 	// Draw a link from one branch to another
  1336 	if (drawingLink)
  1337 	{
  1338 		 tmpXLink->setEnd (p);
  1339 		 tmpXLink->updateXLink();
  1340 	}	 
  1341 	
  1342     // Move sceneView 
  1343     if (!movingObj && !pickingColor &&!drawingLink && e->buttons() == Qt::LeftButton ) 
  1344 	{
  1345 		QPointF p=e->globalPos();
  1346 		movingVec.setX(-p.x() + movingObj_start.x() );
  1347 		movingVec.setY(-p.y() + movingObj_start.y() );
  1348 		horizontalScrollBar()->setSliderPosition((int)( movingCont_start.x()+movingVec.x() ));
  1349 		verticalScrollBar()->setSliderPosition((int)( movingCont_start.y()+movingVec.y() ) );
  1350     }
  1351 }
  1352 
  1353 
  1354 void MapEditor::mouseReleaseEvent(QMouseEvent* e)
  1355 {
  1356     QPointF p = mapToScene(e->pos());
  1357 	TreeItem *seli=model->getSelectedItem();
  1358 
  1359 	TreeItem *dsti=NULL;
  1360 	if (seli) dsti=findMapItem(p, seli);
  1361 	LinkableMapObj* dst=NULL;
  1362 	if (dsti && dsti->isBranchLikeType ()) 
  1363 		dst=((MapItem*)dsti)->getLMO();	
  1364 	else
  1365 		dsti=NULL;
  1366 
  1367 
  1368 	// Have we been picking color?
  1369 	if (pickingColor)
  1370 	{
  1371 		pickingColor=false;
  1372 		setCursor (Qt::ArrowCursor);
  1373 		// Check if we are over another branch
  1374 		if (dst) 
  1375 		{	
  1376 			if (e->state() & Qt::ShiftModifier)
  1377 				model->colorBranch (((BranchObj*)dst)->getColor());
  1378 			else	
  1379 				model->colorSubtree (((BranchObj*)dst)->getColor());
  1380 		} 
  1381 		return;
  1382 	}
  1383 
  1384 	// Have we been drawing a link?
  1385 	if (drawingLink)	
  1386 	{
  1387 		drawingLink=false;
  1388 		// Check if we are over another branch
  1389 		if (dsti)
  1390 		{	
  1391 			tmpXLink->setEnd ( ((BranchItem*)dsti) );
  1392 			tmpXLink->updateXLink();
  1393 			tmpXLink->activate(); 
  1394 			model->saveState(
  1395 				tmpXLink,QString("delete ()"),
  1396 				dsti,QString("addXLink (\"%1\",\"%2\")").arg(model->getSelectString(tmpXLink->getBegin())).arg(model->getSelectString(dsti)),
  1397 				QString("Add xLink from %1 to %2").arg(model->getObjectName(tmpXLink->getBegin())).arg(model->getObjectName(dsti)) 
  1398 			);	
  1399 		} else
  1400 		{
  1401 			model->deleteItem(tmpXLink);
  1402 			tmpXLink=NULL;
  1403 		}
  1404 		return;
  1405 	}
  1406 	
  1407     // Have we been moving something?
  1408     if ( seli && movingObj ) 
  1409     {	
  1410 		if (seli->getType()==TreeItem::Image)
  1411 		{
  1412 			FloatImageObj *fio=(FloatImageObj*)( ((MapItem*)seli)->getLMO());
  1413 			if(fio)
  1414 			{
  1415 				// Moved FloatObj. Maybe we need to reposition
  1416 				QString pold=qpointFToString(movingObj_orgRelPos);
  1417 				QString pnow=qpointFToString(fio->getRelPos());
  1418 				model->saveState(
  1419 					seli,
  1420 					"moveRel "+pold,
  1421 					seli,
  1422 					"moveRel "+pnow,
  1423 					QString("Move %1 to relative position %2").arg(model->getObjectName(seli)).arg(pnow));
  1424 
  1425 				fio->getParObj()->requestReposition();
  1426 				model->reposition();
  1427 			}	
  1428 		}
  1429 
  1430 		BranchItem *bi=model->getSelectedBranch();
  1431 		if (bi && bi->depth()==0)
  1432 		{	
  1433             if (movingObj_orgPos != bi->getBranchObj()->getAbsPos())	// FIXME-3 check getBO here...
  1434             {
  1435                 QString pold=qpointFToString(movingObj_orgPos);
  1436                 QString pnow=qpointFToString(bi->getBranchObj()->getAbsPos());		// FIXME-3 check getBO here...
  1437 
  1438                 model->saveState(
  1439                     bi,
  1440                     "move "+pold,
  1441                     bi,
  1442                     "move "+pnow,
  1443                     QString("Move mapcenter %1 to position %2").arg(model->getObjectName(bi)).arg(pnow));
  1444             }
  1445 		}
  1446 	
  1447 		if (seli->isBranchLikeType() ) //(seli->getType() == TreeItem::Branch )
  1448 		{	// A branch was moved
  1449 			LinkableMapObj* lmosel=NULL;		
  1450 			lmosel=((MapItem*)seli)->getLMO();
  1451 				
  1452 			// save the position in case we link to mapcenter
  1453 			QPointF savePos=QPointF (lmosel->getAbsPos()  );
  1454 
  1455 			// Reset the temporary drawn link to the original one
  1456 			lmosel->unsetParObjTmp();
  1457 
  1458 			// For Redo we may need to save original selection
  1459 			QString preSelStr=model->getSelectString(seli);
  1460 
  1461 			copyingObj=false;	
  1462 			if (dsti && objectMoved)
  1463 			{
  1464 				// We have a destination, relink to that
  1465 
  1466 				BranchObj* bsel=model->getSelectedBranchObj();
  1467 
  1468 				QString preParStr=model->getSelectString (bsel->getParObj());
  1469 				QString preNum=QString::number (seli->num(),10);
  1470 				QString preDstParStr;
  1471 				bool relinked;
  1472 
  1473 				if (e->state() & Qt::ShiftModifier && dst->getParObj())
  1474 				{	// Link above dst
  1475 					preDstParStr=model->getSelectString (dst->getParObj());
  1476 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti->parent(),((BranchItem*)dsti)->num());
  1477 				} else 
  1478 				if (e->state() & Qt::ControlModifier && dst->getParObj())
  1479 				{
  1480 					// Link below dst
  1481 					preDstParStr=model->getSelectString (dst->getParObj());
  1482 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti->parent(),((BranchItem*)dsti)->num()+1);
  1483 				} else	
  1484 				{	// Append to dst
  1485 					preDstParStr=model->getSelectString(dst);
  1486 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti);
  1487 					if (dsti->depth()==0) bsel->move (savePos);
  1488 				} 
  1489 				if (relinked)
  1490 				{
  1491 					QString postSelStr=model->getSelectString(lmosel);
  1492 					QString postNum=QString::number (seli->num(),10);
  1493 
  1494 					QString undoCom="relinkTo (\""+ 
  1495 						preParStr+ "\"," + preNum  +"," + 
  1496 						QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+ ")";
  1497 
  1498 					QString redoCom="relinkTo (\""+ 
  1499 						preDstParStr + "\"," + postNum + "," +
  1500 						QString ("%1,%2").arg(savePos.x()).arg(savePos.y())+ ")";
  1501 
  1502 					model->saveState (
  1503 						postSelStr,undoCom,
  1504 						preSelStr, redoCom,
  1505 						QString("Relink %1 to %2").arg(model->getObjectName(bsel)).arg(model->getObjectName(dst)) );
  1506 
  1507 				}
  1508 			} else
  1509 			{
  1510 				// No destination, undo  temporary move	
  1511 
  1512 				if (seli->depth()==1)
  1513 				{
  1514 					// The select string might be different _after_ moving around.
  1515 					// Therefor reposition and then use string of old selection, too
  1516 					model->reposition();
  1517 
  1518                     QPointF rp(lmosel->getRelPos());
  1519                     if (rp != movingObj_orgRelPos)
  1520                     {
  1521                         QString ps=qpointFToString(rp);
  1522                         model->saveState(
  1523                             model->getSelectString(lmosel), "moveRel "+qpointFToString(movingObj_orgRelPos), 
  1524                             preSelStr, "moveRel "+ps, 
  1525                             QString("Move %1 to relative position %2").arg(model->getObjectName(lmosel)).arg(ps));
  1526                     }
  1527 				}
  1528 
  1529 				// Draw the original link, before selection was moved around
  1530 				if (settings.value("/animation/use",true).toBool() && seli->depth()>1) 
  1531 				{
  1532 					lmosel->setRelPos();	// calc relPos first for starting point
  1533 					
  1534 					model->startAnimation(
  1535 						(BranchObj*)lmosel,
  1536 						lmosel->getRelPos(),
  1537 						movingObj_orgRelPos
  1538 					);	
  1539 				} else	
  1540 					model->reposition();
  1541 			}
  1542 		}
  1543 		model->emitSelectionChanged();  //FIXME-3 needed? at least not after pos of selection has changed...
  1544 		// Finally resize scene, if needed
  1545 		scene()->update();
  1546 		movingObj=NULL;		
  1547 		objectMoved=false;
  1548 
  1549 	} else 
  1550 		// maybe we moved View: set old cursor
  1551 		setCursor (Qt::ArrowCursor);
  1552     
  1553 }
  1554 
  1555 void MapEditor::mouseDoubleClickEvent(QMouseEvent* e)
  1556 {
  1557 	if (debug) 
  1558 	{
  1559 		cout << "ME p="<<mapToScene (e->pos())<<"  scrollBarPos="<<getScrollBarPos();
  1560 		cout << "  min="<<QPointF(horizontalScrollBar()->minimum(),verticalScrollBar()->minimum());
  1561 		cout << endl;
  1562 	}
  1563 
  1564 
  1565 	if (model->isSelectionBlocked() ) 
  1566 	{
  1567 		e->ignore();
  1568 		return;
  1569 	}
  1570 
  1571 	if (e->button() == Qt::LeftButton )
  1572 	{
  1573 		QPointF p = mapToScene(e->pos());
  1574 		TreeItem *ti=findMapItem (p, NULL);
  1575 		if (ti) {	// MapObj was found
  1576 			// First select the MapObj than edit heading
  1577 			model->select (ti);
  1578 			editHeading();
  1579 		}
  1580 	}
  1581 }
  1582 
  1583 void MapEditor::resizeEvent (QResizeEvent* e)
  1584 {
  1585 	QGraphicsView::resizeEvent( e );
  1586 }
  1587 
  1588 void MapEditor::dragEnterEvent(QDragEnterEvent *event)
  1589 {
  1590 	//for (unsigned int i=0;event->format(i);i++) // Debug mime type
  1591 	//	cerr << event->format(i) << endl;
  1592 
  1593 	if (event->mimeData()->hasImage())
  1594 		event->acceptProposedAction();
  1595 	else	
  1596 		if (event->mimeData()->hasUrls())
  1597 			event->acceptProposedAction();
  1598 }
  1599 
  1600 void MapEditor::dragMoveEvent(QDragMoveEvent *)
  1601 {
  1602 }
  1603 
  1604 void MapEditor::dragLeaveEvent(QDragLeaveEvent *event)
  1605 {
  1606 	event->accept();
  1607 }
  1608 
  1609 void MapEditor::dropEvent(QDropEvent *event)
  1610 {
  1611 	BranchItem *selbi=model->getSelectedBranch();
  1612 	if (selbi)
  1613 	{
  1614 		if (debug)
  1615 		{
  1616 			foreach (QString format,event->mimeData()->formats()) 
  1617 				cout << "MapEditor: Dropped format: "<<qPrintable (format)<<endl;
  1618 			foreach (QString url,event->mimeData()->urls())
  1619 				cout << "  URL:"<<url.toStdString()<<endl;
  1620 			//foreach (QString plain,event->mimeData()->text())
  1621 			//	cout << "   PLAIN:"<<plain.toStdString()<<endl;
  1622 			QByteArray ba=event->mimeData()->data("STRING");
  1623 			
  1624 			QString s;
  1625 			s=ba;
  1626 			cout << "  STRING:" <<s.toStdString()<<endl;
  1627 
  1628 			ba=event->mimeData()->data("TEXT");
  1629 			s=ba;
  1630 			cout << "    TEXT:" <<s.toStdString()<<endl;
  1631 
  1632 			ba=event->mimeData()->data("COMPOUND_TEXT");
  1633 			s=ba;
  1634 			cout << "   CTEXT:" <<s.toStdString()<<endl;
  1635 
  1636 			ba=event->mimeData()->data("text/x-moz-url");
  1637 			s=ba;
  1638 			cout << "   x-moz-url:" <<s.toStdString()<<endl;
  1639 			foreach (char b,ba)
  1640 				if (b!=0) cout << "b="<<b<<endl;
  1641 		}
  1642 
  1643 		if (event->mimeData()->hasImage()) 
  1644 		{
  1645 			 QVariant imageData = event->mimeData()->imageData();
  1646 			 model->addFloatImage (qvariant_cast<QPixmap>(imageData));
  1647 		} else
  1648 		if (event->mimeData()->hasUrls())
  1649 		{
  1650 			//model->selectLastBranch();
  1651 			QList <QUrl> uris=event->mimeData()->urls();
  1652 			QStringList files;
  1653 			QString s;
  1654 			QString heading;
  1655 			BranchItem *bi;
  1656 			for (int i=0; i<uris.count();i++)
  1657 			{
  1658 				// Workaround to avoid adding empty branches
  1659 				if (!uris.at(i).toString().isEmpty())
  1660 				{
  1661 					bi=model->addNewBranch();
  1662 					if (bi)
  1663 					{
  1664 						model->select(bi);
  1665 						QString u=uris.at(i).toString();
  1666 						s=uris.at(i).toLocalFile();
  1667 						if (!s.isEmpty()) 
  1668 						{
  1669 						   QString file = QDir::fromNativeSeparators(s);
  1670 						   heading = QFileInfo(file).baseName();
  1671 						   files.append(file);
  1672 						   if (file.endsWith(".vym", false))
  1673 							   model->setVymLink(file);
  1674 						   else
  1675 							   model->setURL(u);
  1676 					   } else 
  1677 					   {
  1678 							model->setURL(u);
  1679 
  1680 /*
  1681 							// Automatically try to fetch data from Bugzilla
  1682 							if (settings.value( "/mainwindow/showTestMenu",false).toBool() 
  1683 								&& u.contains ("https://bugzilla.novell.com"))
  1684 								model->getBugzillaData();
  1685 */								
  1686 					   }
  1687 
  1688 					   if (!heading.isEmpty())
  1689 						   model->setHeading(heading);
  1690 					   else
  1691 						   model->setHeading(u);
  1692 						   
  1693 						model->select (bi->parent());	   
  1694 					}
  1695 				}
  1696 			}
  1697 			//model->reposition();
  1698 		}
  1699 	}	
  1700 	event->acceptProposedAction();
  1701 }
  1702 
  1703 void MapEditor::updateSelection(QItemSelection newsel,QItemSelection oldsel)
  1704 {
  1705 	// Note: Here we are prepared for multiple selections, though this 
  1706 	// is not yet implemented elsewhere
  1707 
  1708 	// Here in MapEditor we can only select Branches and Images
  1709 	QList <TreeItem*> treeItemsNew;
  1710 	QList <TreeItem*> treeItemsOld;
  1711 
  1712 	QModelIndex newIndex;
  1713 
  1714 	bool do_reposition=false;
  1715 
  1716 	QModelIndex ix;
  1717 	foreach (ix,newsel.indexes() )
  1718 	{
  1719 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1720 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1721 			if (!treeItemsNew.contains(ti)) treeItemsNew.append (ti);
  1722 	}
  1723 	foreach (ix,oldsel.indexes() )
  1724 	{
  1725 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1726 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1727 			if (!treeItemsOld.contains(ti)) treeItemsOld.append (ti);
  1728 	}
  1729 
  1730 	// Trim list of selection rectangles 
  1731 	while (treeItemsNew.count() < selboxList.count() )
  1732 		delete selboxList.takeFirst();
  1733 
  1734 	// Take care to tmp scroll/unscroll
  1735 	if (!oldsel.isEmpty())
  1736 	{
  1737 		QModelIndex ix=oldsel.indexes().first(); 
  1738 		if (ix.isValid() )
  1739 		{
  1740 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1741 			if (ti)
  1742 			{
  1743 				if (ti->isBranchLikeType() )
  1744 				{
  1745 					// reset tmp scrolled branches
  1746 					BranchItem *bi=(BranchItem*)ti;
  1747 					if (bi->resetTmpUnscroll() )
  1748 						do_reposition=true;
  1749 				}
  1750 				if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1751 					// Hide link if not needed
  1752 					((MapItem*)ti)->getLMO()->updateVisibility();
  1753 			}
  1754 		}
  1755 	}
  1756 
  1757 	if (!treeItemsNew.isEmpty())
  1758 	{
  1759 		QModelIndex ix=newsel.indexes().first(); 
  1760 		if (ix.isValid() )
  1761 		{
  1762 			newIndex=ix;
  1763 
  1764 			// Temporary unscroll if necessary
  1765 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1766 			if (ti->isBranchLikeType() )
  1767 			{
  1768 				BranchItem *bi=(BranchItem*)ti;
  1769 				if (bi->hasScrolledParent(bi) )
  1770 				{
  1771 					if (bi->parentBranch()->tmpUnscroll() )
  1772 						do_reposition=true;
  1773 				}	
  1774 			}
  1775 			if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1776 				// Show link if needed
  1777 				((MapItem*)ti)->getLMO()->updateVisibility();
  1778 		}
  1779 	}
  1780 	if (do_reposition) model->reposition();
  1781 
  1782 	// Reduce rectangles
  1783 	while (treeItemsNew.count() < selboxList.count() )
  1784 		delete selboxList.takeFirst();
  1785 
  1786 	// Add additonal rectangles
  1787 	QGraphicsRectItem *sb;
  1788 	while (treeItemsNew.count() > selboxList.count() )
  1789 	{
  1790 		sb = mapScene->addRect(
  1791 			QRectF(0,0,0,0), 
  1792 			QPen(selectionColor),
  1793 			selectionColor);
  1794 		sb->setZValue(Z_SELBOX);
  1795 		sb->show();
  1796 		selboxList.append (sb);
  1797 	}
  1798 
  1799 	// Reposition rectangles
  1800 	QRectF bbox;
  1801 	QModelIndex index;
  1802 
  1803 	LinkableMapObj *lmo;
  1804 	for (int i=0; i<treeItemsNew.count();++i)
  1805 	{
  1806 		lmo=((MapItem*)treeItemsNew.at(i) )->getLMO();
  1807 		bbox=lmo->getBBox();
  1808 		sb=selboxList.at(i);
  1809 		sb->setRect (
  1810 			bbox.x(),bbox.y(), 
  1811 			bbox.width(), bbox.height());
  1812 		sb->setPen (selectionColor);	
  1813 		sb->setBrush (selectionColor);	
  1814 		i++;
  1815 	}
  1816 
  1817 	scene()->update();  
  1818 }
  1819 
  1820 void MapEditor::updateData (const QModelIndex &sel)
  1821 {
  1822 	TreeItem *ti= static_cast<TreeItem*>(sel.internalPointer());
  1823 
  1824 /* testing
  1825 	cout << "ME::updateData\n";
  1826 
  1827 	cout << "  ti="<<ti<<endl;
  1828 	cout << "  h="<<ti->getHeading().toStdString()<<endl;
  1829 	*/
  1830 	
  1831 	if (ti->isBranchLikeType())
  1832 	{
  1833 	//	cout << "  ->updating...\n";
  1834 		BranchObj *bo=(BranchObj*) ( ((MapItem*)ti)->getLMO());
  1835 		bo->updateData();
  1836 	}
  1837 }
  1838 
  1839 void MapEditor::setSelectionColor (QColor col)
  1840 {
  1841 	selectionColor=col;
  1842 	QItemSelection sel=model->getSelectionModel()->selection();
  1843 	updateSelection(sel,sel);
  1844 }
  1845 
  1846 
  1847 QColor MapEditor::getSelectionColor ()
  1848 {
  1849 	return selectionColor;
  1850 }
  1851 
  1852