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