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