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