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