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