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