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