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