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