mapeditor.cpp
author insilmaril
Tue, 30 Mar 2010 17:30:39 +0000
changeset 842 bec082472471
parent 841 46553c106c52
child 844 c48bb42fb977
permissions -rw-r--r--
Much improved results in FindResultsWidget
     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 	if (e->key()==Qt::Key_PageUp || e->key()==Qt::Key_PageDown)
   989 		// Ignore PageUP/Down to avoid scrolling with keys
   990 		return;
   991 
   992 	if (e->modifiers() & Qt::ControlModifier)
   993 	{
   994 		switch (mainWindow->getModMode())
   995 		{
   996 			case Main::ModModeColor: 
   997 				setCursor (PickColorCursor);
   998 				break;
   999 			case Main::ModModeCopy: 
  1000 				setCursor (CopyCursor);
  1001 				break;
  1002 			case Main::ModModeXLink: 
  1003 				setCursor (XLinkCursor);
  1004 				break;
  1005 			default :
  1006 				setCursor (Qt::ArrowCursor);
  1007 				break;
  1008 		} 
  1009 	}	
  1010 	QGraphicsView::keyPressEvent(e);
  1011 }
  1012 
  1013 void MapEditor::keyReleaseEvent(QKeyEvent* e)
  1014 {
  1015 	if (!(e->modifiers() & Qt::ControlModifier))
  1016 		setCursor (Qt::ArrowCursor);
  1017 }
  1018 
  1019 void MapEditor::mousePressEvent(QMouseEvent* e)
  1020 {
  1021 	// Ignore right clicks or wile editing heading
  1022 	if (e->button() == Qt::RightButton or model->isSelectionBlocked() )
  1023 	{
  1024 		//qDebug() << "  ME::ignoring right mouse event...\n";
  1025 		e->ignore();
  1026 		QGraphicsView::mousePressEvent(e);
  1027 		return;
  1028 	}
  1029 
  1030     QPointF p = mapToScene(e->pos());
  1031     TreeItem *ti=findMapItem (p, NULL);
  1032     LinkableMapObj* lmo=NULL;
  1033 	if (ti) lmo=((MapItem*)ti)->getLMO();
  1034 	
  1035 	
  1036 	e->accept();
  1037 
  1038 	//Take care of  system flags _or_ modifier modes
  1039 	//
  1040 	if (lmo && ti->isBranchLikeType() )
  1041 	{
  1042 		QString foname=((BranchObj*)lmo)->getSystemFlagName(p);
  1043 		if (!foname.isEmpty())
  1044 		{
  1045 			// systemFlag clicked
  1046 			model->select (lmo);	
  1047 			if (foname.contains("system-url")) 
  1048 			{
  1049 				if (e->state() & Qt::ControlModifier)
  1050 					mainWindow->editOpenURLTab();
  1051 				else	
  1052 					mainWindow->editOpenURL();
  1053 			}	
  1054 			else if (foname=="system-vymLink")
  1055 			{
  1056 				mainWindow->editOpenVymLink();
  1057 				// tabWidget may change, better return now
  1058 				// before segfaulting...
  1059 			} else if (foname=="system-note")
  1060 				mainWindow->windowToggleNoteEditor();
  1061 			else if (foname=="hideInExport")		
  1062 				model->toggleHideExport();
  1063 			// FIXME-3 needed? xelection.update();	
  1064 			return;	
  1065 		} else
  1066 		{
  1067 			// Take care of xLink
  1068 			if (ti->xlinkCount()>0 && lmo->getBBox().width()>30)
  1069 			{
  1070 				if ((lmo->getOrientation()!=LinkableMapObj::RightOfCenter && p.x() < lmo->getBBox().left()+20)  ||
  1071 				    (lmo->getOrientation()!=LinkableMapObj::LeftOfCenter && p.x() > lmo->getBBox().right()-20) ) 
  1072 				{
  1073 					// FIXME-4 if (ti->xlinkCount()>1)
  1074 					if (true)
  1075 					{
  1076 						QMenu menu;
  1077 						QList <QAction*> alist;
  1078 						for (int i=0;i<ti->xlinkCount();i++)
  1079 							alist.append (new QAction(ti->getXLinkNum(i)->getOtherBranch(ti)->getHeading(),&menu));
  1080 						menu.addActions (alist);	
  1081 						QAction *ra=menu.exec (e->globalPos() );
  1082 						if (ra)
  1083 							model->select (ti->getXLinkNum(alist.indexOf(ra))->getOtherBranch (ti));
  1084 						while (!alist.isEmpty())
  1085 						{
  1086 							QAction *a=alist.takeFirst();
  1087 							delete a;
  1088 						}	
  1089 						return;
  1090 					} else
  1091 					{
  1092 						model->select (ti->getXLinkNum(0)->getOtherBranch (ti));
  1093 						return;
  1094 					}
  1095 				}	
  1096 			}
  1097 		}
  1098 	}	
  1099 
  1100 	// No system flag clicked, take care of modmodes (CTRL-Click)
  1101 	if (e->state() & Qt::ControlModifier)
  1102 	{
  1103 		if (mainWindow->getModMode()==Main::ModModeColor)
  1104 		{
  1105 				pickingColor=true;
  1106 				setCursor (PickColorCursor);
  1107 				return;
  1108 		} 
  1109 		if (mainWindow->getModMode()==Main::ModModeXLink)
  1110 		{	
  1111 			BranchItem *bi_begin=model->getSelectedBranch();
  1112 			if (bi_begin)	
  1113 			{
  1114 				drawingLink=true;
  1115 				tmpXLink=model->createXLink(bi_begin,true);
  1116 				tmpXLink->setColor(model->getMapDefXLinkColor());
  1117 				tmpXLink->setWidth(model->getMapDefXLinkWidth());
  1118 				tmpXLink->setEnd   (p);
  1119 				tmpXLink->updateXLink();
  1120 				return;
  1121 			} 
  1122 		}
  1123 	}	// End of modmodes
  1124 
  1125     if (lmo) 
  1126 	{	
  1127 	/*
  1128 		qDebug() << "ME::mouse pressed\n";
  1129 		qDebug() << "  lmo="<<lmo;
  1130 		qDebug() << "   ti="<<ti->getHeadingStd();
  1131 	*/
  1132 		// Select the clicked object
  1133 
  1134 		// Get clicked LMO
  1135 		model->select (ti);
  1136 
  1137 		// Left Button	    Move Branches
  1138 		if (e->button() == Qt::LeftButton )
  1139 		{
  1140 			movingObj_start.setX( p.x() - lmo->x() );	
  1141 			movingObj_start.setY( p.y() - lmo->y() );	
  1142 			movingObj_orgPos.setX (lmo->x() );
  1143 			movingObj_orgPos.setY (lmo->y() );
  1144 			lmo->setRelPos();
  1145 			movingObj_orgRelPos=lmo->getRelPos();
  1146 
  1147 			// If modMode==copy, then we want to "move" the _new_ object around
  1148 			// then we need the offset from p to the _old_ selection, because of tmp
  1149 			if (mainWindow->getModMode()==Main::ModModeCopy &&
  1150 				e->state() & Qt::ControlModifier)
  1151 			{
  1152 				BranchItem *bi=model->getSelectedBranch();
  1153 				if (bi)
  1154 				{
  1155 					copyingObj=true;
  1156 					//FIXME-2   TreeItem::addBranch (BranchItem still missing) 
  1157 					//bi->addBranch (model->getSelectedBranch());
  1158 					model->unselect();
  1159 					model->select(bi->getLastBranch());
  1160 					model->reposition();
  1161 				}
  1162 			} 
  1163 
  1164 			movingObj=model->getSelectedLMO();	
  1165 		} else
  1166 			// Middle Button    Toggle Scroll
  1167 			// (On Mac OS X this won't work, but we still have 
  1168 			// a button in the toolbar)
  1169 			if (e->button() == Qt::MidButton )
  1170 				model->toggleScroll();
  1171 		// model->updateActions(); FIXME-3 needed?
  1172 		// FIXME-3 needed? xelection.update();
  1173 	} else 
  1174 	{ // No MapObj found, we are on the scene itself
  1175 		// Left Button	    move Pos of sceneView
  1176 		if (e->button() == Qt::LeftButton )
  1177 		{
  1178 			movingObj=NULL;	// move Content not Obj
  1179 			movingObj_start=e->globalPos();
  1180 			movingCont_start=QPointF (
  1181 				horizontalScrollBar()->value(),
  1182 				verticalScrollBar()->value());
  1183 			movingVec=QPointF(0,0);
  1184 			setCursor(HandOpenCursor);
  1185 		} 
  1186     } 
  1187 	QGraphicsView::mousePressEvent(e);
  1188 }
  1189 
  1190 void MapEditor::mouseMoveEvent(QMouseEvent* e)
  1191 {
  1192 
  1193     QPointF p = mapToScene(e->pos());
  1194 	TreeItem *seli=model->getSelectedItem();
  1195 	LinkableMapObj* lmosel=NULL;	
  1196 	if (seli && (seli->isBranchLikeType() ||seli->getType()==TreeItem::Image))
  1197 		lmosel=((MapItem*)seli)->getLMO();
  1198 
  1199     // Move the selected MapObj
  1200     if ( lmosel && movingObj) 
  1201     {	
  1202 		objectMoved=true;
  1203 		// reset cursor if we are moving and don't copy
  1204 		if (mainWindow->getModMode()!=Main::ModModeCopy)
  1205 			setCursor (Qt::ArrowCursor);
  1206 
  1207 		// To avoid jumping of the sceneView, only 
  1208 		// show selection, if not tmp linked
  1209 		/* FIXME-2 if (!lmosel->hasParObjTmp())
  1210 			model->emitShowSelection();
  1211 			*/
  1212 		
  1213 		// Now move the selection, but add relative position 
  1214 		// (movingObj_start) where selection was chosen with 
  1215 		// mousepointer. (This avoids flickering resp. jumping 
  1216 		// of selection back to absPos)
  1217 		
  1218 		// Check if we could link 
  1219 		TreeItem *ti=findMapItem (p, seli);
  1220 		BranchItem *dsti=NULL;
  1221 		LinkableMapObj* dst=NULL;
  1222 		if (ti && ti!=seli && ti->isBranchLikeType())
  1223 		{
  1224 			dsti=(BranchItem*)ti;
  1225 			dst=dsti->getLMO(); 
  1226 		} else
  1227 			dsti=NULL;
  1228 		
  1229 
  1230 		if (lmosel && seli->getType()==TreeItem::Image)	
  1231 		{
  1232 			FloatObj *fio=(FloatImageObj*)lmosel;
  1233 			fio->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  1234 			fio->setRelPos();
  1235 			fio->updateLinkGeometry(); //no need for reposition, if we update link here
  1236 			model->emitSelectionChanged();	// position has changed
  1237 
  1238 			// Relink float to new mapcenter or branch, if shift is pressed	
  1239 			// Only relink, if selection really has a new parent
  1240 			if ( e->modifiers()==Qt::ShiftModifier && dsti &&  dsti != seli->parent()  )
  1241 			{
  1242 				// Also save the move which was done so far
  1243 				QString pold=qpointFToString(movingObj_orgRelPos);
  1244 				QString pnow=qpointFToString(fio->getRelPos());
  1245 				model->saveState(
  1246 					seli,
  1247 					"moveRel "+pold,
  1248 					seli,
  1249 					"moveRel "+pnow,
  1250 					QString("Move %1 to relative position %2").arg(model->getObjectName(fio)).arg(pnow));
  1251 				fio->getParObj()->requestReposition();
  1252 				model->reposition();
  1253 
  1254 				model->relinkImage ((ImageItem*) seli,dsti);
  1255 				model->select (seli);
  1256 				//movingObj=lmosel;	//FIXME-3
  1257 				//movingObj_orgRelPos=lmosel->getRelPos();	
  1258 
  1259 				model->reposition();
  1260 			}
  1261 		} else	
  1262 		{	// selection != a FloatObj
  1263 			if (seli->depth()==0)		
  1264 			{
  1265 				// Move mapcenter
  1266 				lmosel->move   (p-movingObj_start);		
  1267 				if (e->buttons()== Qt::LeftButton && e->modifiers()==Qt::ShiftModifier) 
  1268 				{
  1269 					// Move only mapcenter, leave its children where they are
  1270 					QPointF v;
  1271 					v=lmosel->getAbsPos();
  1272 					for (int i=0; i<seli->branchCount(); ++i)
  1273 					{
  1274 						seli->getBranchObjNum(i)->setRelPos();
  1275 						seli->getBranchObjNum(i)->setOrientation();
  1276 					}
  1277 				}	
  1278 			} else
  1279 			{	
  1280 				if (seli->depth()==1)
  1281 				{
  1282 					// Move mainbranch
  1283 					if (!lmosel->hasParObjTmp())
  1284 						lmosel->move(p-movingObj_start);		
  1285 					lmosel->setRelPos();
  1286 				} else
  1287 				{
  1288 					// Move ordinary branch
  1289 					if (lmosel->getOrientation() == LinkableMapObj::LeftOfCenter)
  1290 						// Add width of bbox here, otherwise alignRelTo will cause jumping around
  1291 						lmosel->move(p.x() -movingObj_start.x() , //lmosel->getBBox().width(), 
  1292 							p.y()-movingObj_start.y() +lmosel->getTopPad() );		
  1293 					else	
  1294 						lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() -lmosel->getTopPad());
  1295 					lmosel->setRelPos();	
  1296 				} 
  1297 
  1298 			} // depth>0
  1299 				// Maybe we can relink temporary?
  1300 				if (dsti)
  1301 				{
  1302 					if (e->modifiers()==Qt::ControlModifier)
  1303 					{
  1304 						// Special case: CTRL to link below dst
  1305 						lmosel->setParObjTmp (dst,p,+1);
  1306 					} else if (e->modifiers()==Qt::ShiftModifier)
  1307 						lmosel->setParObjTmp (dst,p,-1);
  1308 					else
  1309 						lmosel->setParObjTmp (dst,p,0);
  1310 				} else	
  1311 				{
  1312 					lmosel->unsetParObjTmp();
  1313 				}		
  1314 				// reposition subbranch
  1315 				lmosel->reposition();	
  1316 
  1317 			QItemSelection sel=model->getSelectionModel()->selection();
  1318 			updateSelection(sel,sel);	// position has changed
  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 		 tmpXLink->setEnd (p);
  1330 		 tmpXLink->updateXLink();
  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 			tmpXLink->setEnd ( ((BranchItem*)dsti) );
  1384 			tmpXLink->updateXLink();
  1385 			tmpXLink->activate(); 
  1386 			model->saveState(
  1387 				tmpXLink,QString("delete ()"),
  1388 				dsti,QString("addXLink (\"%1\",\"%2\")").arg(model->getSelectString(tmpXLink->getBegin())).arg(model->getSelectString(dsti)),
  1389 				QString("Add xLink from %1 to %2").arg(model->getObjectName(tmpXLink->getBegin())).arg(model->getObjectName(dsti)) 
  1390 			);	
  1391 		} else
  1392 		{
  1393 			model->deleteItem(tmpXLink);
  1394 			tmpXLink=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::resizeEvent (QResizeEvent* e)
  1580 {
  1581 	QGraphicsView::resizeEvent( e );
  1582 }
  1583 
  1584 void MapEditor::dragEnterEvent(QDragEnterEvent *event)
  1585 {
  1586 	//for (unsigned int i=0;event->format(i);i++) // Debug mime type
  1587 	//	cerr << event->format(i) << endl;
  1588 
  1589 	if (event->mimeData()->hasImage())
  1590 		event->acceptProposedAction();
  1591 	else	
  1592 		if (event->mimeData()->hasUrls())
  1593 			event->acceptProposedAction();
  1594 }
  1595 
  1596 void MapEditor::dragMoveEvent(QDragMoveEvent *)
  1597 {
  1598 }
  1599 
  1600 void MapEditor::dragLeaveEvent(QDragLeaveEvent *event)
  1601 {
  1602 	event->accept();
  1603 }
  1604 
  1605 void MapEditor::dropEvent(QDropEvent *event)
  1606 {
  1607 	BranchItem *selbi=model->getSelectedBranch();
  1608 	if (selbi)
  1609 	{
  1610 		if (debug)
  1611 		{
  1612 			foreach (QString format,event->mimeData()->formats()) 
  1613 				qDebug()<< "MapEditor: Dropped format: "<<qPrintable (format);
  1614 			foreach (QString url,event->mimeData()->urls())
  1615 				qDebug()<< "  URL:"<<url;
  1616 			//foreach (QString plain,event->mimeData()->text())
  1617 			//	qDebug()<< "   PLAIN:"<<plain;
  1618 			QByteArray ba=event->mimeData()->data("STRING");
  1619 			
  1620 			QString s;
  1621 			s=ba;
  1622 			qDebug() << "  STRING:" <<s;
  1623 
  1624 			ba=event->mimeData()->data("TEXT");
  1625 			s=ba;
  1626 			qDebug() << "    TEXT:" <<s;
  1627 
  1628 			ba=event->mimeData()->data("COMPOUND_TEXT");
  1629 			s=ba;
  1630 			qDebug() << "   CTEXT:" <<s;
  1631 
  1632 			ba=event->mimeData()->data("text/x-moz-url");
  1633 			s=ba;
  1634 			qDebug() << "   x-moz-url:" <<s;
  1635 			foreach (char b,ba)
  1636 				if (b!=0) qDebug() << "b="<<b;
  1637 		}
  1638 
  1639 		if (event->mimeData()->hasImage()) 
  1640 		{
  1641 			 QVariant imageData = event->mimeData()->imageData();
  1642 			 model->addFloatImage (qvariant_cast<QPixmap>(imageData));
  1643 		} else
  1644 		if (event->mimeData()->hasUrls())
  1645 		{
  1646 			//model->selectLastBranch();
  1647 			QList <QUrl> uris=event->mimeData()->urls();
  1648 			QStringList files;
  1649 			QString s;
  1650 			QString heading;
  1651 			BranchItem *bi;
  1652 			for (int i=0; i<uris.count();i++)
  1653 			{
  1654 				// Workaround to avoid adding empty branches
  1655 				if (!uris.at(i).toString().isEmpty())
  1656 				{
  1657 					bi=model->addNewBranch();
  1658 					if (bi)
  1659 					{
  1660 						model->select(bi);
  1661 						QString u=uris.at(i).toString();
  1662 						s=uris.at(i).toLocalFile();
  1663 						if (!s.isEmpty()) 
  1664 						{
  1665 						   QString file = QDir::fromNativeSeparators(s);
  1666 						   heading = QFileInfo(file).baseName();
  1667 						   files.append(file);
  1668 						   if (file.endsWith(".vym", false))
  1669 							   model->setVymLink(file);
  1670 						   else
  1671 							   model->setURL(u);
  1672 					   } else 
  1673 					   {
  1674 							model->setURL(u);
  1675 
  1676 /*
  1677 							// Automatically try to fetch data from Bugzilla
  1678 							if (settings.value( "/mainwindow/showTestMenu",false).toBool() 
  1679 								&& u.contains ("https://bugzilla.novell.com"))
  1680 								model->getBugzillaData();
  1681 */								
  1682 					   }
  1683 
  1684 					   if (!heading.isEmpty())
  1685 						   model->setHeading(heading);
  1686 					   else
  1687 						   model->setHeading(u);
  1688 						   
  1689 						model->select (bi->parent());	   
  1690 					}
  1691 				}
  1692 			}
  1693 			//model->reposition();
  1694 		}
  1695 	}	
  1696 	event->acceptProposedAction();
  1697 }
  1698 
  1699 void MapEditor::updateSelection(QItemSelection newsel,QItemSelection oldsel)
  1700 {
  1701 	// Note: Here we are prepared for multiple selections, though this 
  1702 	// is not yet implemented elsewhere
  1703 
  1704 	// Here in MapEditor we can only select Branches and Images
  1705 	QList <TreeItem*> treeItemsNew;
  1706 	QList <TreeItem*> treeItemsOld;
  1707 
  1708 	QModelIndex newIndex;
  1709 
  1710 	bool do_reposition=false;
  1711 
  1712 	QModelIndex ix;
  1713 	foreach (ix,newsel.indexes() )
  1714 	{
  1715 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1716 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1717 			if (!treeItemsNew.contains(ti)) treeItemsNew.append (ti);
  1718 	}
  1719 	foreach (ix,oldsel.indexes() )
  1720 	{
  1721 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1722 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1723 			if (!treeItemsOld.contains(ti)) treeItemsOld.append (ti);
  1724 	}
  1725 
  1726 	// Trim list of selection rectangles 
  1727 	while (treeItemsNew.count() < selboxList.count() )
  1728 		delete selboxList.takeFirst();
  1729 
  1730 	// Take care to tmp scroll/unscroll
  1731 	if (!oldsel.isEmpty())
  1732 	{
  1733 		QModelIndex ix=oldsel.indexes().first(); 
  1734 		if (ix.isValid() )
  1735 		{
  1736 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1737 			if (ti)
  1738 			{
  1739 				if (ti->isBranchLikeType() )
  1740 				{
  1741 					// reset tmp scrolled branches
  1742 					BranchItem *bi=(BranchItem*)ti;
  1743 					if (bi->resetTmpUnscroll() )
  1744 						do_reposition=true;
  1745 				}
  1746 				if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1747 					// Hide link if not needed
  1748 					((MapItem*)ti)->getLMO()->updateVisibility();
  1749 			}
  1750 		}
  1751 	}
  1752 
  1753 	if (!treeItemsNew.isEmpty())
  1754 	{
  1755 		QModelIndex ix=newsel.indexes().first(); 
  1756 		if (ix.isValid() )
  1757 		{
  1758 			newIndex=ix;
  1759 
  1760 			// Temporary unscroll if necessary
  1761 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1762 			if (ti->isBranchLikeType() )
  1763 			{
  1764 				BranchItem *bi=(BranchItem*)ti;
  1765 				if (bi->hasScrolledParent(bi) )
  1766 				{
  1767 					if (bi->parentBranch()->tmpUnscroll() )
  1768 						do_reposition=true;
  1769 				}	
  1770 			}
  1771 			if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1772 				// Show link if needed
  1773 				((MapItem*)ti)->getLMO()->updateVisibility();
  1774 		}
  1775 	}
  1776 	if (do_reposition) model->reposition();
  1777 
  1778 	// Reduce rectangles
  1779 	while (treeItemsNew.count() < selboxList.count() )
  1780 		delete selboxList.takeFirst();
  1781 
  1782 	// Add additonal rectangles
  1783 	QGraphicsRectItem *sb;
  1784 	while (treeItemsNew.count() > selboxList.count() )
  1785 	{
  1786 		sb = mapScene->addRect(
  1787 			QRectF(0,0,0,0), 
  1788 			QPen(selectionColor),
  1789 			selectionColor);
  1790 		sb->setZValue(Z_SELBOX);
  1791 		sb->show();
  1792 		selboxList.append (sb);
  1793 	}
  1794 
  1795 	// Reposition rectangles
  1796 	QRectF bbox;
  1797 	QModelIndex index;
  1798 
  1799 	LinkableMapObj *lmo;
  1800 	for (int i=0; i<treeItemsNew.count();++i)
  1801 	{
  1802 		lmo=((MapItem*)treeItemsNew.at(i) )->getLMO();
  1803 		bbox=lmo->getBBox();
  1804 		sb=selboxList.at(i);
  1805 		sb->setRect (
  1806 			bbox.x(),bbox.y(), 
  1807 			bbox.width(), bbox.height());
  1808 		sb->setPen (selectionColor);	
  1809 		sb->setBrush (selectionColor);	
  1810 		i++;
  1811 	}
  1812 
  1813 	scene()->update();  
  1814 }
  1815 
  1816 void MapEditor::updateData (const QModelIndex &sel)
  1817 {
  1818 	TreeItem *ti= static_cast<TreeItem*>(sel.internalPointer());
  1819 
  1820 /* testing
  1821 	qDebug() << "ME::updateData\n";
  1822 
  1823 	qDebug() << "  ti="<<ti;
  1824 	qDebug() << "  h="<<ti->getHeading();
  1825 	*/
  1826 	
  1827 	if (ti->isBranchLikeType())
  1828 	{
  1829 	//	qDebug() << "  ->updating...\n";
  1830 		BranchObj *bo=(BranchObj*) ( ((MapItem*)ti)->getLMO());
  1831 		bo->updateData();
  1832 	}
  1833 }
  1834 
  1835 void MapEditor::setSelectionColor (QColor col)
  1836 {
  1837 	selectionColor=col;
  1838 	QItemSelection sel=model->getSelectionModel()->selection();
  1839 	updateSelection(sel,sel);
  1840 }
  1841 
  1842 
  1843 QColor MapEditor::getSelectionColor ()
  1844 {
  1845 	return selectionColor;
  1846 }
  1847 
  1848