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