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