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