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