mapeditor.cpp
author insilmaril
Thu, 25 Feb 2010 11:03:52 +0000
changeset 824 36eb4b8f409e
parent 823 0bba81dde1bc
child 834 0fad394bc330
permissions -rw-r--r--
Added dialog for HTML export. Grouping in Switchboard shortcuts
     1 #include "mapeditor.h"
     2 
     3 #include <iostream>	
     4 
     5 #include <QObject>
     6 
     7 #include "branchitem.h"
     8 #include "geometry.h"
     9 #include "mainwindow.h"
    10 #include "misc.h"
    11 #include "warningdialog.h"
    12 #include "xlinkitem.h"
    13 
    14 
    15 extern int statusbarTime;
    16 extern Main *mainWindow;
    17 extern QString tmpVymDir;
    18 extern QString clipboardDir;
    19 extern QString clipboardFile;
    20 extern bool clipboardEmpty;
    21 extern bool debug;
    22 
    23 extern QMenu* branchContextMenu;
    24 extern QMenu* floatimageContextMenu;
    25 extern QMenu* canvasContextMenu;
    26 
    27 extern Settings settings;
    28 extern QString iconPath;
    29 
    30 ///////////////////////////////////////////////////////////////////////
    31 ///////////////////////////////////////////////////////////////////////
    32 MapEditor::MapEditor( VymModel *vm) 
    33 {
    34 	//cout << "Constructor ME "<<this<<endl;
    35 	mapScene= new QGraphicsScene(NULL);
    36 	mapScene->setBackgroundBrush (QBrush(Qt::white, Qt::SolidPattern));
    37 
    38 	zoomFactor=zoomFactorTarget=1;
    39 
    40 	model=vm;
    41 	model->setScene (mapScene);
    42 	model->registerEditor(this);
    43 	model->makeDefault();	// No changes in model so far
    44 
    45     setScene (mapScene);
    46 
    47     printer=NULL;
    48 
    49 	// Create bitmap cursors, platform dependant
    50 	HandOpenCursor=QCursor (QPixmap(iconPath+"cursorhandopen.png"),1,1);		
    51 	PickColorCursor=QCursor ( QPixmap(iconPath+"cursorcolorpicker.png"), 5,27 ); 
    52 	CopyCursor=QCursor ( QPixmap(iconPath+"cursorcopy.png"), 1,1 ); 
    53 	XLinkCursor=QCursor ( QPixmap(iconPath+"cursorxlink.png"), 1,7 ); 
    54 
    55 	//setFocusPolicy (Qt::StrongFocus);	//FIXME-3
    56 
    57 	pickingColor=false;
    58 	drawingLink=false;
    59 	copyingObj=false;
    60 	objectMoved=false;
    61 
    62     editingBO=NULL;
    63     movingObj=NULL;
    64 
    65 	printFrame=true;
    66 	printFooter=true;
    67 
    68 	setAcceptDrops (true);	
    69 
    70 	//model->reposition();	//FIXME-3 really still needed?
    71 
    72 
    73 	// Shortcuts and actions
    74 	QAction *a;
    75     a = new QAction("Select upper branch", this);
    76 	a->setShortcut (Qt::Key_Up );
    77 	a->setShortcutContext (Qt::WidgetShortcut);
    78 	addAction (a);
    79     connect( a, SIGNAL( triggered() ), this, SLOT( cursorUp() ) );
    80 
    81     a = new QAction( "Select lower branch",this);
    82 	a->setShortcut ( Qt::Key_Down );
    83 	a->setShortcutContext (Qt::WidgetShortcut);
    84 	addAction (a);
    85     connect( a, SIGNAL( triggered() ), this, SLOT( cursorDown() ) );
    86 
    87     a = new QAction( "Select left branch", this);
    88 	a->setShortcut (Qt::Key_Left );
    89 //	a->setShortcutContext (Qt::WindowShortcut);
    90 //	a->setShortcutContext (Qt::WidgetWithChildrenShortcut);
    91 	addAction (a);
    92     connect( a, SIGNAL( triggered() ), this, SLOT( cursorLeft() ) );
    93 
    94     a = new QAction( "Select child branch", this);
    95 	a->setShortcut (Qt::Key_Right);
    96 //	a->setShortcutContext (Qt::WidgetWithChildrenShortcut);
    97 	addAction (a);
    98     connect( a, SIGNAL( triggered() ), this, SLOT( cursorRight() ) );
    99 
   100     a = new QAction(  "Select first branch", this);
   101 	a->setShortcut (Qt::Key_Home );
   102 	a->setShortcutContext (Qt::WidgetWithChildrenShortcut);
   103 	addAction (a);
   104     connect( a, SIGNAL( triggered() ), this, SLOT( cursorFirst() ) );
   105 
   106     a = new QAction( "Select last branch",this);
   107 	a->setShortcut ( Qt::Key_End );
   108 	a->setShortcutContext (Qt::WidgetWithChildrenShortcut);
   109 	addAction (a);
   110     connect( a, SIGNAL( triggered() ), this, SLOT( cursorLast() ) );
   111 
   112 	// Action to embed LineEdit for heading in Scene
   113 	editingHeading=false;
   114 	lineEdit=NULL;
   115 
   116 	a = new QAction( tr( "Edit heading","MapEditor" ), this);
   117 	a->setShortcut ( Qt::Key_Return );					//Edit heading
   118 	a->setShortcutContext (Qt::WidgetShortcut);
   119 	addAction (a);
   120     connect( a, SIGNAL( triggered() ), this, SLOT( editHeading() ) );
   121 	a = new QAction( tr( "Edit heading","MapEditor" ), this);
   122 	a->setShortcut ( Qt::Key_Enter);					//Edit heading
   123 	addAction (a);
   124     connect( a, SIGNAL( triggered() ), this, SLOT( editHeading() ) );
   125 
   126 	// Selections
   127 	selectionColor =QColor (255,255,0);
   128 	
   129 
   130 	// Attributes	//FIXME-2 testing only...
   131 	QString k;
   132 	AttributeDef *ad;
   133 	attrTable= new AttributeTable();
   134 	k="A - StringList";
   135 	ad=attrTable->addKey (k,StringList);
   136 	if (ad)
   137 	{
   138 		QStringList sl;
   139 		sl <<"val 1"<<"val 2"<< "val 3";
   140 		ad->setValue (QVariant (sl));
   141 	}
   142 	//attrTable->addValue ("Key A","P 1");
   143 	//attrTable->addValue ("Key A","P 2");
   144 	//attrTable->addValue ("Key A","P 3");
   145 	//attrTable->addValue ("Key A","P 4");
   146 	k="B - FreeString";
   147 	ad=attrTable->addKey (k,FreeString);
   148 	if (ad)
   149 	{
   150 		//attrTable->addValue ("Key B","w1");
   151 		//attrTable->addValue ("Key B","w2");
   152 	}
   153 	k="C - UniqueString";
   154 	ad=attrTable->addKey (k,UniqueString);
   155 	if (ad)
   156 	{
   157 	//attrTable->addKey ("Key Prio");
   158 	//attrTable->addValue ("Key Prio","Prio 1");
   159 	//attrTable->addValue ("Key Prio","Prio 2");
   160 	}
   161 }
   162 
   163 MapEditor::~MapEditor()
   164 {
   165 	//cout <<"Destructor MapEditor for "<<model->getMapName().toStdString()<<endl;
   166 	model->unregisterEditor(this);
   167 }
   168 
   169 VymModel* MapEditor::getModel()
   170 {
   171     return model;
   172 }
   173 
   174 QGraphicsScene * MapEditor::getScene()
   175 {
   176     return mapScene;
   177 }
   178 
   179 void MapEditor::scrollTo (const QModelIndex &index)	
   180 {
   181 	if (index.isValid())
   182 	{
   183 		LinkableMapObj* lmo=NULL;
   184 		TreeItem *ti= static_cast<TreeItem*>(index.internalPointer());
   185 		if (ti->getType()==TreeItem::Image ||ti->isBranchLikeType() )
   186 			lmo=((MapItem*)ti)->getLMO();
   187 		if (lmo) 
   188 		{
   189 			QRectF r=lmo->getBBox();
   190 			setScrollBarPosTarget (r);
   191 		}	
   192 	}
   193 }
   194 
   195 void MapEditor::setScrollBarPosTarget (const QRectF &rect)
   196 {
   197 	// Code copied from Qt sources
   198 	int xmargin=50;
   199 	int ymargin=50;
   200 
   201     qreal width = viewport()->width();
   202     qreal height = viewport()->height();
   203     QRectF viewRect = matrix().mapRect(rect);
   204 
   205     qreal left = horizontalScrollBar()->value();
   206     qreal right = left + width;
   207     qreal top = verticalScrollBar()->value();
   208     qreal bottom = top + height;
   209 
   210 	scrollBarPosTarget=getScrollBarPos();
   211 
   212     if (viewRect.left() <= left + xmargin) {
   213         // need to scroll from the left
   214   //      if (!d->leftIndent)
   215             scrollBarPosTarget.setX(int(viewRect.left() - xmargin - 0.5));
   216     }
   217     if (viewRect.right() >= right - xmargin) {
   218         // need to scroll from the right
   219 //        if (!d->leftIndent)
   220             scrollBarPosTarget.setX(int(viewRect.right() - width + xmargin + 0.5));
   221     }
   222     if (viewRect.top() <= top + ymargin) {
   223         // need to scroll from the top
   224    //     if (!d->topIndent)
   225             scrollBarPosTarget.setY(int(viewRect.top() - ymargin - 0.5));
   226     }
   227     if (viewRect.bottom() >= bottom - ymargin) {
   228         // need to scroll from the bottom
   229 //        if (!d->topIndent)
   230             scrollBarPosTarget.setY(int(viewRect.bottom() - height + ymargin + 0.5));
   231     }
   232 
   233 	if (scrollBarPosTarget==getScrollBarPos()) return;
   234 
   235 	if (scrollBarPosAnimation.state()==QtAbstractAnimation::Running)
   236 		scrollBarPosAnimation.stop();
   237 	
   238 	if (settings.value ("/animation/use/",true).toBool() )
   239 	{
   240 		scrollBarPosAnimation.setTargetObject (this);
   241 		scrollBarPosAnimation.setPropertyName ("scrollBarPos");
   242 		scrollBarPosAnimation.setDuration(1000);
   243 		scrollBarPosAnimation.setEasingCurve ( QtEasingCurve::OutQuint);
   244 		scrollBarPosAnimation.setStartValue(
   245 			QPointF (horizontalScrollBar()->value() ,
   246 					 verticalScrollBar()->value() ) );
   247 		scrollBarPosAnimation.setEndValue(scrollBarPosTarget);
   248 		scrollBarPosAnimation.start();
   249 	} else
   250 		setScrollBarPos (scrollBarPosTarget);
   251 }
   252 
   253 QPointF MapEditor::getScrollBarPosTarget()
   254 {
   255     return scrollBarPosTarget;
   256 }
   257 
   258 
   259 void MapEditor::setScrollBarPos(const QPointF &p)
   260 {
   261     scrollBarPos=p;
   262 	horizontalScrollBar()->setValue(int(p.x()));
   263 	verticalScrollBar()->setValue(int(p.y()));
   264 }
   265 
   266 QPointF MapEditor::getScrollBarPos()
   267 {
   268 	return QPointF (horizontalScrollBar()->value(),verticalScrollBar()->value());
   269     //return scrollBarPos;
   270 }
   271 
   272 void MapEditor::setZoomFactorTarget (const qreal &zft)
   273 {
   274 	zoomFactorTarget=zft;
   275 	if (zoomAnimation.state()==QtAbstractAnimation::Running)
   276 		zoomAnimation.stop();
   277 	if (settings.value ("/animation/use/",true).toBool() )
   278 	{
   279 		//zoomAnimation=QPropertyAnimation(this, "zoomFactor");
   280 		zoomAnimation.setTargetObject (this);
   281 		zoomAnimation.setPropertyName ("zoomFactor");
   282 		zoomAnimation.setDuration(1000);
   283 		zoomAnimation.setEasingCurve ( QtEasingCurve::OutQuint);
   284 		zoomAnimation.setStartValue(zoomFactor);
   285 		zoomAnimation.setEndValue(zft);
   286 		zoomAnimation.start();
   287 	} else
   288 		setZoomFactor (zft);
   289 }
   290 
   291 qreal MapEditor::getZoomFactorTarget()
   292 {
   293     return zoomFactorTarget;
   294 }
   295 
   296 
   297 void MapEditor::setZoomFactor(const qreal &zf)
   298 {
   299     zoomFactor=zf;
   300 	setMatrix (QMatrix(zf, 0, 0, zf, 0, 0),false );
   301 }
   302 
   303 qreal MapEditor::getZoomFactor()
   304 {
   305     return zoomFactor;
   306 }
   307 
   308 void MapEditor::print()
   309 {
   310 	if ( !printer ) 
   311 	{
   312 		printer = new QPrinter;
   313 		printer->setColorMode (QPrinter::Color);
   314 		printer->setPrinterName (settings.value("/mainwindow/printerName",printer->printerName()).toString());
   315 		printer->setOutputFormat((QPrinter::OutputFormat)settings.value("/mainwindow/printerFormat",printer->outputFormat()).toInt());
   316 		printer->setOutputFileName(settings.value("/mainwindow/printerFileName",printer->outputFileName()).toString());
   317 	}
   318 
   319 	QRectF totalBBox=getTotalBBox();
   320 
   321 	// Try to set orientation automagically
   322 	// Note: Interpretation of generated postscript is amibiguous, if 
   323 	// there are problems with landscape mode, see
   324 	// http://sdb.suse.de/de/sdb/html/jsmeix_print-cups-landscape-81.html
   325 
   326 	if (totalBBox.width()>totalBBox.height())
   327 		// recommend landscape
   328 		printer->setOrientation (QPrinter::Landscape);
   329 	else	
   330 		// recommend portrait
   331 		printer->setOrientation (QPrinter::Portrait);
   332 
   333 	if ( printer->setup(this) ) 
   334 	// returns false, if printing is canceled
   335 	{
   336 		QPainter pp(printer);
   337 
   338 		pp.setRenderHint(QPainter::Antialiasing,true);
   339 
   340 		// Don't print the visualisation of selection
   341 		model->unselect();
   342 
   343 		QRectF mapRect=totalBBox;
   344 		QGraphicsRectItem *frame=NULL;
   345 
   346 		if (printFrame) 
   347 		{
   348 			// Print frame around map
   349 			mapRect.setRect (totalBBox.x()-10, totalBBox.y()-10, 
   350 				totalBBox.width()+20, totalBBox.height()+20);
   351 			frame=mapScene->addRect (mapRect, QPen(Qt::black),QBrush(Qt::NoBrush));
   352 			frame->setZValue(0);
   353 			frame->show();    
   354 		}		
   355 
   356 
   357 		double paperAspect = (double)printer->width()   / (double)printer->height();
   358 		double   mapAspect = (double)mapRect.width() / (double)mapRect.height();
   359 		int viewBottom;
   360 		if (mapAspect>=paperAspect)
   361 		{
   362 			// Fit horizontally to paper width
   363 			//pp.setViewport(0,0, printer->width(),(int)(printer->width()/mapAspect) );	
   364 			viewBottom=(int)(printer->width()/mapAspect);	
   365 		}	else
   366 		{
   367 			// Fit vertically to paper height
   368 			//pp.setViewport(0,0,(int)(printer->height()*mapAspect),printer->height());	
   369 			viewBottom=printer->height();	
   370 		}	
   371 		
   372 		if (printFooter) 
   373 		{
   374 			// Print footer below map
   375 			QFont font;		
   376 			font.setPointSize(10);
   377 			pp.setFont (font);
   378 			QRectF footerBox(0,viewBottom,printer->width(),15);
   379 			// FIXME-3 fileName not any longer available here: pp.drawText ( footerBox,Qt::AlignLeft,"VYM - " +fileName);
   380 			pp.drawText ( footerBox, Qt::AlignRight, QDate::currentDate().toString(Qt::TextDate));
   381 		}
   382 		mapScene->render (
   383 			&pp, 
   384 			QRectF (0,0,printer->width(),printer->height()-15),
   385 			QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height())
   386 		);
   387 		
   388 		// Viewport has paper dimension
   389 		if (frame)  delete (frame);
   390 
   391 		// Restore selection
   392 		model->reselect();
   393 
   394 		// Save settings in vymrc
   395 		settings.writeEntry("/mainwindow/printerName",printer->printerName());
   396 		settings.writeEntry("/mainwindow/printerFormat",printer->outputFormat());
   397 		settings.writeEntry("/mainwindow/printerFileName",printer->outputFileName());
   398 	}
   399 }
   400 
   401 QRectF MapEditor::getTotalBBox()	
   402 {
   403 	QPen pen;
   404 	pen.setWidth (1);
   405 	pen.setCapStyle ( Qt::RoundCap );
   406 
   407 	QRectF rt;
   408 	BranchObj *bo;
   409 	BranchItem *cur=NULL;
   410 	BranchItem *prev=NULL;
   411 	model->nextBranch(cur,prev);
   412 	while (cur) 
   413 	{
   414 		if (!cur->hasHiddenExportParent())
   415 		{
   416 			bo=(BranchObj*)(cur->getLMO());
   417 			if (bo && bo->isVisibleObj())
   418 			{
   419 				bo->calcBBoxSizeWithChildren();
   420 				// FIXME-3 testing
   421 				//QRectF r1=bo->getBBoxSizeWithChildren();
   422 				QRectF r1=bo->getBBox();
   423 				//pen.setColor ( QColor(qrand()%32*8,qrand()%32*8,qrand()%32*8));
   424 				//mapScene->addRect (r1,pen);
   425 
   426 				if (rt.isNull()) rt=r1;
   427 				rt=addBBox (r1, rt);
   428 				//FIXME-2 cout <<"ME: r1="<<r1<<"  "<<cur->getHeadingStd()<<endl;
   429 				//cout <<"    rt="<<rt<<endl;
   430 			}
   431 		}
   432 		model->nextBranch(cur,prev);
   433 	}
   434 	return rt;	
   435 }
   436 
   437 
   438 QImage MapEditor::getImage()
   439 {
   440 	QRectF mapRect=getTotalBBox();
   441 	int w=mapRect.width()+2;
   442 	int h=mapRect.height()+2;
   443 	
   444 	QImage pix (w,h,QImage::Format_RGB32);
   445 
   446 	QPainter pp (&pix);
   447 
   448 	pp.setRenderHints(renderHints());
   449 	mapScene->render (	&pp, 
   450 		QRectF(0,0,w,h),
   451 		QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
   452 	return pix;
   453 }
   454 
   455 
   456 void MapEditor::setAntiAlias (bool b)
   457 {
   458 	setRenderHint(QPainter::Antialiasing,b);
   459 }
   460 
   461 void MapEditor::setSmoothPixmap(bool b)
   462 {
   463 	setRenderHint(QPainter::SmoothPixmapTransform,b);
   464 }
   465 
   466 void MapEditor::setHideTmp (bool b)	// FIXME-4 better use signals
   467 {
   468 /*
   469 	if (b)
   470 	{
   471 		setHideTmpMode (HideExport);
   472 		mapCenter->calcBBoxSizeWithChilds();
   473 		QRectF totalBBox=mapCenter->getTotalBBox();
   474 		//QRectF mapRect=totalBBox;
   475 		cout << "  map has =("<<totalBBox.x()<<","<<totalBBox.y()<<","<<totalBBox.width()<<","<<totalBBox.height()<<")\n";
   476 	
   477 		mapRect.setRect (totalBBox.x(), totalBBox.y(), 
   478 			totalBBox.width(), totalBBox.height());
   479 			
   480 		QCanvasRectangle *frame=new QCanvasRectangle (mapRect,mapScene);
   481 		frame->setBrush (QColor(white));
   482 		frame->setPen (QColor(black));
   483 		frame->setZValue(0);
   484 		frame->show();    
   485 		
   486 	}	
   487 	else	
   488 	{
   489 		setHideTmpMode (HideNone);
   490 	}	
   491 	cout <<"  hidemode="<<hidemode<<endl;
   492 */
   493 /*
   494 	// Toggle hidemode
   495 	if (hidemode==HideExport)
   496 		setHideTmpMode (HideNone);
   497 	else	
   498 		setHideTmpMode (HideExport);
   499 */		
   500 }
   501 
   502 TreeItem* MapEditor::findMapItem (QPointF p,TreeItem *exclude)
   503 {
   504 	// Start with mapcenter, no images allowed at rootItem
   505 	int i=0;
   506 	BranchItem *bi=model->getRootItem()->getFirstBranch();
   507 	TreeItem *found=NULL;
   508 	while (bi)
   509 	{
   510 		found=bi->findMapItem (p, exclude);
   511 		if (found) return found;
   512 		i++;
   513 		bi=model->getRootItem()->getBranchNum(i);
   514 	}
   515 	return NULL;
   516 }
   517 
   518 AttributeTable* MapEditor::attributeTable()
   519 {
   520 	return attrTable;
   521 }
   522 
   523 void MapEditor::testFunction1()
   524 {
   525 	cout << "ME::test1  selected TI="<<model->getSelectedItem()<<endl;
   526 	model->setExportMode (true);
   527 
   528 	/*
   529 	// Code copied from Qt sources
   530 	QRectF rect=model->getSelectedBranchObj()->getBBox();
   531 	int xmargin=50;
   532 	int ymargin=50;
   533 
   534     qreal width = viewport()->width();
   535     qreal height = viewport()->height();
   536     QRectF viewRect = matrix().mapRect(rect);
   537 
   538     qreal left = horizontalScrollBar()->value();
   539     qreal right = left + width;
   540     qreal top = verticalScrollBar()->value();
   541     qreal bottom = top + height;
   542 
   543     if (viewRect.left() <= left + xmargin) {
   544         // need to scroll from the left
   545   //      if (!d->leftIndent)
   546             horizontalScrollBar()->setValue(int(viewRect.left() - xmargin - 0.5));
   547     }
   548     if (viewRect.right() >= right - xmargin) {
   549         // need to scroll from the right
   550 //        if (!d->leftIndent)
   551             horizontalScrollBar()->setValue(int(viewRect.right() - width + xmargin + 0.5));
   552     }
   553     if (viewRect.top() <= top + ymargin) {
   554         // need to scroll from the top
   555    //     if (!d->topIndent)
   556             verticalScrollBar()->setValue(int(viewRect.top() - ymargin - 0.5));
   557     }
   558     if (viewRect.bottom() >= bottom - ymargin) {
   559         // need to scroll from the bottom
   560 //        if (!d->topIndent)
   561             verticalScrollBar()->setValue(int(viewRect.bottom() - height + ymargin + 0.5));
   562     }
   563 	cout << "test1:  hor="<<horizontalScrollBar()->value()<<endl;
   564 	cout << "test1:  ver="<<verticalScrollBar()->value()<<endl;
   565 }
   566 
   567 */
   568 /*
   569 	 QtPropertyAnimation *animation=new QtPropertyAnimation(this, "sceneRect");
   570 	 animation->setDuration(5000);
   571 	 //animation->setEasingCurve ( QtEasingCurve::OutElastic);
   572 	 animation->setEasingCurve ( QtEasingCurve::OutQuint);
   573 	 animation->setStartValue(sceneRect() );
   574 	 animation->setEndValue(QRectF(50, 50, 1000, 1000));
   575 
   576 	 animation->start();
   577 */	 
   578 /*
   579 	QDialog *dia= new QDialog (this);
   580 	dia->setGeometry (50,50,10,10);
   581 
   582      dia->show();
   583      dia ->raise();
   584 
   585 	 QtPropertyAnimation *animation=new QtPropertyAnimation(dia, "geometry");
   586 	 animation->setDuration(1000);
   587 	 //animation->setEasingCurve ( QtEasingCurve::OutElastic);
   588 	 animation->setEasingCurve ( QtEasingCurve::OutQuint);
   589 	 animation->setStartValue(QRect(50, 50, 10, 10));
   590 	 animation->setEndValue(QRect(250, 250, 100, 100));
   591 
   592 	 animation->start();
   593  */
   594 
   595 }
   596 	
   597 void MapEditor::testFunction2()
   598 {
   599 	model->setExportMode (false);
   600 	return;
   601 
   602 	// Create list with all bounding polygons
   603 	QList <LinkableMapObj*> mapobjects;
   604 	QList <ConvexPolygon> polys; 
   605 	ConvexPolygon p;
   606 	QList <Vector> vectors;
   607 	QList <Vector> orgpos;
   608 	QStringList headings;	//FIXME-3 testing only
   609 	Vector v;
   610 	BranchItem *bi;
   611 	BranchItem *bi2;
   612 	BranchObj *bo;
   613 
   614 	// Outer loop: Iterate until we no more changes in orientation 
   615 	bool orientationChanged=true;
   616 	while (orientationChanged)
   617 	{
   618 		BranchItem *ri=model->getRootItem();
   619 		for (int i=0;i<ri->branchCount();++i)
   620 		{
   621 			bi=ri->getBranchNum (i);
   622 			bo=(BranchObj*)bi->getLMO();
   623 			if (bo)
   624 			{
   625 				mapobjects.append (bo);
   626 				p=bo->getBoundingPolygon();
   627 				p.calcCentroid();
   628 				polys.append(p);
   629 				vectors.append (QPointF(0,0));
   630 				orgpos.append (p.at(0));
   631 				headings.append (bi->getHeading());
   632 			}
   633 			for (int j=0;j<bi->branchCount();++j)
   634 			{
   635 				bi2=bi->getBranchNum (j);
   636 				bo=(BranchObj*)bi2->getLMO();
   637 				if (bo)
   638 				{
   639 					mapobjects.append (bo);
   640 					p=bo->getBoundingPolygon();
   641 					p.calcCentroid();
   642 					polys.append(p);
   643 					vectors.append (QPointF(0,0));
   644 					orgpos.append (p.at(0));
   645 					headings.append (bi2->getHeading());
   646 				}	
   647 			}
   648 		}
   649 
   650 		// Iterate moving bounding polygons until we have no more collisions
   651 		int collisions=1;
   652 		while (collisions>0)
   653 		{
   654 			collisions=0;
   655 			for (int i=0; i<polys.size()-1; ++i)
   656 			{
   657 				for (int j=i+1; j<polys.size();++j)
   658 				{
   659 					if (polygonCollision (polys.at(i),polys.at(j), QPointF(0,0)).intersect )
   660 					{
   661 						collisions++;
   662 						//cout << "Collision: "<<headings[i].toStdString()<<" - "<<headings[j].toStdString()<<endl;
   663 						v=polys.at(j).centroid()-polys.at(i).centroid();
   664 						// Move also away if centroids are identical
   665 						if (v.isNull()) 
   666 						{
   667 							//cout << "v==0="<<polys[i].centroid()<<polys[j].centroid()<<" "<<v<<endl;
   668 							v.setX (rand()%200 -100);
   669 							v.setY (rand()%200 -100);
   670 							//cout << v;
   671 						}
   672 						v.normalize();
   673 						v.scale (2);
   674 						//cout <<  "  v="<<v<<endl;
   675 						vectors[j]=v;
   676 						vectors[i]=v;
   677 						vectors[i].invert();
   678 					}  
   679 				}
   680 			}
   681 			for (int i=0;i<vectors.size();i++)
   682 			{
   683 				//cout << " v="<<vectors[i]<<" "<<headings[i].toStdString()<<endl;
   684 				polys[i].translate (vectors[i]);
   685 			}
   686 			cout << "Collisions: "<<collisions<<endl;
   687 			//collisions=0;
   688 		}	
   689 
   690 		// Finally move the real objects and update 
   691 		QList <LinkableMapObj::Orientation> orients;
   692 		for (int i=0;i<polys.size();i++)
   693 		{
   694 			Vector v=polys[i].at(0)-orgpos[i];
   695 			orients.append (mapobjects[i]->getOrientation());
   696 			mapobjects[i]->moveBy(v.x(),v.y() );
   697 			mapobjects[i]->setRelPos();
   698 		}	
   699 		model->reposition();	
   700 		orientationChanged=false;
   701 		for (int i=0;i<polys.size();i++)
   702 			if (orients[i]!=mapobjects[i]->getOrientation())
   703 			{
   704 				orientationChanged=true;
   705 				break;
   706 			}
   707 		cout << "Final: orientChanged="<<orientationChanged<<endl;
   708 		break;
   709 		//orientationChanged=false;
   710 	} // loop if orientation has changed
   711 
   712 	model->emitSelectionChanged();
   713 }
   714 
   715 BranchItem* MapEditor::getBranchDirectAbove (BranchItem *bi)
   716 {
   717 	if (bi)
   718 	{
   719 		int i=bi->num();
   720 		if (i>0) return bi->parent()->getBranchNum(i-1);
   721 	}
   722 	return NULL;
   723 }
   724 
   725 BranchItem* MapEditor::getBranchAbove (BranchItem *selbi)
   726 {
   727 	if (selbi)
   728 	{
   729 		int dz=selbi->depth();	// original depth
   730 		bool invert=false;
   731 		if (selbi->getLMO()->getOrientation()==LinkableMapObj::LeftOfCenter)
   732 			invert=true;
   733 
   734 		BranchItem *bi;
   735 
   736 		// Look for branch with same parent but directly above
   737 		if (dz==1 && invert)
   738 			bi=getBranchDirectBelow(selbi);
   739 		else
   740 			bi=getBranchDirectAbove (selbi);
   741 
   742 		if (bi) 
   743 			// direct predecessor
   744 			return bi;
   745 
   746 		// Go towards center and look for predecessor
   747 		while (selbi->depth()>0)
   748 		{
   749 			selbi=(BranchItem*)(selbi->parent());
   750 			if (selbi->depth()==1 && invert)
   751 				bi=getBranchDirectBelow (selbi);
   752 			else
   753 				bi=getBranchDirectAbove (selbi);
   754 			if (bi)
   755 			{
   756 				// turn 
   757 				selbi=bi;
   758 				while (selbi->depth()<dz)
   759 				{
   760 					// try to get back to original depth dz
   761 					bi=selbi->getLastBranch();
   762 					if (!bi) 
   763 					{
   764 						return selbi;
   765 					}
   766 					selbi=bi;
   767 				}
   768 				return selbi;
   769 			}
   770 		}
   771 	}
   772 	return NULL;
   773 }
   774 
   775 BranchItem* MapEditor::getBranchDirectBelow(BranchItem *bi)
   776 {
   777 	if (bi)
   778 	{
   779 		int i=bi->num();
   780 		if (i+1<bi->parent()->branchCount()) return bi->parent()->getBranchNum(i+1);
   781 	}
   782 	return NULL;
   783 }
   784 
   785 BranchItem* MapEditor::getBranchBelow (BranchItem *selbi)
   786 {
   787 	if (selbi)
   788 	{
   789 		BranchItem *bi;
   790 		int dz=selbi->depth();	// original depth
   791 		bool invert=false;
   792 		if (selbi->getLMO()->getOrientation()==LinkableMapObj::LeftOfCenter)
   793 			invert=true;
   794 
   795 
   796 		// Look for branch with same parent but directly below
   797 		if (dz==1 && invert)
   798 			bi=getBranchDirectAbove (selbi);
   799 		else
   800 			bi=getBranchDirectBelow (selbi);
   801 		if (bi) 
   802 			// direct successor
   803 			return bi;
   804 
   805 
   806 		// Go towards center and look for neighbour
   807 		while (selbi->depth()>0)
   808 		{
   809 			selbi=(BranchItem*)(selbi->parent());
   810 			if (selbi->depth()==1 && invert)
   811 				bi=getBranchDirectAbove (selbi);
   812 			else
   813 				bi=getBranchDirectBelow (selbi);
   814 			if (bi)
   815 			{
   816 				// turn 
   817 				selbi=bi;
   818 				while (selbi->depth()<dz)
   819 				{
   820 					// try to get back to original depth dz
   821 					bi=selbi->getFirstBranch();
   822 					if (!bi) 
   823 					{
   824 						return selbi;
   825 					}
   826 					selbi=bi;
   827 				}
   828 				return selbi;
   829 			}
   830 		}
   831 	}
   832 	return NULL;
   833 }
   834 
   835 BranchItem* MapEditor::getLeftBranch (BranchItem *bi)
   836 {
   837 	if (bi)
   838 	{
   839 		if (bi->depth()==0)
   840 			// Special case: use alternative selection index
   841 			return bi->getLastSelectedBranchAlt();	
   842 		if (bi->getBranchObj()->getOrientation()==LinkableMapObj::RightOfCenter)	
   843 			// right of center
   844 			return (BranchItem*)(bi->parent());
   845 		else
   846 			// left of center
   847 			if (bi->getType()== TreeItem::Branch )
   848 				return bi->getLastSelectedBranch();
   849 	}
   850 	return NULL;
   851 }
   852 
   853 BranchItem* MapEditor::getRightBranch(BranchItem *bi)
   854 {
   855 	if (bi)
   856 	{
   857 		if (bi->depth()==0) return bi->getLastSelectedBranch();	
   858 		if (bi->getBranchObj()->getOrientation()==LinkableMapObj::LeftOfCenter)	
   859 			// left of center
   860 			return (BranchItem*)(bi->parent());
   861 		else
   862 			// right of center
   863 			if (bi->getType()== TreeItem::Branch )
   864 				return (BranchItem*)bi->getLastSelectedBranch();
   865 	}
   866 	return NULL;
   867 }
   868 
   869 
   870 
   871 void MapEditor::cursorUp()
   872 {
   873 	BranchItem *bi=model->getSelectedBranch();
   874 	if (bi) model->select (getBranchAbove(bi));
   875 }
   876 
   877 void MapEditor::cursorDown()	
   878 
   879 {
   880 	BranchItem *bi=model->getSelectedBranch();
   881 	if (bi) model->select (getBranchBelow(bi));
   882 }
   883 
   884 void MapEditor::cursorLeft()
   885 {
   886 	BranchItem *bi=getLeftBranch (model->getSelectedBranch());
   887 	if (bi) model->select (bi);
   888 }
   889 
   890 void MapEditor::cursorRight()	
   891 {
   892 	BranchItem *bi=getRightBranch (model->getSelectedBranch());
   893 	if (bi) model->select (bi);
   894 }
   895 
   896 void MapEditor::cursorFirst()	
   897 {
   898 	model->selectFirstBranch();
   899 }
   900 
   901 void MapEditor::cursorLast()	
   902 {
   903 	model->selectLastBranch();
   904 }
   905 
   906 
   907 void MapEditor::editHeading()
   908 {
   909 	if (editingHeading)
   910 	{
   911 		editHeadingFinished();
   912 		return;
   913 	}
   914 	BranchObj *bo=model->getSelectedBranchObj();
   915 	BranchItem *bi=model->getSelectedBranch();
   916 	if (bo)	
   917 	{
   918 		model->setSelectionBlocked(true);
   919 
   920 		lineEdit=new QLineEdit;
   921 		QGraphicsProxyWidget *pw=scene()->addWidget (lineEdit);
   922 		pw->setZValue (Z_LINEEDIT);
   923 
   924 		lineEdit->setText (bi->getHeading());
   925 		QPoint p = mapTo (this,bo->getAbsPos().toPoint() );
   926 		lineEdit->setGeometry(p.x(),p.y(),230,25);
   927 		//lineEdit->selectAll();
   928 		//lineEdit->setCursorPosition (1);
   929 		lineEdit->show();
   930 		lineEdit->setFocus();
   931 		lineEdit->grabKeyboard();
   932 		editingHeading=true;
   933 	}
   934 
   935 }
   936 void MapEditor::editHeadingFinished()
   937 {
   938 	editingHeading=false;
   939 	lineEdit->releaseKeyboard();
   940 	lineEdit->clearFocus();
   941 	QString s=lineEdit->text();
   942 	s.replace (QRegExp ("\\n")," ");	// Don't paste newline chars
   943 	model->setHeading (s);
   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.contains("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 				fio->getParObj()->requestReposition();
  1426 				model->reposition();
  1427 			}	
  1428 		}
  1429 
  1430 		BranchItem *bi=model->getSelectedBranch();
  1431 		if (bi && bi->depth()==0)
  1432 		{	
  1433             if (movingObj_orgPos != bi->getBranchObj()->getAbsPos())	// FIXME-3 check getBO here...
  1434             {
  1435                 QString pold=qpointFToString(movingObj_orgPos);
  1436                 QString pnow=qpointFToString(bi->getBranchObj()->getAbsPos());		// FIXME-3 check getBO here...
  1437 
  1438                 model->saveState(
  1439                     bi,
  1440                     "move "+pold,
  1441                     bi,
  1442                     "move "+pnow,
  1443                     QString("Move mapcenter %1 to position %2").arg(model->getObjectName(bi)).arg(pnow));
  1444             }
  1445 		}
  1446 	
  1447 		if (seli->isBranchLikeType() ) //(seli->getType() == TreeItem::Branch )
  1448 		{	// A branch was moved
  1449 			LinkableMapObj* lmosel=NULL;		
  1450 			lmosel=((MapItem*)seli)->getLMO();
  1451 				
  1452 			// save the position in case we link to mapcenter
  1453 			QPointF savePos=QPointF (lmosel->getAbsPos()  );
  1454 
  1455 			// Reset the temporary drawn link to the original one
  1456 			lmosel->unsetParObjTmp();
  1457 
  1458 			// For Redo we may need to save original selection
  1459 			QString preSelStr=model->getSelectString(seli);
  1460 
  1461 			copyingObj=false;	
  1462 			if (dsti && objectMoved)
  1463 			{
  1464 				// We have a destination, relink to that
  1465 
  1466 				BranchObj* bsel=model->getSelectedBranchObj();
  1467 
  1468 				QString preParStr=model->getSelectString (bsel->getParObj());
  1469 				QString preNum=QString::number (seli->num(),10);
  1470 				QString preDstParStr;
  1471 				bool relinked;
  1472 
  1473 				if (e->state() & Qt::ShiftModifier && dst->getParObj())
  1474 				{	// Link above dst
  1475 					preDstParStr=model->getSelectString (dst->getParObj());
  1476 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti->parent(),((BranchItem*)dsti)->num());
  1477 				} else 
  1478 				if (e->state() & Qt::ControlModifier && dst->getParObj())
  1479 				{
  1480 					// Link below dst
  1481 					preDstParStr=model->getSelectString (dst->getParObj());
  1482 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti->parent(),((BranchItem*)dsti)->num()+1);
  1483 				} else	
  1484 				{	// Append to dst
  1485 					preDstParStr=model->getSelectString(dst);
  1486 					relinked=model->relinkBranch ((BranchItem*)seli,(BranchItem*)dsti);
  1487 					if (dsti->depth()==0) bsel->move (savePos);
  1488 				} 
  1489 				if (relinked)
  1490 				{
  1491 					QString postSelStr=model->getSelectString(lmosel);
  1492 					QString postNum=QString::number (seli->num(),10);
  1493 
  1494 					QString undoCom="relinkTo (\""+ 
  1495 						preParStr+ "\"," + preNum  +"," + 
  1496 						QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+ ")";
  1497 
  1498 					QString redoCom="relinkTo (\""+ 
  1499 						preDstParStr + "\"," + postNum + "," +
  1500 						QString ("%1,%2").arg(savePos.x()).arg(savePos.y())+ ")";
  1501 
  1502 					model->saveState (
  1503 						postSelStr,undoCom,
  1504 						preSelStr, redoCom,
  1505 						QString("Relink %1 to %2").arg(model->getObjectName(bsel)).arg(model->getObjectName(dst)) );
  1506 
  1507 				}
  1508 			} else
  1509 			{
  1510 				// No destination, undo  temporary move	
  1511 
  1512 				if (seli->depth()==1)
  1513 				{
  1514 					// The select string might be different _after_ moving around.
  1515 					// Therefor reposition and then use string of old selection, too
  1516 					model->reposition();
  1517 
  1518                     QPointF rp(lmosel->getRelPos());
  1519                     if (rp != movingObj_orgRelPos)
  1520                     {
  1521                         QString ps=qpointFToString(rp);
  1522                         model->saveState(
  1523                             model->getSelectString(lmosel), "moveRel "+qpointFToString(movingObj_orgRelPos), 
  1524                             preSelStr, "moveRel "+ps, 
  1525                             QString("Move %1 to relative position %2").arg(model->getObjectName(lmosel)).arg(ps));
  1526                     }
  1527 				}
  1528 
  1529 				// Draw the original link, before selection was moved around
  1530 				if (settings.value("/animation/use",true).toBool() 
  1531 					&& seli->depth()>1
  1532 //					&& distance (lmosel->getRelPos(),movingObj_orgRelPos)<3
  1533 				) 
  1534 				{
  1535 					lmosel->setRelPos();	// calc relPos first for starting point
  1536 					
  1537 					model->startAnimation(
  1538 						(BranchObj*)lmosel,
  1539 						lmosel->getRelPos(),
  1540 						movingObj_orgRelPos
  1541 					);	
  1542 				} else	
  1543 					model->reposition();
  1544 			}
  1545 		}
  1546 		model->emitSelectionChanged();  //FIXME-3 needed? at least not after pos of selection has changed...
  1547 		// Finally resize scene, if needed
  1548 		scene()->update();
  1549 		movingObj=NULL;		
  1550 		objectMoved=false;
  1551 
  1552 	} else 
  1553 		// maybe we moved View: set old cursor
  1554 		setCursor (Qt::ArrowCursor);
  1555     
  1556 }
  1557 
  1558 void MapEditor::mouseDoubleClickEvent(QMouseEvent* e)
  1559 {
  1560 	if (debug) 
  1561 	{
  1562 		cout << "ME p="<<mapToScene (e->pos())<<"  scrollBarPos="<<getScrollBarPos();
  1563 		cout << "  min="<<QPointF(horizontalScrollBar()->minimum(),verticalScrollBar()->minimum());
  1564 		cout << endl;
  1565 	}
  1566 
  1567 
  1568 	if (model->isSelectionBlocked() ) 
  1569 	{
  1570 		e->ignore();
  1571 		return;
  1572 	}
  1573 
  1574 	if (e->button() == Qt::LeftButton )
  1575 	{
  1576 		QPointF p = mapToScene(e->pos());
  1577 		TreeItem *ti=findMapItem (p, NULL);
  1578 		if (ti) {	// MapObj was found
  1579 			// First select the MapObj than edit heading
  1580 			model->select (ti);
  1581 			editHeading();
  1582 		}
  1583 	}
  1584 }
  1585 
  1586 void MapEditor::resizeEvent (QResizeEvent* e)
  1587 {
  1588 	QGraphicsView::resizeEvent( e );
  1589 }
  1590 
  1591 void MapEditor::dragEnterEvent(QDragEnterEvent *event)
  1592 {
  1593 	//for (unsigned int i=0;event->format(i);i++) // Debug mime type
  1594 	//	cerr << event->format(i) << endl;
  1595 
  1596 	if (event->mimeData()->hasImage())
  1597 		event->acceptProposedAction();
  1598 	else	
  1599 		if (event->mimeData()->hasUrls())
  1600 			event->acceptProposedAction();
  1601 }
  1602 
  1603 void MapEditor::dragMoveEvent(QDragMoveEvent *)
  1604 {
  1605 }
  1606 
  1607 void MapEditor::dragLeaveEvent(QDragLeaveEvent *event)
  1608 {
  1609 	event->accept();
  1610 }
  1611 
  1612 void MapEditor::dropEvent(QDropEvent *event)
  1613 {
  1614 	BranchItem *selbi=model->getSelectedBranch();
  1615 	if (selbi)
  1616 	{
  1617 		if (debug)
  1618 		{
  1619 			foreach (QString format,event->mimeData()->formats()) 
  1620 				cout << "MapEditor: Dropped format: "<<qPrintable (format)<<endl;
  1621 			foreach (QString url,event->mimeData()->urls())
  1622 				cout << "  URL:"<<url.toStdString()<<endl;
  1623 			//foreach (QString plain,event->mimeData()->text())
  1624 			//	cout << "   PLAIN:"<<plain.toStdString()<<endl;
  1625 			QByteArray ba=event->mimeData()->data("STRING");
  1626 			
  1627 			QString s;
  1628 			s=ba;
  1629 			cout << "  STRING:" <<s.toStdString()<<endl;
  1630 
  1631 			ba=event->mimeData()->data("TEXT");
  1632 			s=ba;
  1633 			cout << "    TEXT:" <<s.toStdString()<<endl;
  1634 
  1635 			ba=event->mimeData()->data("COMPOUND_TEXT");
  1636 			s=ba;
  1637 			cout << "   CTEXT:" <<s.toStdString()<<endl;
  1638 
  1639 			ba=event->mimeData()->data("text/x-moz-url");
  1640 			s=ba;
  1641 			cout << "   x-moz-url:" <<s.toStdString()<<endl;
  1642 			foreach (char b,ba)
  1643 				if (b!=0) cout << "b="<<b<<endl;
  1644 		}
  1645 
  1646 		if (event->mimeData()->hasImage()) 
  1647 		{
  1648 			 QVariant imageData = event->mimeData()->imageData();
  1649 			 model->addFloatImage (qvariant_cast<QPixmap>(imageData));
  1650 		} else
  1651 		if (event->mimeData()->hasUrls())
  1652 		{
  1653 			//model->selectLastBranch();
  1654 			QList <QUrl> uris=event->mimeData()->urls();
  1655 			QStringList files;
  1656 			QString s;
  1657 			QString heading;
  1658 			BranchItem *bi;
  1659 			for (int i=0; i<uris.count();i++)
  1660 			{
  1661 				// Workaround to avoid adding empty branches
  1662 				if (!uris.at(i).toString().isEmpty())
  1663 				{
  1664 					bi=model->addNewBranch();
  1665 					if (bi)
  1666 					{
  1667 						model->select(bi);
  1668 						QString u=uris.at(i).toString();
  1669 						s=uris.at(i).toLocalFile();
  1670 						if (!s.isEmpty()) 
  1671 						{
  1672 						   QString file = QDir::fromNativeSeparators(s);
  1673 						   heading = QFileInfo(file).baseName();
  1674 						   files.append(file);
  1675 						   if (file.endsWith(".vym", false))
  1676 							   model->setVymLink(file);
  1677 						   else
  1678 							   model->setURL(u);
  1679 					   } else 
  1680 					   {
  1681 							model->setURL(u);
  1682 
  1683 /*
  1684 							// Automatically try to fetch data from Bugzilla
  1685 							if (settings.value( "/mainwindow/showTestMenu",false).toBool() 
  1686 								&& u.contains ("https://bugzilla.novell.com"))
  1687 								model->getBugzillaData();
  1688 */								
  1689 					   }
  1690 
  1691 					   if (!heading.isEmpty())
  1692 						   model->setHeading(heading);
  1693 					   else
  1694 						   model->setHeading(u);
  1695 						   
  1696 						model->select (bi->parent());	   
  1697 					}
  1698 				}
  1699 			}
  1700 			//model->reposition();
  1701 		}
  1702 	}	
  1703 	event->acceptProposedAction();
  1704 }
  1705 
  1706 void MapEditor::updateSelection(QItemSelection newsel,QItemSelection oldsel)
  1707 {
  1708 	// Note: Here we are prepared for multiple selections, though this 
  1709 	// is not yet implemented elsewhere
  1710 
  1711 	// Here in MapEditor we can only select Branches and Images
  1712 	QList <TreeItem*> treeItemsNew;
  1713 	QList <TreeItem*> treeItemsOld;
  1714 
  1715 	QModelIndex newIndex;
  1716 
  1717 	bool do_reposition=false;
  1718 
  1719 	QModelIndex ix;
  1720 	foreach (ix,newsel.indexes() )
  1721 	{
  1722 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1723 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1724 			if (!treeItemsNew.contains(ti)) treeItemsNew.append (ti);
  1725 	}
  1726 	foreach (ix,oldsel.indexes() )
  1727 	{
  1728 		TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1729 		if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image )
  1730 			if (!treeItemsOld.contains(ti)) treeItemsOld.append (ti);
  1731 	}
  1732 
  1733 	// Trim list of selection rectangles 
  1734 	while (treeItemsNew.count() < selboxList.count() )
  1735 		delete selboxList.takeFirst();
  1736 
  1737 	// Take care to tmp scroll/unscroll
  1738 	if (!oldsel.isEmpty())
  1739 	{
  1740 		QModelIndex ix=oldsel.indexes().first(); 
  1741 		if (ix.isValid() )
  1742 		{
  1743 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1744 			if (ti)
  1745 			{
  1746 				if (ti->isBranchLikeType() )
  1747 				{
  1748 					// reset tmp scrolled branches
  1749 					BranchItem *bi=(BranchItem*)ti;
  1750 					if (bi->resetTmpUnscroll() )
  1751 						do_reposition=true;
  1752 				}
  1753 				if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1754 					// Hide link if not needed
  1755 					((MapItem*)ti)->getLMO()->updateVisibility();
  1756 			}
  1757 		}
  1758 	}
  1759 
  1760 	if (!treeItemsNew.isEmpty())
  1761 	{
  1762 		QModelIndex ix=newsel.indexes().first(); 
  1763 		if (ix.isValid() )
  1764 		{
  1765 			newIndex=ix;
  1766 
  1767 			// Temporary unscroll if necessary
  1768 			TreeItem *ti= static_cast<TreeItem*>(ix.internalPointer());
  1769 			if (ti->isBranchLikeType() )
  1770 			{
  1771 				BranchItem *bi=(BranchItem*)ti;
  1772 				if (bi->hasScrolledParent(bi) )
  1773 				{
  1774 					if (bi->parentBranch()->tmpUnscroll() )
  1775 						do_reposition=true;
  1776 				}	
  1777 			}
  1778 			if (ti->isBranchLikeType() || ti->getType()==TreeItem::Image)
  1779 				// Show link if needed
  1780 				((MapItem*)ti)->getLMO()->updateVisibility();
  1781 		}
  1782 	}
  1783 	if (do_reposition) model->reposition();
  1784 
  1785 	// Reduce rectangles
  1786 	while (treeItemsNew.count() < selboxList.count() )
  1787 		delete selboxList.takeFirst();
  1788 
  1789 	// Add additonal rectangles
  1790 	QGraphicsRectItem *sb;
  1791 	while (treeItemsNew.count() > selboxList.count() )
  1792 	{
  1793 		sb = mapScene->addRect(
  1794 			QRectF(0,0,0,0), 
  1795 			QPen(selectionColor),
  1796 			selectionColor);
  1797 		sb->setZValue(Z_SELBOX);
  1798 		sb->show();
  1799 		selboxList.append (sb);
  1800 	}
  1801 
  1802 	// Reposition rectangles
  1803 	QRectF bbox;
  1804 	QModelIndex index;
  1805 
  1806 	LinkableMapObj *lmo;
  1807 	for (int i=0; i<treeItemsNew.count();++i)
  1808 	{
  1809 		lmo=((MapItem*)treeItemsNew.at(i) )->getLMO();
  1810 		bbox=lmo->getBBox();
  1811 		sb=selboxList.at(i);
  1812 		sb->setRect (
  1813 			bbox.x(),bbox.y(), 
  1814 			bbox.width(), bbox.height());
  1815 		sb->setPen (selectionColor);	
  1816 		sb->setBrush (selectionColor);	
  1817 		i++;
  1818 	}
  1819 
  1820 	scene()->update();  
  1821 }
  1822 
  1823 void MapEditor::updateData (const QModelIndex &sel)
  1824 {
  1825 	TreeItem *ti= static_cast<TreeItem*>(sel.internalPointer());
  1826 
  1827 /* testing
  1828 	cout << "ME::updateData\n";
  1829 
  1830 	cout << "  ti="<<ti<<endl;
  1831 	cout << "  h="<<ti->getHeading().toStdString()<<endl;
  1832 	*/
  1833 	
  1834 	if (ti->isBranchLikeType())
  1835 	{
  1836 	//	cout << "  ->updating...\n";
  1837 		BranchObj *bo=(BranchObj*) ( ((MapItem*)ti)->getLMO());
  1838 		bo->updateData();
  1839 	}
  1840 }
  1841 
  1842 void MapEditor::setSelectionColor (QColor col)
  1843 {
  1844 	selectionColor=col;
  1845 	QItemSelection sel=model->getSelectionModel()->selection();
  1846 	updateSelection(sel,sel);
  1847 }
  1848 
  1849 
  1850 QColor MapEditor::getSelectionColor ()
  1851 {
  1852 	return selectionColor;
  1853 }
  1854 
  1855