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