mapeditor.cpp
author insilmaril
Mon, 22 Mar 2010 15:37:23 +0000
changeset 841 46553c106c52
parent 837 5ecd0462f76b
child 842 bec082472471
permissions -rw-r--r--
Fixes for QLineEdit and moving vym.changelog up one level
     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()==QAbstractAnimation::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 ( QEasingCurve::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()==QAbstractAnimation::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 ( QEasingCurve::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 #include <iostream>
   465 void MapEditor::autoLayout()
   466 {
   467 	// Create list with all bounding polygons
   468 	QList <LinkableMapObj*> mapobjects;
   469 	QList <ConvexPolygon> polys; 
   470 	ConvexPolygon p;
   471 	QList <Vector> vectors;
   472 	QList <Vector> orgpos;
   473 	QStringList headings;	//FIXME-3 testing only
   474 	Vector v;
   475 	BranchItem *bi;
   476 	BranchItem *bi2;
   477 	BranchObj *bo;
   478 
   479 	// Outer loop: Iterate until we no more changes in orientation 
   480 	bool orientationChanged=true;
   481 	while (orientationChanged)
   482 	{
   483 		BranchItem *ri=model->getRootItem();
   484 		for (int i=0;i<ri->branchCount();++i)
   485 		{
   486 			bi=ri->getBranchNum (i);
   487 			bo=(BranchObj*)bi->getLMO();
   488 			if (bo)
   489 			{
   490 				mapobjects.append (bo);
   491 				p=bo->getBoundingPolygon();
   492 				p.calcCentroid();
   493 				polys.append(p);
   494 				vectors.append (QPointF(0,0));
   495 				orgpos.append (p.at(0));
   496 				headings.append (bi->getHeading());
   497 			}
   498 			for (int j=0;j<bi->branchCount();++j)
   499 			{
   500 				bi2=bi->getBranchNum (j);
   501 				bo=(BranchObj*)bi2->getLMO();
   502 				if (bo)
   503 				{
   504 					mapobjects.append (bo);
   505 					p=bo->getBoundingPolygon();
   506 					p.calcCentroid();
   507 					polys.append(p);
   508 					vectors.append (QPointF(0,0));
   509 					orgpos.append (p.at(0));
   510 					headings.append (bi2->getHeading());
   511 				}	
   512 			}
   513 		}
   514 
   515 		// Iterate moving bounding polygons until we have no more collisions
   516 		int collisions=1;
   517 		while (collisions>0)
   518 		{
   519 			collisions=0;
   520 			for (int i=0; i<polys.size()-1; ++i)
   521 			{
   522 				for (int j=i+1; j<polys.size();++j)
   523 				{
   524 					if (polygonCollision (polys.at(i),polys.at(j), QPointF(0,0)).intersect )
   525 					{
   526 						collisions++;
   527 						if (debug) qDebug() << "Collision: "<<headings[i]<<" - "<<headings[j];
   528 						v=polys.at(j).centroid()-polys.at(i).centroid();
   529 						// Move also away if centroids are identical
   530 						if (v.isNull()) 
   531 						{
   532 							v.setX (rand()%200 -100);
   533 							v.setY (rand()%200 -100);
   534 						}
   535 						// Add random direction
   536 						Vector w (cos (rand()%1000),sin(rand()%1000));
   537 						
   538 						// Scale translation vector by area of polygons
   539 						v.normalize();
   540 						vectors[j]=v*10000/polys.at(j).weight();		
   541 						vectors[i]=v*10000/polys.at(i).weight();		
   542 						vectors[i].invert();
   543 						//FIXME-3 outer loop, "i" get's changed several times...
   544 						// Better not move away from centroid of 2 colliding polys, 
   545 						// but from centroid of _all_
   546 					}  
   547 				}
   548 			}
   549 			for (int i=0;i<vectors.size();i++)
   550 			{
   551 				//qDebug() << " v="<<vectors[i]<<" "<<headings[i];
   552 				if (!vectors[i].isNull() )
   553 				polys[i].translate (vectors[i]);
   554 			}
   555 			if (debug) qDebug()<< "Collisions total: "<<collisions;
   556 			//collisions=0;
   557 		}	
   558 
   559 		// Finally move the real objects and update 
   560 		QList <LinkableMapObj::Orientation> orients;
   561 		for (int i=0;i<polys.size();i++)
   562 		{
   563 			Vector v=polys[i].at(0)-orgpos[i];
   564 			orients.append (mapobjects[i]->getOrientation());
   565 			if (!v.isNull())
   566 			{
   567 				if (debug) cout<<" Moving "<<polys.at(i).weight()<<" "<<mapobjects[i]->getAbsPos()<<" -> "<<mapobjects[i]->getAbsPos() + v<<"  "<<headings[i].toStdString()<<endl;
   568 				//mapobjects[i]->moveBy(v.x(),v.y() );
   569 				//mapobjects[i]->setRelPos();
   570 				model->startAnimation ((BranchObj*)mapobjects[i], v);
   571 				if (debug) cout<<i<< " Weight: "<<polys.at(i).weight()<<" "<<v<<" "<<headings.at(i).toStdString()<<endl;
   572 			}
   573 		}	
   574 		/*
   575 		model->reposition();	
   576 		orientationChanged=false;
   577 		for (int i=0;i<polys.size();i++)
   578 			if (orients[i]!=mapobjects[i]->getOrientation())
   579 			{
   580 				orientationChanged=true;
   581 				break;
   582 			}
   583 		*/
   584 	
   585 		break;
   586 
   587 		//orientationChanged=false;
   588 	} // loop if orientation has changed
   589 
   590 	model->emitSelectionChanged();
   591 }
   592 
   593 TreeItem* MapEditor::findMapItem (QPointF p,TreeItem *exclude)
   594 {
   595 	// Start with mapcenter, no images allowed at rootItem
   596 	int i=0;
   597 	BranchItem *bi=model->getRootItem()->getFirstBranch();
   598 	TreeItem *found=NULL;
   599 	while (bi)
   600 	{
   601 		found=bi->findMapItem (p, exclude);
   602 		if (found) return found;
   603 		i++;
   604 		bi=model->getRootItem()->getBranchNum(i);
   605 	}
   606 	return NULL;
   607 }
   608 
   609 AttributeTable* MapEditor::attributeTable()
   610 {
   611 	return attrTable;
   612 }
   613 
   614 void MapEditor::testFunction1()
   615 {
   616 /*
   617 	qDebug()<< "ME::test1  selected TI="<<model->getSelectedItem();
   618 	model->setExportMode (true);
   619 */
   620 	QLineEdit *le3=new QLineEdit;
   621 	mapScene->addWidget (le3);
   622 	le3->setGeometry (10,10,100,30);
   623 	le3->setText("LineEdit 3");
   624 
   625 	QLineEdit *le4=new QLineEdit;
   626 	mapScene->addWidget (le4);
   627 	le4->setGeometry (10,50,100,30);
   628 	le4->setText("LineEdit 4");
   629 	//le4->setFocus();
   630 
   631 
   632 
   633 	/*
   634 	// Code copied from Qt sources
   635 	QRectF rect=model->getSelectedBranchObj()->getBBox();
   636 	int xmargin=50;
   637 	int ymargin=50;
   638 
   639     qreal width = viewport()->width();
   640     qreal height = viewport()->height();
   641     QRectF viewRect = matrix().mapRect(rect);
   642 
   643     qreal left = horizontalScrollBar()->value();
   644     qreal right = left + width;
   645     qreal top = verticalScrollBar()->value();
   646     qreal bottom = top + height;
   647 
   648     if (viewRect.left() <= left + xmargin) {
   649         // need to scroll from the left
   650   //      if (!d->leftIndent)
   651             horizontalScrollBar()->setValue(int(viewRect.left() - xmargin - 0.5));
   652     }
   653     if (viewRect.right() >= right - xmargin) {
   654         // need to scroll from the right
   655 //        if (!d->leftIndent)
   656             horizontalScrollBar()->setValue(int(viewRect.right() - width + xmargin + 0.5));
   657     }
   658     if (viewRect.top() <= top + ymargin) {
   659         // need to scroll from the top
   660    //     if (!d->topIndent)
   661             verticalScrollBar()->setValue(int(viewRect.top() - ymargin - 0.5));
   662     }
   663     if (viewRect.bottom() >= bottom - ymargin) {
   664         // need to scroll from the bottom
   665 //        if (!d->topIndent)
   666             verticalScrollBar()->setValue(int(viewRect.bottom() - height + ymargin + 0.5));
   667     }
   668 	qDebug() << "test1:  hor="<<horizontalScrollBar()->value();
   669 	qDebug() << "test1:  ver="<<verticalScrollBar()->value();
   670 }
   671 
   672 */
   673 /*
   674 	 QtPropertyAnimation *animation=new QtPropertyAnimation(this, "sceneRect");
   675 	 animation->setDuration(5000);
   676 	 //animation->setEasingCurve ( QtEasingCurve::OutElastic);
   677 	 animation->setEasingCurve ( QtEasingCurve::OutQuint);
   678 	 animation->setStartValue(sceneRect() );
   679 	 animation->setEndValue(QRectF(50, 50, 1000, 1000));
   680 
   681 	 animation->start();
   682 */	 
   683 /*
   684 	QDialog *dia= new QDialog (this);
   685 	dia->setGeometry (50,50,10,10);
   686 
   687      dia->show();
   688      dia ->raise();
   689 
   690 	 QtPropertyAnimation *animation=new QtPropertyAnimation(dia, "geometry");
   691 	 animation->setDuration(1000);
   692 	 //animation->setEasingCurve ( QtEasingCurve::OutElastic);
   693 	 animation->setEasingCurve ( QtEasingCurve::OutQuint);
   694 	 animation->setStartValue(QRect(50, 50, 10, 10));
   695 	 animation->setEndValue(QRect(250, 250, 100, 100));
   696 
   697 	 animation->start();
   698  */
   699 
   700 }
   701 	
   702 void MapEditor::testFunction2()
   703 {
   704 	autoLayout();
   705 }
   706 
   707 BranchItem* MapEditor::getBranchDirectAbove (BranchItem *bi)
   708 {
   709 	if (bi)
   710 	{
   711 		int i=bi->num();
   712 		if (i>0) return bi->parent()->getBranchNum(i-1);
   713 	}
   714 	return NULL;
   715 }
   716 
   717 BranchItem* MapEditor::getBranchAbove (BranchItem *selbi)
   718 {
   719 	if (selbi)
   720 	{
   721 		int dz=selbi->depth();	// original depth
   722 		bool invert=false;
   723 		if (selbi->getLMO()->getOrientation()==LinkableMapObj::LeftOfCenter)
   724 			invert=true;
   725 
   726 		BranchItem *bi;
   727 
   728 		// Look for branch with same parent but directly above
   729 		if (dz==1 && invert)
   730 			bi=getBranchDirectBelow(selbi);
   731 		else
   732 			bi=getBranchDirectAbove (selbi);
   733 
   734 		if (bi) 
   735 			// direct predecessor
   736 			return bi;
   737 
   738 		// Go towards center and look for predecessor
   739 		while (selbi->depth()>0)
   740 		{
   741 			selbi=(BranchItem*)(selbi->parent());
   742 			if (selbi->depth()==1 && invert)
   743 				bi=getBranchDirectBelow (selbi);
   744 			else
   745 				bi=getBranchDirectAbove (selbi);
   746 			if (bi)
   747 			{
   748 				// turn 
   749 				selbi=bi;
   750 				while (selbi->depth()<dz)
   751 				{
   752 					// try to get back to original depth dz
   753 					bi=selbi->getLastBranch();
   754 					if (!bi) 
   755 					{
   756 						return selbi;
   757 					}
   758 					selbi=bi;
   759 				}
   760 				return selbi;
   761 			}
   762 		}
   763 	}
   764 	return NULL;
   765 }
   766 
   767 BranchItem* MapEditor::getBranchDirectBelow(BranchItem *bi)
   768 {
   769 	if (bi)
   770 	{
   771 		int i=bi->num();
   772 		if (i+1<bi->parent()->branchCount()) return bi->parent()->getBranchNum(i+1);
   773 	}
   774 	return NULL;
   775 }
   776 
   777 BranchItem* MapEditor::getBranchBelow (BranchItem *selbi)
   778 {
   779 	if (selbi)
   780 	{
   781 		BranchItem *bi;
   782 		int dz=selbi->depth();	// original depth
   783 		bool invert=false;
   784 		if (selbi->getLMO()->getOrientation()==LinkableMapObj::LeftOfCenter)
   785 			invert=true;
   786 
   787 
   788 		// Look for branch with same parent but directly below
   789 		if (dz==1 && invert)
   790 			bi=getBranchDirectAbove (selbi);
   791 		else
   792 			bi=getBranchDirectBelow (selbi);
   793 		if (bi) 
   794 			// direct successor
   795 			return bi;
   796 
   797 
   798 		// Go towards center and look for neighbour
   799 		while (selbi->depth()>0)
   800 		{
   801 			selbi=(BranchItem*)(selbi->parent());
   802 			if (selbi->depth()==1 && invert)
   803 				bi=getBranchDirectAbove (selbi);
   804 			else
   805 				bi=getBranchDirectBelow (selbi);
   806 			if (bi)
   807 			{
   808 				// turn 
   809 				selbi=bi;
   810 				while (selbi->depth()<dz)
   811 				{
   812 					// try to get back to original depth dz
   813 					bi=selbi->getFirstBranch();
   814 					if (!bi) 
   815 					{
   816 						return selbi;
   817 					}
   818 					selbi=bi;
   819 				}
   820 				return selbi;
   821 			}
   822 		}
   823 	}
   824 	return NULL;
   825 }
   826 
   827 BranchItem* MapEditor::getLeftBranch (BranchItem *bi)
   828 {
   829 	if (bi)
   830 	{
   831 		if (bi->depth()==0)
   832 			// Special case: use alternative selection index
   833 			return bi->getLastSelectedBranchAlt();	
   834 		if (bi->getBranchObj()->getOrientation()==LinkableMapObj::RightOfCenter)	
   835 			// right of center
   836 			return (BranchItem*)(bi->parent());
   837 		else
   838 			// left of center
   839 			if (bi->getType()== TreeItem::Branch )
   840 				return bi->getLastSelectedBranch();
   841 	}
   842 	return NULL;
   843 }
   844 
   845 BranchItem* MapEditor::getRightBranch(BranchItem *bi)
   846 {
   847 	if (bi)
   848 	{
   849 		if (bi->depth()==0) return bi->getLastSelectedBranch();	
   850 		if (bi->getBranchObj()->getOrientation()==LinkableMapObj::LeftOfCenter)	
   851 			// left of center
   852 			return (BranchItem*)(bi->parent());
   853 		else
   854 			// right of center
   855 			if (bi->getType()== TreeItem::Branch )
   856 				return (BranchItem*)bi->getLastSelectedBranch();
   857 	}
   858 	return NULL;
   859 }
   860 
   861 
   862 
   863 void MapEditor::cursorUp()
   864 {
   865 	BranchItem *bi=model->getSelectedBranch();
   866 	if (bi) model->select (getBranchAbove(bi));
   867 }
   868 
   869 void MapEditor::cursorDown()	
   870 
   871 {
   872 	BranchItem *bi=model->getSelectedBranch();
   873 	if (bi) model->select (getBranchBelow(bi));
   874 }
   875 
   876 void MapEditor::cursorLeft()
   877 {
   878 	BranchItem *bi=getLeftBranch (model->getSelectedBranch());
   879 	if (bi) model->select (bi);
   880 }
   881 
   882 void MapEditor::cursorRight()	
   883 {
   884 	BranchItem *bi=getRightBranch (model->getSelectedBranch());
   885 	if (bi) model->select (bi);
   886 }
   887 
   888 void MapEditor::cursorFirst()	
   889 {
   890 	model->selectFirstBranch();
   891 }
   892 
   893 void MapEditor::cursorLast()	
   894 {
   895 	model->selectLastBranch();
   896 }
   897 
   898 
   899 void MapEditor::editHeading()
   900 {
   901 	if (editingHeading)
   902 	{
   903 		editHeadingFinished();
   904 		return;
   905 	}
   906 	BranchObj *bo=model->getSelectedBranchObj();
   907 	BranchItem *bi=model->getSelectedBranch();
   908 	if (bo)	
   909 	{
   910 		model->setSelectionBlocked(true);
   911 
   912 		lineEdit=new QLineEdit;
   913 		QGraphicsProxyWidget *pw=mapScene->addWidget (lineEdit);
   914 		pw->setZValue (Z_LINEEDIT);
   915 		lineEdit->setCursor(Qt::IBeamCursor);
   916 		lineEdit->setCursorPosition(1);
   917 		QPoint p = mapTo (this,bo->getAbsPos().toPoint() );
   918 		lineEdit->setGeometry(p.x(),p.y(),230,25);
   919 		lineEdit->setText (bi->getHeading());
   920 		lineEdit->setFocus();
   921 		lineEdit->selectAll();	// Hack to enable cursor in lineEdit
   922 		lineEdit->deselect();	// probably a Qt bug...
   923 		//lineEdit->grabKeyboard();
   924 		editingHeading=true;
   925 	}
   926 
   927 }
   928 void MapEditor::editHeadingFinished()
   929 {
   930 	editingHeading=false;
   931 	//lineEdit->releaseKeyboard();
   932 	//lineEdit->clearFocus();
   933 	QString s=lineEdit->text();
   934 	s.replace (QRegExp ("\\n")," ");	// Don't paste newline chars
   935 	model->setHeading (s);
   936 	model->setSelectionBlocked(false);
   937 	delete (lineEdit);
   938 
   939 	// Maybe reselect previous branch 
   940 	mainWindow->editHeadingFinished (model);
   941 }
   942 
   943 
   944 void MapEditor::contextMenuEvent ( QContextMenuEvent * e )
   945 {
   946 	// Lineedits are already closed by preceding
   947 	// mouseEvent, we don't need to close here.
   948 
   949     QPointF p = mapToScene(e->pos());
   950     TreeItem *ti=findMapItem (p, NULL);
   951     LinkableMapObj* lmo=NULL;
   952 	if (ti) lmo=((MapItem*)ti)->getLMO();
   953 	
   954     if (lmo) 
   955 	{	// MapObj was found
   956 		if (model->getSelectedLMO() != lmo)
   957 		{
   958 			// select the MapObj
   959 			model->select(lmo);
   960 		}
   961 		// Context Menu 
   962 		if (model->getSelectedBranchObj() ) 
   963 		{
   964 			// Context Menu on branch or mapcenter
   965 			branchContextMenu->popup(e->globalPos() );
   966 		} else
   967 		{
   968 			if (model->getSelectedImage() )
   969 			{
   970 				// Context Menu on floatimage
   971 				floatimageContextMenu->popup(e->globalPos() );
   972 			}	
   973 		}	
   974 	} else 
   975 	{ // No MapObj found, we are on the Canvas itself
   976 		// Context Menu on scene
   977 		
   978 		// Open context menu synchronously to position new mapcenter
   979 		model->setContextPos (p);
   980 		canvasContextMenu->exec(e->globalPos() );
   981 		model->unsetContextPos ();
   982     } 
   983 	e->accept();
   984 }
   985 
   986 void MapEditor::keyPressEvent(QKeyEvent* e)
   987 {
   988 	//qDebug()<<"ME::keyPressed";
   989 	//return;
   990 	if (e->modifiers() & Qt::ControlModifier)
   991 	{
   992 		switch (mainWindow->getModMode())
   993 		{
   994 			case Main::ModModeColor: 
   995 				setCursor (PickColorCursor);
   996 				break;
   997 			case Main::ModModeCopy: 
   998 				setCursor (CopyCursor);
   999 				break;
  1000 			case Main::ModModeXLink: 
  1001 				setCursor (XLinkCursor);
  1002 				break;
  1003 			default :
  1004 				setCursor (Qt::ArrowCursor);
  1005 				break;
  1006 		} 
  1007 	}	
  1008 	QGraphicsView::keyPressEvent(e);
  1009 }
  1010 
  1011 void MapEditor::keyReleaseEvent(QKeyEvent* e)
  1012 {
  1013 	if (!(e->modifiers() & Qt::ControlModifier))
  1014 		setCursor (Qt::ArrowCursor);
  1015 }
  1016 
  1017 void MapEditor::mousePressEvent(QMouseEvent* e)
  1018 {
  1019 	// Ignore right clicks or wile editing heading
  1020 	if (e->button() == Qt::RightButton or model->isSelectionBlocked() )
  1021 	{
  1022 		//qDebug() << "  ME::ignoring right mouse event...\n";
  1023 		e->ignore();
  1024 		QGraphicsView::mousePressEvent(e);
  1025 		return;
  1026 	}
  1027 
  1028     QPointF p = mapToScene(e->pos());
  1029     TreeItem *ti=findMapItem (p, NULL);
  1030     LinkableMapObj* lmo=NULL;
  1031 	if (ti) lmo=((MapItem*)ti)->getLMO();
  1032 	
  1033 	
  1034 	e->accept();
  1035 
  1036 	//Take care of  system flags _or_ modifier modes
  1037 	//
  1038 	if (lmo && ti->isBranchLikeType() )
  1039 	{
  1040 		QString foname=((BranchObj*)lmo)->getSystemFlagName(p);
  1041 		if (!foname.isEmpty())
  1042 		{
  1043 			// systemFlag clicked
  1044 			model->select (lmo);	
  1045 			if (foname.contains("system-url")) 
  1046 			{
  1047 				if (e->state() & Qt::ControlModifier)
  1048 					mainWindow->editOpenURLTab();
  1049 				else	
  1050 					mainWindow->editOpenURL();
  1051 			}	
  1052 			else if (foname=="system-vymLink")
  1053 			{
  1054 				mainWindow->editOpenVymLink();
  1055 				// tabWidget may change, better return now
  1056 				// before segfaulting...
  1057 			} else if (foname=="system-note")
  1058 				mainWindow->windowToggleNoteEditor();
  1059 			else if (foname=="hideInExport")		
  1060 				model->toggleHideExport();
  1061 			// FIXME-3 needed? xelection.update();	
  1062 			return;	
  1063 		} else
  1064 		{
  1065 			// Take care of xLink
  1066 			if (ti->xlinkCount()>0 && lmo->getBBox().width()>30)
  1067 			{
  1068 				if ((lmo->getOrientation()!=LinkableMapObj::RightOfCenter && p.x() < lmo->getBBox().left()+20)  ||
  1069 				    (lmo->getOrientation()!=LinkableMapObj::LeftOfCenter && p.x() > lmo->getBBox().right()-20) ) 
  1070 				{
  1071 					// FIXME-4 if (ti->xlinkCount()>1)
  1072 					if (true)
  1073 					{
  1074 						QMenu menu;
  1075 						QList <QAction*> alist;
  1076 						for (int i=0;i<ti->xlinkCount();i++)
  1077 							alist.append (new QAction(ti->getXLinkNum(i)->getOtherBranch(ti)->getHeading(),&menu));
  1078 						menu.addActions (alist);	
  1079 						QAction *ra=menu.exec (e->globalPos() );
  1080 						if (ra)
  1081 							model->select (ti->getXLinkNum(alist.indexOf(ra))->getOtherBranch (ti));
  1082 						while (!alist.isEmpty())
  1083 						{
  1084 							QAction *a=alist.takeFirst();
  1085 							delete a;
  1086 						}	
  1087 						return;
  1088 					} else
  1089 					{
  1090 						model->select (ti->getXLinkNum(0)->getOtherBranch (ti));
  1091 						return;
  1092 					}
  1093 				}	
  1094 			}
  1095 		}
  1096 	}	
  1097 
  1098 	// No system flag clicked, take care of modmodes (CTRL-Click)
  1099 	if (e->state() & Qt::ControlModifier)
  1100 	{
  1101 		if (mainWindow->getModMode()==Main::ModModeColor)
  1102 		{
  1103 				pickingColor=true;
  1104 				setCursor (PickColorCursor);
  1105 				return;
  1106 		} 
  1107 		if (mainWindow->getModMode()==Main::ModModeXLink)
  1108 		{	
  1109 			BranchItem *bi_begin=model->getSelectedBranch();
  1110 			if (bi_begin)	
  1111 			{
  1112 				drawingLink=true;
  1113 				tmpXLink=model->createXLink(bi_begin,true);
  1114 				tmpXLink->setColor(model->getMapDefXLinkColor());
  1115 				tmpXLink->setWidth(model->getMapDefXLinkWidth());
  1116 				tmpXLink->setEnd   (p);
  1117 				tmpXLink->updateXLink();
  1118 				return;
  1119 			} 
  1120 		}
  1121 	}	// End of modmodes
  1122 
  1123     if (lmo) 
  1124 	{	
  1125 	/*
  1126 		qDebug() << "ME::mouse pressed\n";
  1127 		qDebug() << "  lmo="<<lmo;
  1128 		qDebug() << "   ti="<<ti->getHeadingStd();
  1129 	*/
  1130 		// Select the clicked object
  1131 
  1132 		// Get clicked LMO
  1133 		model->select (ti);
  1134 
  1135 		// Left Button	    Move Branches
  1136 		if (e->button() == Qt::LeftButton )
  1137 		{
  1138 			movingObj_start.setX( p.x() - lmo->x() );	
  1139 			movingObj_start.setY( p.y() - lmo->y() );	
  1140 			movingObj_orgPos.setX (lmo->x() );
  1141 			movingObj_orgPos.setY (lmo->y() );
  1142 			lmo->setRelPos();
  1143 			movingObj_orgRelPos=lmo->getRelPos();
  1144 
  1145 			// If modMode==copy, then we want to "move" the _new_ object around
  1146 			// then we need the offset from p to the _old_ selection, because of tmp
  1147 			if (mainWindow->getModMode()==Main::ModModeCopy &&
  1148 				e->state() & Qt::ControlModifier)
  1149 			{
  1150 				BranchItem *bi=model->getSelectedBranch();
  1151 				if (bi)
  1152 				{
  1153 					copyingObj=true;
  1154 					//FIXME-2   TreeItem::addBranch (BranchItem still missing) 
  1155 					//bi->addBranch (model->getSelectedBranch());
  1156 					model->unselect();
  1157 					model->select(bi->getLastBranch());
  1158 					model->reposition();
  1159 				}
  1160 			} 
  1161 
  1162 			movingObj=model->getSelectedLMO();	
  1163 		} else
  1164 			// Middle Button    Toggle Scroll
  1165 			// (On Mac OS X this won't work, but we still have 
  1166 			// a button in the toolbar)
  1167 			if (e->button() == Qt::MidButton )
  1168 				model->toggleScroll();
  1169 		// model->updateActions(); FIXME-3 needed?
  1170 		// FIXME-3 needed? xelection.update();
  1171 	} else 
  1172 	{ // No MapObj found, we are on the scene itself
  1173 		// Left Button	    move Pos of sceneView
  1174 		if (e->button() == Qt::LeftButton )
  1175 		{
  1176 			movingObj=NULL;	// move Content not Obj
  1177 			movingObj_start=e->globalPos();
  1178 			movingCont_start=QPointF (
  1179 				horizontalScrollBar()->value(),
  1180 				verticalScrollBar()->value());
  1181 			movingVec=QPointF(0,0);
  1182 			setCursor(HandOpenCursor);
  1183 		} 
  1184     } 
  1185 	QGraphicsView::mousePressEvent(e);
  1186 }
  1187 
  1188 void MapEditor::mouseMoveEvent(QMouseEvent* e)
  1189 {
  1190 
  1191     QPointF p = mapToScene(e->pos());
  1192 	TreeItem *seli=model->getSelectedItem();
  1193 	LinkableMapObj* lmosel=NULL;	
  1194 	if (seli && (seli->isBranchLikeType() ||seli->getType()==TreeItem::Image))
  1195 		lmosel=((MapItem*)seli)->getLMO();
  1196 
  1197     // Move the selected MapObj
  1198     if ( lmosel && movingObj) 
  1199     {	
  1200 		objectMoved=true;
  1201 		// reset cursor if we are moving and don't copy
  1202 		if (mainWindow->getModMode()!=Main::ModModeCopy)
  1203 			setCursor (Qt::ArrowCursor);
  1204 
  1205 		// To avoid jumping of the sceneView, only 
  1206 		// show selection, if not tmp linked
  1207 		/* FIXME-2 if (!lmosel->hasParObjTmp())
  1208 			model->emitShowSelection();
  1209 			*/
  1210 		
  1211 		// Now move the selection, but add relative position 
  1212 		// (movingObj_start) where selection was chosen with 
  1213 		// mousepointer. (This avoids flickering resp. jumping 
  1214 		// of selection back to absPos)
  1215 		
  1216 		// Check if we could link 
  1217 		TreeItem *ti=findMapItem (p, seli);
  1218 		BranchItem *dsti=NULL;
  1219 		LinkableMapObj* dst=NULL;
  1220 		if (ti && ti!=seli && ti->isBranchLikeType())
  1221 		{
  1222 			dsti=(BranchItem*)ti;
  1223 			dst=dsti->getLMO(); 
  1224 		} else
  1225 			dsti=NULL;
  1226 		
  1227 
  1228 		if (lmosel && seli->getType()==TreeItem::Image)	
  1229 		{
  1230 			FloatObj *fio=(FloatImageObj*)lmosel;
  1231 			fio->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  1232 			fio->setRelPos();
  1233 			fio->updateLinkGeometry(); //no need for reposition, if we update link here
  1234 			model->emitSelectionChanged();	// position has changed
  1235 
  1236 			// Relink float to new mapcenter or branch, if shift is pressed	
  1237 			// Only relink, if selection really has a new parent
  1238 			if ( e->modifiers()==Qt::ShiftModifier && dsti &&  dsti != seli->parent()  )
  1239 			{
  1240 				// Also save the move which was done so far
  1241 				QString pold=qpointFToString(movingObj_orgRelPos);
  1242 				QString pnow=qpointFToString(fio->getRelPos());
  1243 				model->saveState(
  1244 					seli,
  1245 					"moveRel "+pold,
  1246 					seli,
  1247 					"moveRel "+pnow,
  1248 					QString("Move %1 to relative position %2").arg(model->getObjectName(fio)).arg(pnow));
  1249 				fio->getParObj()->requestReposition();
  1250 				model->reposition();
  1251 
  1252 				model->relinkImage ((ImageItem*) seli,dsti);
  1253 				model->select (seli);
  1254 				//movingObj=lmosel;	//FIXME-3
  1255 				//movingObj_orgRelPos=lmosel->getRelPos();	
  1256 
  1257 				model->reposition();
  1258 			}
  1259 		} else	
  1260 		{	// selection != a FloatObj
  1261 			if (seli->depth()==0)		
  1262 			{
  1263 				// Move mapcenter
  1264 				lmosel->move   (p-movingObj_start);		
  1265 				if (e->buttons()== Qt::LeftButton && e->modifiers()==Qt::ShiftModifier) 
  1266 				{
  1267 					// Move only mapcenter, leave its children where they are
  1268 					QPointF v;
  1269 					v=lmosel->getAbsPos();
  1270 					for (int i=0; i<seli->branchCount(); ++i)
  1271 					{
  1272 						seli->getBranchObjNum(i)->setRelPos();
  1273 						seli->getBranchObjNum(i)->setOrientation();
  1274 					}
  1275 				}	
  1276 			} else
  1277 			{	
  1278 				if (seli->depth()==1)
  1279 				{
  1280 					// Move mainbranch
  1281 					if (!lmosel->hasParObjTmp())
  1282 						lmosel->move(p-movingObj_start);		
  1283 					lmosel->setRelPos();
  1284 				} else
  1285 				{
  1286 					// Move ordinary branch
  1287 					if (lmosel->getOrientation() == LinkableMapObj::LeftOfCenter)
  1288 						// Add width of bbox here, otherwise alignRelTo will cause jumping around
  1289 						lmosel->move(p.x() -movingObj_start.x() , //lmosel->getBBox().width(), 
  1290 							p.y()-movingObj_start.y() +lmosel->getTopPad() );		
  1291 					else	
  1292 						lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() -lmosel->getTopPad());
  1293 					lmosel->setRelPos();	
  1294 				} 
  1295 
  1296 			} // depth>0
  1297 				// Maybe we can relink temporary?
  1298 				if (dsti)
  1299 				{
  1300 					if (e->modifiers()==Qt::ControlModifier)
  1301 					{
  1302 						// Special case: CTRL to link below dst
  1303 						lmosel->setParObjTmp (dst,p,+1);
  1304 					} else if (e->modifiers()==Qt::ShiftModifier)
  1305 						lmosel->setParObjTmp (dst,p,-1);
  1306 					else
  1307 						lmosel->setParObjTmp (dst,p,0);
  1308 				} else	
  1309 				{
  1310 					lmosel->unsetParObjTmp();
  1311 				}		
  1312 				// reposition subbranch
  1313 				lmosel->reposition();	
  1314 
  1315 			QItemSelection sel=model->getSelectionModel()->selection();
  1316 			updateSelection(sel,sel);	// position has changed
  1317 
  1318 		} // no FloatImageObj
  1319 
  1320 		scene()->update();
  1321 		return;
  1322 	} // selection && moving_obj
  1323 		
  1324 	// Draw a link from one branch to another
  1325 	if (drawingLink)
  1326 	{
  1327 		 tmpXLink->setEnd (p);
  1328 		 tmpXLink->updateXLink();
  1329 	}	 
  1330 	
  1331     // Move sceneView 
  1332     if (!movingObj && !pickingColor &&!drawingLink && e->buttons() == Qt::LeftButton ) 
  1333 	{
  1334 		QPointF p=e->globalPos();
  1335 		movingVec.setX(-p.x() + movingObj_start.x() );
  1336 		movingVec.setY(-p.y() + movingObj_start.y() );
  1337 		horizontalScrollBar()->setSliderPosition((int)( movingCont_start.x()+movingVec.x() ));
  1338 		verticalScrollBar()->setSliderPosition((int)( movingCont_start.y()+movingVec.y() ) );
  1339     }
  1340 	QGraphicsView::mouseMoveEvent (e);	
  1341 }
  1342 
  1343 
  1344 void MapEditor::mouseReleaseEvent(QMouseEvent* e)
  1345 {
  1346     QPointF p = mapToScene(e->pos());
  1347 	TreeItem *seli=model->getSelectedItem();
  1348 
  1349 	TreeItem *dsti=NULL;
  1350 	if (seli) dsti=findMapItem(p, seli);
  1351 	LinkableMapObj* dst=NULL;
  1352 	if (dsti && dsti->isBranchLikeType ()) 
  1353 		dst=((MapItem*)dsti)->getLMO();	
  1354 	else
  1355 		dsti=NULL;
  1356 
  1357 
  1358 	// Have we been picking color?
  1359 	if (pickingColor)
  1360 	{
  1361 		pickingColor=false;
  1362 		setCursor (Qt::ArrowCursor);
  1363 		// Check if we are over another branch
  1364 		if (dst) 
  1365 		{	
  1366 			if (e->state() & Qt::ShiftModifier)
  1367 				model->colorBranch (((BranchObj*)dst)->getColor());
  1368 			else	
  1369 				model->colorSubtree (((BranchObj*)dst)->getColor());
  1370 		} 
  1371 		return;
  1372 	}
  1373 
  1374 	// Have we been drawing a link?
  1375 	if (drawingLink)	
  1376 	{
  1377 		drawingLink=false;
  1378 		// Check if we are over another branch
  1379 		if (dsti)
  1380 		{	
  1381 			tmpXLink->setEnd ( ((BranchItem*)dsti) );
  1382 			tmpXLink->updateXLink();
  1383 			tmpXLink->activate(); 
  1384 			model->saveState(
  1385 				tmpXLink,QString("delete ()"),
  1386 				dsti,QString("addXLink (\"%1\",\"%2\")").arg(model->getSelectString(tmpXLink->getBegin())).arg(model->getSelectString(dsti)),
  1387 				QString("Add xLink from %1 to %2").arg(model->getObjectName(tmpXLink->getBegin())).arg(model->getObjectName(dsti)) 
  1388 			);	
  1389 		} else
  1390 		{
  1391 			model->deleteItem(tmpXLink);
  1392 			tmpXLink=NULL;
  1393 		}
  1394 		return;
  1395 	}
  1396 	
  1397     // Have we been moving something?
  1398     if ( seli && movingObj ) 
  1399     {	
  1400 		if (seli->getType()==TreeItem::Image)
  1401 		{
  1402 			FloatImageObj *fio=(FloatImageObj*)( ((MapItem*)seli)->getLMO());
  1403 			if(fio)
  1404 			{
  1405 				// Moved FloatObj. Maybe we need to reposition
  1406 				QString pold=qpointFToString(movingObj_orgRelPos);
  1407 				QString pnow=qpointFToString(fio->getRelPos());
  1408 				model->saveState(
  1409 					seli,
  1410 					"moveRel "+pold,
  1411 					seli,
  1412 					"moveRel "+pnow,
  1413 					QString("Move %1 to relative position %2").arg(model->getObjectName(seli)).arg(pnow));
  1414 
  1415 				fio->getParObj()->requestReposition();
  1416 				model->reposition();
  1417 			}	
  1418 		}
  1419 
  1420 		BranchItem *bi=model->getSelectedBranch();
  1421 		if (bi && bi->depth()==0)
  1422 		{	
  1423             if (movingObj_orgPos != bi->getBranchObj()->getAbsPos())	// FIXME-3 check getBO here...
  1424             {
  1425                 QString pold=qpointFToString(movingObj_orgPos);
  1426                 QString pnow=qpointFToString(bi->getBranchObj()->getAbsPos());		// FIXME-3 check getBO here...
  1427 
  1428                 model->saveState(
  1429                     bi,
  1430                     "move "+pold,
  1431                     bi,
  1432                     "move "+pnow,
  1433                     QString("Move mapcenter %1 to position %2").arg(model->getObjectName(bi)).arg(pnow));
  1434             }
  1435 		}
  1436 	
  1437 		if (seli->isBranchLikeType() ) //(seli->getType() == TreeItem::Branch )
  1438 		{	// A branch was moved
  1439 			LinkableMapObj* lmosel=NULL;		
  1440 			lmosel=((MapItem*)seli)->getLMO();
  1441 				
  1442 			// save the position in case we link to mapcenter
  1443 			QPointF savePos=QPointF (lmosel->getAbsPos()  );
  1444 
  1445 			// Reset the temporary drawn link to the original one
  1446 			lmosel->unsetParObjTmp();
  1447 
  1448 			// For Redo we may need to save original selection
  1449 			QString preSelStr=model->getSelectString(seli);
  1450 
  1451 			copyingObj=false;	
  1452 			if (dsti && objectMoved)
  1453 			{
  1454 				// We have a destination, relink to that
  1455 
  1456 				BranchObj* bsel=model->getSelectedBranchObj();
  1457 
  1458 				QString preParStr=model->getSelectString (bsel->getParObj());
  1459 				QString preNum=QString::number (seli->num(),10);
  1460 				QString preDstParStr;
  1461 				bool relinked;
  1462 
  1463 				if (e->state() & Qt::ShiftModifier && dst->getParObj())
  1464 				{	// Link above dst
  1465 					preDstParStr=model->getSelectString (dst->getParObj());
  1466 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti->parent(),((BranchItem*)dsti)->num());
  1467 				} else 
  1468 				if (e->state() & Qt::ControlModifier && dst->getParObj())
  1469 				{
  1470 					// Link below dst
  1471 					preDstParStr=model->getSelectString (dst->getParObj());
  1472 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti->parent(),((BranchItem*)dsti)->num()+1);
  1473 				} else	
  1474 				{	// Append to dst
  1475 					preDstParStr=model->getSelectString(dst);
  1476 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti);
  1477 					if (dsti->depth()==0) bsel->move (savePos);
  1478 				} 
  1479 				if (relinked)
  1480 				{
  1481 					QString postSelStr=model->getSelectString(lmosel);
  1482 					QString postNum=QString::number (seli->num(),10);
  1483 
  1484 					QString undoCom="relinkTo (\""+ 
  1485 						preParStr+ "\"," + preNum  +"," + 
  1486 						QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+ ")";
  1487 
  1488 					QString redoCom="relinkTo (\""+ 
  1489 						preDstParStr + "\"," + postNum + "," +
  1490 						QString ("%1,%2").arg(savePos.x()).arg(savePos.y())+ ")";
  1491 
  1492 					model->saveState (
  1493 						postSelStr,undoCom,
  1494 						preSelStr, redoCom,
  1495 						QString("Relink %1 to %2").arg(model->getObjectName(bsel)).arg(model->getObjectName(dst)) );
  1496 
  1497 				}
  1498 			} else
  1499 			{
  1500 				// No destination, undo  temporary move	
  1501 
  1502 				if (seli->depth()==1)
  1503 				{
  1504 					// The select string might be different _after_ moving around.
  1505 					// Therefor reposition and then use string of old selection, too
  1506 					model->reposition();
  1507 
  1508                     QPointF rp(lmosel->getRelPos());
  1509                     if (rp != movingObj_orgRelPos)
  1510                     {
  1511                         QString ps=qpointFToString(rp);
  1512                         model->saveState(
  1513                             model->getSelectString(lmosel), "moveRel "+qpointFToString(movingObj_orgRelPos), 
  1514                             preSelStr, "moveRel "+ps, 
  1515                             QString("Move %1 to relative position %2").arg(model->getObjectName(lmosel)).arg(ps));
  1516                     }
  1517 				}
  1518 
  1519 				// Draw the original link, before selection was moved around
  1520 				if (settings.value("/animation/use",true).toBool() 
  1521 					&& seli->depth()>1
  1522 //					&& distance (lmosel->getRelPos(),movingObj_orgRelPos)<3
  1523 				) 
  1524 				{
  1525 					lmosel->setRelPos();	// calc relPos first for starting point
  1526 					
  1527 					model->startAnimation(
  1528 						(BranchObj*)lmosel,
  1529 						lmosel->getRelPos(),
  1530 						movingObj_orgRelPos
  1531 					);	
  1532 				} else	
  1533 					model->reposition();
  1534 			}
  1535 		}
  1536 		model->emitSelectionChanged();  //FIXME-3 needed? at least not after pos of selection has changed...
  1537 		// Finally resize scene, if needed
  1538 		scene()->update();
  1539 		movingObj=NULL;		
  1540 		objectMoved=false;
  1541 
  1542 	} else 
  1543 		// maybe we moved View: set old cursor
  1544 		setCursor (Qt::ArrowCursor);
  1545 
  1546 	QGraphicsView::mouseReleaseEvent(e);
  1547 }
  1548 
  1549 void MapEditor::mouseDoubleClickEvent(QMouseEvent* e)
  1550 {
  1551 	if (debug) 
  1552 	{
  1553 		qDebug()<< "ME p="<<mapToScene (e->pos())<<"  scrollBarPos="<<getScrollBarPos() <<
  1554 		           "  min="<<QPointF(horizontalScrollBar()->minimum(),verticalScrollBar()->minimum());
  1555 	}
  1556 
  1557 
  1558 /*
  1559 	if (model->isSelectionBlocked() ) 
  1560 	{
  1561 		e->ignore();
  1562 		return;
  1563 	}
  1564 */
  1565 	if (e->button() == Qt::LeftButton )
  1566 	{
  1567 		QPointF p = mapToScene(e->pos());
  1568 		TreeItem *ti=findMapItem (p, NULL);
  1569 		if (ti) {	// MapObj was found
  1570 			// First select the MapObj than edit heading
  1571 			model->select (ti);
  1572 			editHeading();
  1573 		}
  1574 	}
  1575 }
  1576 
  1577 void MapEditor::resizeEvent (QResizeEvent* e)
  1578 {
  1579 	QGraphicsView::resizeEvent( e );
  1580 }
  1581 
  1582 void MapEditor::dragEnterEvent(QDragEnterEvent *event)
  1583 {
  1584 	//for (unsigned int i=0;event->format(i);i++) // Debug mime type
  1585 	//	cerr << event->format(i) << endl;
  1586 
  1587 	if (event->mimeData()->hasImage())
  1588 		event->acceptProposedAction();
  1589 	else	
  1590 		if (event->mimeData()->hasUrls())
  1591 			event->acceptProposedAction();
  1592 }
  1593 
  1594 void MapEditor::dragMoveEvent(QDragMoveEvent *)
  1595 {
  1596 }
  1597 
  1598 void MapEditor::dragLeaveEvent(QDragLeaveEvent *event)
  1599 {
  1600 	event->accept();
  1601 }
  1602 
  1603 void MapEditor::dropEvent(QDropEvent *event)
  1604 {
  1605 	BranchItem *selbi=model->getSelectedBranch();
  1606 	if (selbi)
  1607 	{
  1608 		if (debug)
  1609 		{
  1610 			foreach (QString format,event->mimeData()->formats()) 
  1611 				qDebug()<< "MapEditor: Dropped format: "<<qPrintable (format);
  1612 			foreach (QString url,event->mimeData()->urls())
  1613 				qDebug()<< "  URL:"<<url;
  1614 			//foreach (QString plain,event->mimeData()->text())
  1615 			//	qDebug()<< "   PLAIN:"<<plain;
  1616 			QByteArray ba=event->mimeData()->data("STRING");
  1617 			
  1618 			QString s;
  1619 			s=ba;
  1620 			qDebug() << "  STRING:" <<s;
  1621 
  1622 			ba=event->mimeData()->data("TEXT");
  1623 			s=ba;
  1624 			qDebug() << "    TEXT:" <<s;
  1625 
  1626 			ba=event->mimeData()->data("COMPOUND_TEXT");
  1627 			s=ba;
  1628 			qDebug() << "   CTEXT:" <<s;
  1629 
  1630 			ba=event->mimeData()->data("text/x-moz-url");
  1631 			s=ba;
  1632 			qDebug() << "   x-moz-url:" <<s;
  1633 			foreach (char b,ba)
  1634 				if (b!=0) qDebug() << "b="<<b;
  1635 		}
  1636 
  1637 		if (event->mimeData()->hasImage()) 
  1638 		{
  1639 			 QVariant imageData = event->mimeData()->imageData();
  1640 			 model->addFloatImage (qvariant_cast<QPixmap>(imageData));
  1641 		} else
  1642 		if (event->mimeData()->hasUrls())
  1643 		{
  1644 			//model->selectLastBranch();
  1645 			QList <QUrl> uris=event->mimeData()->urls();
  1646 			QStringList files;
  1647 			QString s;
  1648 			QString heading;
  1649 			BranchItem *bi;
  1650 			for (int i=0; i<uris.count();i++)
  1651 			{
  1652 				// Workaround to avoid adding empty branches
  1653 				if (!uris.at(i).toString().isEmpty())
  1654 				{
  1655 					bi=model->addNewBranch();
  1656 					if (bi)
  1657 					{
  1658 						model->select(bi);
  1659 						QString u=uris.at(i).toString();
  1660 						s=uris.at(i).toLocalFile();
  1661 						if (!s.isEmpty()) 
  1662 						{
  1663 						   QString file = QDir::fromNativeSeparators(s);
  1664 						   heading = QFileInfo(file).baseName();
  1665 						   files.append(file);
  1666 						   if (file.endsWith(".vym", false))
  1667 							   model->setVymLink(file);
  1668 						   else
  1669 							   model->setURL(u);
  1670 					   } else 
  1671 					   {
  1672 							model->setURL(u);
  1673 
  1674 /*
  1675 							// Automatically try to fetch data from Bugzilla
  1676 							if (settings.value( "/mainwindow/showTestMenu",false).toBool() 
  1677 								&& u.contains ("https://bugzilla.novell.com"))
  1678 								model->getBugzillaData();
  1679 */								
  1680 					   }
  1681 
  1682 					   if (!heading.isEmpty())
  1683 						   model->setHeading(heading);
  1684 					   else
  1685 						   model->setHeading(u);
  1686 						   
  1687 						model->select (bi->parent());	   
  1688 					}
  1689 				}
  1690 			}
  1691 			//model->reposition();
  1692 		}
  1693 	}	
  1694 	event->acceptProposedAction();
  1695 }
  1696 
  1697 void MapEditor::updateSelection(QItemSelection newsel,QItemSelection oldsel)
  1698 {
  1699 	// Note: Here we are prepared for multiple selections, though this 
  1700 	// is not yet implemented elsewhere
  1701 
  1702 	// Here in MapEditor we can only select Branches and Images
  1703 	QList <TreeItem*> treeItemsNew;
  1704 	QList <TreeItem*> treeItemsOld;
  1705 
  1706 	QModelIndex newIndex;
  1707 
  1708 	bool do_reposition=false;
  1709 
  1710 	QModelIndex ix;
  1711 	foreach (ix,newsel.indexes() )
  1712 	{
  1713 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1714 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1715 			if (!treeItemsNew.contains(ti)) treeItemsNew.append (ti);
  1716 	}
  1717 	foreach (ix,oldsel.indexes() )
  1718 	{
  1719 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1720 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1721 			if (!treeItemsOld.contains(ti)) treeItemsOld.append (ti);
  1722 	}
  1723 
  1724 	// Trim list of selection rectangles 
  1725 	while (treeItemsNew.count() < selboxList.count() )
  1726 		delete selboxList.takeFirst();
  1727 
  1728 	// Take care to tmp scroll/unscroll
  1729 	if (!oldsel.isEmpty())
  1730 	{
  1731 		QModelIndex ix=oldsel.indexes().first(); 
  1732 		if (ix.isValid() )
  1733 		{
  1734 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1735 			if (ti)
  1736 			{
  1737 				if (ti->isBranchLikeType() )
  1738 				{
  1739 					// reset tmp scrolled branches
  1740 					BranchItem *bi=(BranchItem*)ti;
  1741 					if (bi->resetTmpUnscroll() )
  1742 						do_reposition=true;
  1743 				}
  1744 				if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1745 					// Hide link if not needed
  1746 					((MapItem*)ti)->getLMO()->updateVisibility();
  1747 			}
  1748 		}
  1749 	}
  1750 
  1751 	if (!treeItemsNew.isEmpty())
  1752 	{
  1753 		QModelIndex ix=newsel.indexes().first(); 
  1754 		if (ix.isValid() )
  1755 		{
  1756 			newIndex=ix;
  1757 
  1758 			// Temporary unscroll if necessary
  1759 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1760 			if (ti->isBranchLikeType() )
  1761 			{
  1762 				BranchItem *bi=(BranchItem*)ti;
  1763 				if (bi->hasScrolledParent(bi) )
  1764 				{
  1765 					if (bi->parentBranch()->tmpUnscroll() )
  1766 						do_reposition=true;
  1767 				}	
  1768 			}
  1769 			if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1770 				// Show link if needed
  1771 				((MapItem*)ti)->getLMO()->updateVisibility();
  1772 		}
  1773 	}
  1774 	if (do_reposition) model->reposition();
  1775 
  1776 	// Reduce rectangles
  1777 	while (treeItemsNew.count() < selboxList.count() )
  1778 		delete selboxList.takeFirst();
  1779 
  1780 	// Add additonal rectangles
  1781 	QGraphicsRectItem *sb;
  1782 	while (treeItemsNew.count() > selboxList.count() )
  1783 	{
  1784 		sb = mapScene->addRect(
  1785 			QRectF(0,0,0,0), 
  1786 			QPen(selectionColor),
  1787 			selectionColor);
  1788 		sb->setZValue(Z_SELBOX);
  1789 		sb->show();
  1790 		selboxList.append (sb);
  1791 	}
  1792 
  1793 	// Reposition rectangles
  1794 	QRectF bbox;
  1795 	QModelIndex index;
  1796 
  1797 	LinkableMapObj *lmo;
  1798 	for (int i=0; i<treeItemsNew.count();++i)
  1799 	{
  1800 		lmo=((MapItem*)treeItemsNew.at(i) )->getLMO();
  1801 		bbox=lmo->getBBox();
  1802 		sb=selboxList.at(i);
  1803 		sb->setRect (
  1804 			bbox.x(),bbox.y(), 
  1805 			bbox.width(), bbox.height());
  1806 		sb->setPen (selectionColor);	
  1807 		sb->setBrush (selectionColor);	
  1808 		i++;
  1809 	}
  1810 
  1811 	scene()->update();  
  1812 }
  1813 
  1814 void MapEditor::updateData (const QModelIndex &sel)
  1815 {
  1816 	TreeItem *ti= static_cast<TreeItem*>(sel.internalPointer());
  1817 
  1818 /* testing
  1819 	qDebug() << "ME::updateData\n";
  1820 
  1821 	qDebug() << "  ti="<<ti;
  1822 	qDebug() << "  h="<<ti->getHeading();
  1823 	*/
  1824 	
  1825 	if (ti->isBranchLikeType())
  1826 	{
  1827 	//	qDebug() << "  ->updating...\n";
  1828 		BranchObj *bo=(BranchObj*) ( ((MapItem*)ti)->getLMO());
  1829 		bo->updateData();
  1830 	}
  1831 }
  1832 
  1833 void MapEditor::setSelectionColor (QColor col)
  1834 {
  1835 	selectionColor=col;
  1836 	QItemSelection sel=model->getSelectionModel()->selection();
  1837 	updateSelection(sel,sel);
  1838 }
  1839 
  1840 
  1841 QColor MapEditor::getSelectionColor ()
  1842 {
  1843 	return selectionColor;
  1844 }
  1845 
  1846