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