mapeditor.cpp
author insilmaril
Thu, 03 Dec 2009 22:32:24 +0000
changeset 814 31de6677aa96
parent 810 a9295db4dcbf
child 815 2881c4424190
permissions -rw-r--r--
Feature: Better handling of xLinks
     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=="system-note")
  1049 				mainWindow->windowToggleNoteEditor();
  1050 			else if (foname=="hideInExport")		
  1051 				model->toggleHideExport();
  1052 			// FIXME-3 needed? xelection.update();	
  1053 			return;	
  1054 		} else
  1055 		{
  1056 			// Take care of xLink
  1057 			if (ti->xlinkCount()>0 && lmo->getBBox().width()>30)
  1058 			{
  1059 				if ((lmo->getOrientation()==LinkableMapObj::RightOfCenter && p.x() > lmo->getBBox().right()-20)  ||
  1060 				    (lmo->getOrientation()==LinkableMapObj::LeftOfCenter && p.x() < lmo->getBBox().left()+20) ) 
  1061 				{
  1062 					if (ti->xlinkCount()>1)
  1063 					{
  1064 						QMenu menu;
  1065 						QList <QAction*> alist;
  1066 						for (int i=0;i<ti->xlinkCount();i++)
  1067 							alist.append (new QAction(ti->getXLinkNum(i)->getOtherBranch(ti)->getHeading(),&menu));
  1068 						menu.addActions (alist);	
  1069 						QAction *ra=menu.exec (e->globalPos() );
  1070 						if (ra)
  1071 							model->select (ti->getXLinkNum(alist.indexOf(ra))->getOtherBranch (ti));
  1072 						while (!alist.isEmpty())
  1073 						{
  1074 							QAction *a=alist.takeFirst();
  1075 							delete a;
  1076 						}	
  1077 						return;
  1078 					} else
  1079 					{
  1080 						model->select (ti->getXLinkNum(0)->getOtherBranch (ti));
  1081 						return;
  1082 					}
  1083 				}	
  1084 			}
  1085 		}
  1086 	}	
  1087 
  1088 	// No system flag clicked, take care of modmodes (CTRL-Click)
  1089 	if (e->state() & Qt::ControlModifier)
  1090 	{
  1091 		if (mainWindow->getModMode()==Main::ModModeColor)
  1092 		{
  1093 				pickingColor=true;
  1094 				setCursor (PickColorCursor);
  1095 				return;
  1096 		} 
  1097 		if (mainWindow->getModMode()==Main::ModModeXLink)
  1098 		{	
  1099 			BranchItem *bi_begin=model->getSelectedBranch();
  1100 			if (bi_begin)	
  1101 			{
  1102 				drawingLink=true;
  1103 				tmpXLink=model->createXLink(bi_begin,true);
  1104 				tmpXLink->setColor(model->getMapDefXLinkColor());
  1105 				tmpXLink->setWidth(model->getMapDefXLinkWidth());
  1106 				tmpXLink->setEnd   (p);
  1107 				tmpXLink->updateXLink();
  1108 				return;
  1109 			} 
  1110 		}
  1111 	}	// End of modmodes
  1112 
  1113     if (lmo) 
  1114 	{	
  1115 	/*
  1116 		cout << "ME::mouse pressed\n";
  1117 		cout << "  lmo="<<lmo<<endl;
  1118 		cout << "   ti="<<ti->getHeadingStd()<<endl;
  1119 	*/
  1120 		// Select the clicked object
  1121 
  1122 		// Get clicked LMO
  1123 		model->select (ti);
  1124 
  1125 		// Left Button	    Move Branches
  1126 		if (e->button() == Qt::LeftButton )
  1127 		{
  1128 			movingObj_start.setX( p.x() - lmo->x() );	
  1129 			movingObj_start.setY( p.y() - lmo->y() );	
  1130 			movingObj_orgPos.setX (lmo->x() );
  1131 			movingObj_orgPos.setY (lmo->y() );
  1132 			lmo->setRelPos();
  1133 			movingObj_orgRelPos=lmo->getRelPos();
  1134 
  1135 			// If modMode==copy, then we want to "move" the _new_ object around
  1136 			// then we need the offset from p to the _old_ selection, because of tmp
  1137 			if (mainWindow->getModMode()==Main::ModModeCopy &&
  1138 				e->state() & Qt::ControlModifier)
  1139 			{
  1140 				BranchItem *bi=model->getSelectedBranch();
  1141 				if (bi)
  1142 				{
  1143 					copyingObj=true;
  1144 					//FIXME-2   TreeItem::addBranch (BranchItem still missing) 
  1145 					//bi->addBranch (model->getSelectedBranch());
  1146 					model->unselect();
  1147 					model->select(bi->getLastBranch());
  1148 					model->reposition();
  1149 				}
  1150 			} 
  1151 
  1152 			movingObj=model->getSelectedLMO();	
  1153 		} else
  1154 			// Middle Button    Toggle Scroll
  1155 			// (On Mac OS X this won't work, but we still have 
  1156 			// a button in the toolbar)
  1157 			if (e->button() == Qt::MidButton )
  1158 				model->toggleScroll();
  1159 		// model->updateActions(); FIXME-3 needed?
  1160 		// FIXME-3 needed? xelection.update();
  1161 	} else 
  1162 	{ // No MapObj found, we are on the scene itself
  1163 		// Left Button	    move Pos of sceneView
  1164 		if (e->button() == Qt::LeftButton )
  1165 		{
  1166 			movingObj=NULL;	// move Content not Obj
  1167 			movingObj_start=e->globalPos();
  1168 			movingCont_start=QPointF (
  1169 				horizontalScrollBar()->value(),
  1170 				verticalScrollBar()->value());
  1171 			movingVec=QPointF(0,0);
  1172 			setCursor(HandOpenCursor);
  1173 		} 
  1174     } 
  1175 }
  1176 
  1177 void MapEditor::mouseMoveEvent(QMouseEvent* e)
  1178 {
  1179     QPointF p = mapToScene(e->pos());
  1180 	TreeItem *seli=model->getSelectedItem();
  1181 	LinkableMapObj* lmosel=NULL;	
  1182 	if (seli && (seli->isBranchLikeType() ||seli->getType()==TreeItem::Image))
  1183 		lmosel=((MapItem*)seli)->getLMO();
  1184 
  1185     // Move the selected MapObj
  1186     if ( lmosel && movingObj) 
  1187     {	
  1188 		objectMoved=true;
  1189 		// reset cursor if we are moving and don't copy
  1190 		if (mainWindow->getModMode()!=Main::ModModeCopy)
  1191 			setCursor (Qt::ArrowCursor);
  1192 
  1193 		// To avoid jumping of the sceneView, only 
  1194 		// show selection, if not tmp linked
  1195 		/* FIXME-2 if (!lmosel->hasParObjTmp())
  1196 			model->emitShowSelection();
  1197 			*/
  1198 		
  1199 		// Now move the selection, but add relative position 
  1200 		// (movingObj_start) where selection was chosen with 
  1201 		// mousepointer. (This avoids flickering resp. jumping 
  1202 		// of selection back to absPos)
  1203 		
  1204 		// Check if we could link 
  1205 		TreeItem *ti=findMapItem (p, seli);
  1206 		BranchItem *dsti=NULL;
  1207 		LinkableMapObj* dst=NULL;
  1208 		if (ti && ti!=seli && ti->isBranchLikeType())
  1209 		{
  1210 			dsti=(BranchItem*)ti;
  1211 			dst=dsti->getLMO(); 
  1212 		} else
  1213 			dsti=NULL;
  1214 		
  1215 
  1216 		if (lmosel && seli->getType()==TreeItem::Image)	
  1217 		{
  1218 			FloatObj *fio=(FloatImageObj*)lmosel;
  1219 			fio->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  1220 			fio->setRelPos();
  1221 			fio->updateLinkGeometry(); //no need for reposition, if we update link here
  1222 			model->emitSelectionChanged();	// position has changed
  1223 
  1224 			// Relink float to new mapcenter or branch, if shift is pressed	
  1225 			// Only relink, if selection really has a new parent
  1226 			if ( e->modifiers()==Qt::ShiftModifier && dsti &&  dsti != seli->parent()  )
  1227 			{
  1228 				// Also save the move which was done so far
  1229 				QString pold=qpointFToString(movingObj_orgRelPos);
  1230 				QString pnow=qpointFToString(fio->getRelPos());
  1231 				model->saveState(
  1232 					seli,
  1233 					"moveRel "+pold,
  1234 					seli,
  1235 					"moveRel "+pnow,
  1236 					QString("Move %1 to relative position %2").arg(model->getObjectName(fio)).arg(pnow));
  1237 				fio->getParObj()->requestReposition();
  1238 				model->reposition();
  1239 
  1240 				model->relinkImage ((ImageItem*) seli,dsti);
  1241 				model->select (seli);
  1242 				//movingObj=lmosel;	//FIXME-3
  1243 				//movingObj_orgRelPos=lmosel->getRelPos();	
  1244 
  1245 				model->reposition();
  1246 			}
  1247 		} else	
  1248 		{	// selection != a FloatObj
  1249 			if (seli->depth()==0)		
  1250 			{
  1251 				// Move mapcenter
  1252 				lmosel->move   (p-movingObj_start);		
  1253 				if (e->buttons()== Qt::LeftButton && e->modifiers()==Qt::ShiftModifier) 
  1254 				{
  1255 					// Move only mapcenter, leave its children where they are
  1256 					QPointF v;
  1257 					v=lmosel->getAbsPos();
  1258 					for (int i=0; i<seli->branchCount(); ++i)
  1259 					{
  1260 						seli->getBranchObjNum(i)->setRelPos();
  1261 						seli->getBranchObjNum(i)->setOrientation();
  1262 					}
  1263 				}	
  1264 			} else
  1265 			{	
  1266 				if (seli->depth()==1)
  1267 				{
  1268 					// Move mainbranch
  1269 					if (!lmosel->hasParObjTmp())
  1270 						lmosel->move(p-movingObj_start);		
  1271 					lmosel->setRelPos();
  1272 				} else
  1273 				{
  1274 					// Move ordinary branch
  1275 					if (lmosel->getOrientation() == LinkableMapObj::LeftOfCenter)
  1276 						// Add width of bbox here, otherwise alignRelTo will cause jumping around
  1277 						lmosel->move(p.x() -movingObj_start.x() , //lmosel->getBBox().width(), 
  1278 							p.y()-movingObj_start.y() +lmosel->getTopPad() );		
  1279 					else	
  1280 						lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() -lmosel->getTopPad());
  1281 					lmosel->setRelPos();	
  1282 				} 
  1283 
  1284 			} // depth>0
  1285 				// Maybe we can relink temporary?
  1286 				if (dsti)	// FIXME-1 check if dsti is ancestor of myself!
  1287 				{
  1288 					if (e->modifiers()==Qt::ControlModifier)
  1289 					{
  1290 						// Special case: CTRL to link below dst
  1291 						lmosel->setParObjTmp (dst,p,+1);
  1292 					} else if (e->modifiers()==Qt::ShiftModifier)
  1293 						lmosel->setParObjTmp (dst,p,-1);
  1294 					else
  1295 						lmosel->setParObjTmp (dst,p,0);
  1296 				} else	
  1297 				{
  1298 					lmosel->unsetParObjTmp();
  1299 				}		
  1300 				// reposition subbranch
  1301 				lmosel->reposition();	
  1302 
  1303 			QItemSelection sel=model->getSelectionModel()->selection();
  1304 			updateSelection(sel,sel);	// position has changed
  1305 
  1306 		} // no FloatImageObj
  1307 
  1308 		scene()->update();
  1309 		return;
  1310 	} // selection && moving_obj
  1311 		
  1312 	// Draw a link from one branch to another
  1313 	if (drawingLink)
  1314 	{
  1315 		 tmpXLink->setEnd (p);
  1316 		 tmpXLink->updateXLink();
  1317 	}	 
  1318 	
  1319     // Move sceneView 
  1320     if (!movingObj && !pickingColor &&!drawingLink && e->buttons() == Qt::LeftButton ) 
  1321 	{
  1322 		QPointF p=e->globalPos();
  1323 		movingVec.setX(-p.x() + movingObj_start.x() );
  1324 		movingVec.setY(-p.y() + movingObj_start.y() );
  1325 		horizontalScrollBar()->setSliderPosition((int)( movingCont_start.x()+movingVec.x() ));
  1326 		verticalScrollBar()->setSliderPosition((int)( movingCont_start.y()+movingVec.y() ) );
  1327     }
  1328 }
  1329 
  1330 
  1331 void MapEditor::mouseReleaseEvent(QMouseEvent* e)
  1332 {
  1333     QPointF p = mapToScene(e->pos());
  1334 	TreeItem *seli=model->getSelectedItem();
  1335 
  1336 	TreeItem *dsti=NULL;
  1337 	if (seli) dsti=findMapItem(p, seli);
  1338 	LinkableMapObj* dst=NULL;
  1339 	if (dsti && dsti->isBranchLikeType ()) 
  1340 		dst=((MapItem*)dsti)->getLMO();	
  1341 	else
  1342 		dsti=NULL;
  1343 
  1344 
  1345 	// Have we been picking color?
  1346 	if (pickingColor)
  1347 	{
  1348 		pickingColor=false;
  1349 		setCursor (Qt::ArrowCursor);
  1350 		// Check if we are over another branch
  1351 		if (dst) 
  1352 		{	
  1353 			if (e->state() & Qt::ShiftModifier)
  1354 				model->colorBranch (((BranchObj*)dst)->getColor());
  1355 			else	
  1356 				model->colorSubtree (((BranchObj*)dst)->getColor());
  1357 		} 
  1358 		return;
  1359 	}
  1360 
  1361 	// Have we been drawing a link?
  1362 	if (drawingLink)	
  1363 	{
  1364 		drawingLink=false;
  1365 		// Check if we are over another branch
  1366 		if (dsti)
  1367 		{	
  1368 			tmpXLink->setEnd ( ((BranchItem*)dsti) );
  1369 			tmpXLink->updateXLink();
  1370 			tmpXLink->activate(); 
  1371 			model->saveState(
  1372 				tmpXLink,QString("delete ()"),
  1373 				dsti,QString("addXLink (\"%1\",\"%2\")").arg(model->getSelectString(tmpXLink->getBegin())).arg(model->getSelectString(dsti)),
  1374 				QString("Add xLink from %1 to %2").arg(model->getObjectName(tmpXLink->getBegin())).arg(model->getObjectName(dsti)) 
  1375 			);	
  1376 		} else
  1377 		{
  1378 			model->deleteItem(tmpXLink);
  1379 			tmpXLink=NULL;
  1380 		}
  1381 		return;
  1382 	}
  1383 	
  1384     // Have we been moving something?
  1385     if ( seli && movingObj ) 
  1386     {	
  1387 		if (seli->getType()==TreeItem::Image)
  1388 		{
  1389 			FloatImageObj *fio=(FloatImageObj*)( ((MapItem*)seli)->getLMO());
  1390 			if(fio)
  1391 			{
  1392 				// Moved FloatObj. Maybe we need to reposition
  1393 				QString pold=qpointFToString(movingObj_orgRelPos);
  1394 				QString pnow=qpointFToString(fio->getRelPos());
  1395 				model->saveState(
  1396 					seli,
  1397 					"moveRel "+pold,
  1398 					seli,
  1399 					"moveRel "+pnow,
  1400 					QString("Move %1 to relative position %2").arg(model->getObjectName(seli)).arg(pnow));
  1401 
  1402 				cout << "ME::release mouse\n";
  1403 				fio->getParObj()->requestReposition();
  1404 				model->reposition();
  1405 			}	
  1406 		}
  1407 
  1408 		BranchItem *bi=model->getSelectedBranch();
  1409 		if (bi && bi->depth()==0)
  1410 		{	
  1411             if (movingObj_orgPos != bi->getBranchObj()->getAbsPos())	// FIXME-3 check getBO here...
  1412             {
  1413                 QString pold=qpointFToString(movingObj_orgPos);
  1414                 QString pnow=qpointFToString(bi->getBranchObj()->getAbsPos());		// FIXME-3 check getBO here...
  1415 
  1416                 model->saveState(
  1417                     bi,
  1418                     "move "+pold,
  1419                     bi,
  1420                     "move "+pnow,
  1421                     QString("Move mapcenter %1 to position %2").arg(model->getObjectName(bi)).arg(pnow));
  1422             }
  1423 		}
  1424 	
  1425 		if (seli->isBranchLikeType() ) //(seli->getType() == TreeItem::Branch )
  1426 		{	// A branch was moved
  1427 			LinkableMapObj* lmosel=NULL;		
  1428 			lmosel=((MapItem*)seli)->getLMO();
  1429 				
  1430 			// save the position in case we link to mapcenter
  1431 			QPointF savePos=QPointF (lmosel->getAbsPos()  );
  1432 
  1433 			// Reset the temporary drawn link to the original one
  1434 			lmosel->unsetParObjTmp();
  1435 
  1436 			// For Redo we may need to save original selection
  1437 			QString preSelStr=model->getSelectString(seli);
  1438 
  1439 			copyingObj=false;	
  1440 			if (dsti && objectMoved)
  1441 			{
  1442 				// We have a destination, relink to that
  1443 
  1444 				BranchObj* bsel=model->getSelectedBranchObj();
  1445 
  1446 				QString preParStr=model->getSelectString (bsel->getParObj());
  1447 				QString preNum=QString::number (seli->num(),10);
  1448 				QString preDstParStr;
  1449 				bool relinked;
  1450 
  1451 				if (e->state() & Qt::ShiftModifier && dst->getParObj())
  1452 				{	// Link above dst
  1453 					preDstParStr=model->getSelectString (dst->getParObj());
  1454 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti->parent(),((BranchItem*)dsti)->num());
  1455 				} else 
  1456 				if (e->state() & Qt::ControlModifier && dst->getParObj())
  1457 				{
  1458 					// Link below dst
  1459 					preDstParStr=model->getSelectString (dst->getParObj());
  1460 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti->parent(),((BranchItem*)dsti)->num()+1);
  1461 				} else	
  1462 				{	// Append to dst
  1463 					preDstParStr=model->getSelectString(dst);
  1464 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti);
  1465 					if (dsti->depth()==0) bsel->move (savePos);
  1466 				} 
  1467 				if (relinked)
  1468 				{
  1469 					QString postSelStr=model->getSelectString(lmosel);
  1470 					QString postNum=QString::number (seli->num(),10);
  1471 
  1472 					QString undoCom="relinkTo (\""+ 
  1473 						preParStr+ "\"," + preNum  +"," + 
  1474 						QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+ ")";
  1475 
  1476 					QString redoCom="relinkTo (\""+ 
  1477 						preDstParStr + "\"," + postNum + "," +
  1478 						QString ("%1,%2").arg(savePos.x()).arg(savePos.y())+ ")";
  1479 
  1480 					model->saveState (
  1481 						postSelStr,undoCom,
  1482 						preSelStr, redoCom,
  1483 						QString("Relink %1 to %2").arg(model->getObjectName(bsel)).arg(model->getObjectName(dst)) );
  1484 
  1485 				}
  1486 			} else
  1487 			{
  1488 				// No destination, undo  temporary move	// FIXME-1 animation missing now?
  1489 
  1490 				if (seli->depth()==1)
  1491 				{
  1492 					// The select string might be different _after_ moving around.
  1493 					// Therefor reposition and then use string of old selection, too
  1494 					model->reposition();
  1495 
  1496                     QPointF rp(lmosel->getRelPos());
  1497                     if (rp != movingObj_orgRelPos)
  1498                     {
  1499                         QString ps=qpointFToString(rp);
  1500                         model->saveState(
  1501                             model->getSelectString(lmosel), "moveRel "+qpointFToString(movingObj_orgRelPos), 
  1502                             preSelStr, "moveRel "+ps, 
  1503                             QString("Move %1 to relative position %2").arg(model->getObjectName(lmosel)).arg(ps));
  1504                     }
  1505 				}
  1506 
  1507 				// Draw the original link, before selection was moved around
  1508 				if (settings.value("/animation/use",false).toBool() && seli->depth()>1) 
  1509 				{
  1510 					lmosel->setRelPos();	// calc relPos first for starting point
  1511 					
  1512 					model->startAnimation(
  1513 						(BranchObj*)lmosel,
  1514 						lmosel->getRelPos(),
  1515 						movingObj_orgRelPos
  1516 					);	
  1517 				} else	
  1518 					model->reposition();
  1519 			}
  1520 		}
  1521 		model->emitSelectionChanged();  //FIXME-3 needed? at least not after pos of selection has changed...
  1522 		// Finally resize scene, if needed
  1523 		scene()->update();
  1524 		movingObj=NULL;		
  1525 		objectMoved=false;
  1526 
  1527 	} else 
  1528 		// maybe we moved View: set old cursor
  1529 		setCursor (Qt::ArrowCursor);
  1530     
  1531 }
  1532 
  1533 void MapEditor::mouseDoubleClickEvent(QMouseEvent* e)
  1534 {
  1535 	if (debug) 
  1536 	{
  1537 		cout << "ME p="<<mapToScene (e->pos())<<"  scrollBarPos="<<getScrollBarPos();
  1538 		cout << "  min="<<QPointF(horizontalScrollBar()->minimum(),verticalScrollBar()->minimum());
  1539 		cout << endl;
  1540 	}
  1541 
  1542 
  1543 	if (model->isSelectionBlocked() ) 
  1544 	{
  1545 		e->ignore();
  1546 		return;
  1547 	}
  1548 
  1549 	if (e->button() == Qt::LeftButton )
  1550 	{
  1551 		QPointF p = mapToScene(e->pos());
  1552 		TreeItem *ti=findMapItem (p, NULL);
  1553 		if (ti) {	// MapObj was found
  1554 			// First select the MapObj than edit heading
  1555 			model->select (ti);
  1556 			editHeading();
  1557 		}
  1558 	}
  1559 }
  1560 
  1561 void MapEditor::resizeEvent (QResizeEvent* e)
  1562 {
  1563 	QGraphicsView::resizeEvent( e );
  1564 }
  1565 
  1566 void MapEditor::dragEnterEvent(QDragEnterEvent *event)
  1567 {
  1568 	//for (unsigned int i=0;event->format(i);i++) // Debug mime type
  1569 	//	cerr << event->format(i) << endl;
  1570 
  1571 	if (event->mimeData()->hasImage())
  1572 		event->acceptProposedAction();
  1573 	else	
  1574 		if (event->mimeData()->hasUrls())
  1575 			event->acceptProposedAction();
  1576 }
  1577 
  1578 void MapEditor::dragMoveEvent(QDragMoveEvent *)
  1579 {
  1580 }
  1581 
  1582 void MapEditor::dragLeaveEvent(QDragLeaveEvent *event)
  1583 {
  1584 	event->accept();
  1585 }
  1586 
  1587 void MapEditor::dropEvent(QDropEvent *event)
  1588 {
  1589 	BranchItem *selbi=model->getSelectedBranch();
  1590 	if (selbi)
  1591 	{
  1592 		if (debug)
  1593 			foreach (QString format,event->mimeData()->formats()) 
  1594 				cout << "MapEditor: Dropped format: "<<qPrintable (format)<<endl;
  1595 
  1596 
  1597 		QList <QUrl> uris;
  1598 		if (event->mimeData()->hasImage()) 
  1599 		{
  1600 			 QVariant imageData = event->mimeData()->imageData();
  1601 			 model->addFloatImage (qvariant_cast<QPixmap>(imageData));
  1602 		} else
  1603 		if (event->mimeData()->hasUrls())
  1604 			uris=event->mimeData()->urls();
  1605 
  1606 		if (uris.count()>0)
  1607 		{
  1608 			QStringList files;
  1609 			QString s;
  1610 			QString heading;
  1611 			BranchItem *bi;
  1612 			for (int i=0; i<uris.count();i++)
  1613 			{
  1614 				// Workaround to avoid adding empty branches
  1615 				if (!uris.at(i).toString().isEmpty())
  1616 				{
  1617 					bi=model->addNewBranch();
  1618 					if (bi)
  1619 					{
  1620 						   /* FIXME-2 
  1621 						s=uris.at(i).toLocalFile();
  1622 						if (!s.isEmpty()) 
  1623 						{
  1624 						   QString file = QDir::fromNativeSeparators(s);
  1625 						   heading = QFileInfo(file).baseName();
  1626 						   files.append(file);
  1627 						   if (file.endsWith(".vym", false))
  1628 							   bi->setVymLink(file);
  1629 						   else
  1630 							   bi->setURL(uris.at(i).toString());
  1631 					   } else 
  1632 					   {
  1633 						   bo->setURL(uris.at(i).toString());
  1634 					   }
  1635 							 */  
  1636 
  1637 					   if (!heading.isEmpty())
  1638 						   bi->setHeading(heading);
  1639 					   else
  1640 						   bi->setHeading(uris.at(i).toString());
  1641 						   
  1642 					}
  1643 				}
  1644 			}
  1645 			model->reposition();
  1646 		}
  1647 	}	
  1648 	event->acceptProposedAction();
  1649 }
  1650 
  1651 void MapEditor::updateSelection(QItemSelection newsel,QItemSelection oldsel)
  1652 {
  1653 	// Note: Here we are prepared for multiple selections, though this 
  1654 	// is not yet implemented elsewhere
  1655 
  1656 	// Here in MapEditor we can only select Branches and Images
  1657 	QList <TreeItem*> treeItemsNew;
  1658 	QList <TreeItem*> treeItemsOld;
  1659 
  1660 	QModelIndex newIndex;
  1661 
  1662 	bool do_reposition=false;
  1663 
  1664 	QModelIndex ix;
  1665 	foreach (ix,newsel.indexes() )
  1666 	{
  1667 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1668 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1669 			if (!treeItemsNew.contains(ti)) treeItemsNew.append (ti);
  1670 	}
  1671 	foreach (ix,oldsel.indexes() )
  1672 	{
  1673 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1674 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1675 			if (!treeItemsOld.contains(ti)) treeItemsOld.append (ti);
  1676 	}
  1677 
  1678 	// Trim list of selection rectangles 
  1679 	while (treeItemsNew.count() < selboxList.count() )
  1680 		delete selboxList.takeFirst();
  1681 
  1682 	// Take care to tmp scroll/unscroll
  1683 	if (!oldsel.isEmpty())
  1684 	{
  1685 		QModelIndex ix=oldsel.indexes().first(); 
  1686 		if (ix.isValid() )
  1687 		{
  1688 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1689 			if (ti)
  1690 			{
  1691 				if (ti->isBranchLikeType() )
  1692 				{
  1693 					// reset tmp scrolled branches
  1694 					BranchItem *bi=(BranchItem*)ti;
  1695 					if (bi->resetTmpUnscroll() )
  1696 						do_reposition=true;
  1697 				}
  1698 				if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1699 					// Hide link if not needed
  1700 					((MapItem*)ti)->getLMO()->updateVisibility();
  1701 			}
  1702 		}
  1703 	}
  1704 
  1705 	if (!treeItemsNew.isEmpty())
  1706 	{
  1707 		QModelIndex ix=newsel.indexes().first(); 
  1708 		if (ix.isValid() )
  1709 		{
  1710 			newIndex=ix;
  1711 
  1712 			// Temporary unscroll if necessary
  1713 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1714 			if (ti->isBranchLikeType() )
  1715 			{
  1716 				BranchItem *bi=(BranchItem*)ti;
  1717 				if (bi->hasScrolledParent(bi) )
  1718 				{
  1719 					if (bi->parentBranch()->tmpUnscroll() )
  1720 						do_reposition=true;
  1721 				}	
  1722 			}
  1723 			if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1724 				// Show link if needed
  1725 				((MapItem*)ti)->getLMO()->updateVisibility();
  1726 		}
  1727 	}
  1728 	if (do_reposition) model->reposition();
  1729 
  1730 	// Reduce rectangles
  1731 	while (treeItemsNew.count() < selboxList.count() )
  1732 		delete selboxList.takeFirst();
  1733 
  1734 	// Add additonal rectangles
  1735 	QGraphicsRectItem *sb;
  1736 	while (treeItemsNew.count() > selboxList.count() )
  1737 	{
  1738 		sb = mapScene->addRect(
  1739 			QRectF(0,0,0,0), 
  1740 			QPen(selectionColor),
  1741 			selectionColor);
  1742 		sb->setZValue(Z_SELBOX);
  1743 		sb->show();
  1744 		selboxList.append (sb);
  1745 	}
  1746 
  1747 	// Reposition rectangles
  1748 	QRectF bbox;
  1749 	QModelIndex index;
  1750 
  1751 	LinkableMapObj *lmo;
  1752 	for (int i=0; i<treeItemsNew.count();++i)
  1753 	{
  1754 		lmo=((MapItem*)treeItemsNew.at(i) )->getLMO();
  1755 		bbox=lmo->getBBox();
  1756 		sb=selboxList.at(i);
  1757 		sb->setRect (
  1758 			bbox.x(),bbox.y(), 
  1759 			bbox.width(), bbox.height());
  1760 		sb->setPen (selectionColor);	
  1761 		sb->setBrush (selectionColor);	
  1762 		i++;
  1763 	}
  1764 
  1765 	scene()->update();  
  1766 }
  1767 
  1768 void MapEditor::updateData (const QModelIndex &sel)
  1769 {
  1770 	TreeItem *ti= static_cast<TreeItem*>(sel.internalPointer());
  1771 
  1772 /* testing
  1773 	cout << "ME::updateData\n";
  1774 
  1775 	cout << "  ti="<<ti<<endl;
  1776 	cout << "  h="<<ti->getHeading().toStdString()<<endl;
  1777 	*/
  1778 	
  1779 	if (ti->isBranchLikeType())
  1780 	{
  1781 	//	cout << "  ->updating...\n";
  1782 		BranchObj *bo=(BranchObj*) ( ((MapItem*)ti)->getLMO());
  1783 		bo->updateData();
  1784 	}
  1785 }
  1786 
  1787 void MapEditor::setSelectionColor (QColor col)
  1788 {
  1789 	selectionColor=col;
  1790 	QItemSelection sel=model->getSelectionModel()->selection();
  1791 	updateSelection(sel,sel);
  1792 }
  1793 
  1794 
  1795 QColor MapEditor::getSelectionColor ()
  1796 {
  1797 	return selectionColor;
  1798 }
  1799 
  1800