mapeditor.cpp
author insilmaril
Tue Mar 14 14:27:04 2006 +0000 (2006-03-14)
changeset 239 bdeb503d2b7f
parent 228 654ad4b03c5a
child 243 fad762341d2d
permissions -rw-r--r--
hideLinkInExport for Branches (Floats still missing). Floats are now OrnamentedObj.
     1 #include "mapeditor.h"
     2 
     3 #include <qstatusbar.h>
     4 #include <qmessagebox.h>
     5 #include <qapplication.h>
     6 #include <qpainter.h>
     7 #include <qpopupmenu.h>
     8 #include <qprinter.h>
     9 #include <qpaintdevicemetrics.h>
    10 #include <qfile.h>
    11 #include <qfiledialog.h>
    12 #include <qdir.h>
    13 #include <qcolor.h>
    14 #include <qcolordialog.h>
    15 #include <qbitmap.h>
    16 #include <qprocess.h>
    17 #include <qinputdialog.h>
    18 #include <qdragobject.h>
    19 #include <qurloperator.h>
    20 #include <qnetworkprotocol.h>
    21 #include <qregexp.h>
    22 
    23 #include <iostream>
    24 #include <cstdlib>
    25 #include <typeinfo>
    26 
    27 #include "version.h"
    28 
    29 #include "api.h"
    30 #include "editxlinkdialog.h"
    31 #include "exports.h"
    32 #include "extrainfodialog.h"
    33 #include "file.h"
    34 #include "linkablemapobj.h"
    35 #include "mainwindow.h"
    36 #include "misc.h"
    37 #include "settings.h"
    38 #include "texteditor.h"
    39 #include "xml.h"
    40 
    41 
    42 extern TextEditor *textEditor;
    43 extern int statusbarTime;
    44 extern Main *mainWindow;
    45 extern QString tmpVymDir;
    46 extern QString clipboardDir;
    47 extern bool clipboardEmpty;
    48 extern FlagRowObj *systemFlagsDefault;
    49 extern FlagRowObj *standardFlagsDefault;
    50 
    51 extern QPtrList <QAction> actionListBranches;
    52 
    53 extern QAction *actionFileSave;
    54 extern QAction *actionEditUndo;
    55 extern QAction *actionEditCopy;
    56 extern QAction *actionEditCut;
    57 extern QAction *actionEditPaste;
    58 extern QAction *actionEditMoveUp;
    59 extern QAction *actionEditMoveDown;
    60 extern QAction *actionEditToggleScroll;
    61 extern QAction *actionEditOpenURL;
    62 extern QAction *actionEditURL;
    63 extern QAction *actionEditHeading2URL;
    64 extern QAction *actionEditBugzilla2URL;
    65 extern QAction *actionEditFATE2URL;
    66 extern QAction *actionEditOpenVymLink;
    67 extern QAction *actionEditVymLink;
    68 extern QAction *actionEditDeleteVymLink;
    69 extern QAction *actionEditHeading;
    70 extern QAction *actionEditDelete;
    71 extern QAction *actionEditAddBranch;
    72 extern QAction *actionEditAddBranchAbove;
    73 extern QAction *actionEditAddBranchBelow;
    74 extern QAction *actionEditRemoveBranchHere;
    75 extern QAction *actionEditRemoveChilds;
    76 extern QAction *actionEditImportAdd;
    77 extern QAction *actionEditImportReplace;
    78 extern QAction *actionEditSaveBranch;
    79 extern QAction *actionEditSelectFirst;
    80 extern QAction *actionEditSelectLast;
    81 extern QAction *actionEditLoadImage;
    82 extern QAction *actionEditToggleFloatExport;
    83 
    84 extern QAction* actionFormatPickColor;
    85 extern QAction* actionFormatColorBranch;
    86 extern QAction* actionFormatColorSubtree;
    87 extern QAction *actionFormatLinkColorHint;
    88 extern QAction *actionFormatBackColor;
    89 extern QAction *actionFormatLinkColor;
    90 
    91 extern QActionGroup* actionGroupModModes;
    92 extern QAction* actionModModeColor;
    93 extern QAction* actionModModeLink;
    94 extern QAction* actionModModeCopy;
    95 
    96 extern QActionGroup *actionGroupFormatFrameTypes;
    97 extern QAction *actionFormatFrameNone;
    98 extern QAction *actionFormatFrameRectangle;
    99 
   100 extern QActionGroup *actionGroupFormatLinkStyles;
   101 extern QAction *actionFormatIncludeImagesVer;
   102 extern QAction *actionFormatIncludeImagesHor;
   103 extern QAction *actionFormatHideLinkUnselected;
   104 extern QAction *actionFormatLinkStyleLine;
   105 extern QAction *actionFormatLinkStyleParabel;
   106 extern QAction *actionFormatLinkStylePolyLine;
   107 extern QAction *actionFormatLinkStylePolyParabel;
   108 
   109 extern QAction *actionViewToggleNoteEditor;
   110 
   111 extern QAction *actionSettingsAutoedit;
   112 extern QAction *actionSettingsAutoselectHeading;
   113 extern QAction *actionSettingsAutoselectText;
   114 extern QAction *actionSettingsPasteNewHeading;
   115 extern QAction *actionSettingsUseFlagGroups;
   116 
   117 extern QPopupMenu *branchContextMenu;
   118 extern QPopupMenu *branchLinksContextMenu;
   119 extern QPopupMenu *branchLinksContextMenuDup;
   120 extern QPopupMenu *floatimageContextMenu;
   121 extern QPopupMenu *saveImageFormatMenu;
   122 extern QPopupMenu *exportImageFormatMenu;
   123 extern QPopupMenu *canvasContextMenu;
   124 
   125 extern Settings settings;
   126 
   127 int MapEditor::mapNum=0;	// make instance
   128 
   129 ///////////////////////////////////////////////////////////////////////
   130 ///////////////////////////////////////////////////////////////////////
   131 MapEditor::MapEditor(
   132 	QWidget* parent, bool interactive, const char* name, WFlags f) :
   133   QCanvasView(parent,name,f), urlOperator(0), imageBuffer(0)
   134 {
   135 	//cout << "Constructor ME "<<this<<endl;
   136 	mapNum++;
   137 
   138     viewport()->setAcceptDrops(true);
   139 
   140     mapCanvas = new QCanvas(1000,800);
   141 	mapCanvas->setAdvancePeriod(30);
   142 	mapCanvas->setBackgroundColor (white);
   143 
   144     setCanvas (mapCanvas);
   145 	
   146 	// Always show scroll bars (automatic would flicker sometimes)
   147 	setVScrollBarMode ( QScrollView::AlwaysOn );
   148 	setHScrollBarMode ( QScrollView::AlwaysOn );
   149 
   150     mapCenter = new MapCenterObj(mapCanvas);
   151     mapCenter->setVisibility (true);
   152 	mapCenter->setMapEditor (this);
   153 	mapCenter->setHeading (tr("New Map","Heading of mapcenter in new map"));
   154 	mapCenter->move(mapCanvas->width()/2-mapCenter->width()/2,mapCanvas->height()/2-mapCenter->height()/2);
   155 
   156     printer=NULL;
   157 
   158     lineedit = new QLineEdit(this, "lineedit"  );
   159     connect( lineedit, SIGNAL( returnPressed() ), SLOT( finishedLineEditNoSave() ) );
   160     lineedit->hide();
   161 
   162     actColor=black; setColor (actColor);
   163 	defLinkColor=QColor (0,0,255);
   164 	defXLinkColor=QColor (180,180,180);
   165 	linkcolorhint=DefaultColor;
   166 	linkstyle=StylePolyParabel;
   167 
   168 	// Create bitmap cursors, patform dependant
   169 	#if defined(Q_OS_MACX)
   170 		#include "icons/cursorhandopen16.xpm"
   171 		#include "icons/cursorcolorpicker16.xpm"
   172 		QBitmap cb( 16, 16, chandopen, TRUE );
   173 		QBitmap cm( 16, 16, chandopenmask, TRUE );
   174 		handOpenCursor=QCursor ( cb, cm );		
   175 		// set hot spot to tip of picker			
   176 		pickColorCursor=QCursor ( cursorcolorpicker_xpm, 1,15 ); 
   177 	#else
   178 		#include "icons/cursorhandopen.xpm"
   179 		#include "icons/cursorcolorpicker.xpm"
   180 
   181 		QBitmap cb( 32, 32, chandopen, TRUE );
   182 		QBitmap cm( 32, 32, chandopenmask, TRUE );
   183 		handOpenCursor=QCursor ( cb, cm );		
   184 		// set hot spot to tip of picker			
   185 		pickColorCursor=QCursor ( cursorcolorpicker_xpm, 5,27 ); 
   186 	#endif
   187 
   188 	pickingColor=false;
   189 	drawingLink=false;
   190 	copyingObj=false;
   191 
   192     editingBO=NULL;
   193     selection=NULL;
   194     selectionLast=NULL;
   195     movingObj=NULL;
   196 
   197 	defXLinkWidth=1;
   198 	defXLinkColor=QColor (230,230,230);
   199 
   200     mapChanged=false;
   201 	mapDefault=true;
   202 	mapUnsaved=false;
   203 	
   204 	zipped=true;
   205 	filePath="";
   206 	fileName="unnamed";
   207 	mapName="";
   208 
   209 	undosTotal=settings.readNumEntry("/vym/mapeditor/undoLevels",50);
   210 	undosAvail=0;	
   211 	undoNum=0;
   212 	
   213 	// Initialize find routine
   214 	itFind=NULL;				
   215 	EOFind=false;
   216 
   217 	printFrame=true;
   218 	printFooter=true;
   219 
   220 	blockReposition=false;
   221 	blockSaveState=false;
   222 	isInteractive=interactive;
   223 	if (isInteractive)
   224 		// Create temporary files
   225 		makeTmpDirs();
   226 
   227 	// Initially set movingCentre
   228 	updateViewCenter();
   229 
   230 	mapCenter->reposition();	//	for positioning heading
   231 }
   232 
   233 MapEditor::~MapEditor()
   234 {
   235   if (imageBuffer) delete imageBuffer;
   236   if (urlOperator) {
   237     urlOperator->stop();
   238     delete urlOperator;
   239   }
   240 
   241 	//cout <<"Destructor MapEditor\n";
   242 
   243 	// Save Settings
   244 	//settings.writeEntry( "/vym/mapeditor/editmode/autoselect",  );
   245 
   246 }
   247 
   248 QColor MapEditor::color()
   249 {
   250     return actColor;
   251 }
   252 
   253 QColor MapEditor::backgroundColor()
   254 {
   255     return mapCanvas->backgroundColor();
   256 }
   257 
   258 MapCenterObj* MapEditor::getMapCenter()
   259 {
   260     return mapCenter;
   261 }
   262 
   263 QCanvas* MapEditor::getCanvas()
   264 {
   265     return mapCanvas;
   266 }
   267 
   268 void MapEditor::adjustCanvasSize()
   269 {
   270 	// To adjust the canvas to map, viewport size and position, we have to
   271 	// do some coordinate magic...
   272 	//
   273 	// Get rectangle of (scroll-)view. 
   274 	// We want to be in canvas coords, so
   275 	// we map. Important if view is zoomed...
   276 	QRect view = inverseWorldMatrix().mapRect( QRect( contentsX(), contentsY(),
   277 												visibleWidth(), visibleHeight()) );	
   278 												
   279 	// Now we need the bounding box of view AND map to calc the correct canvas size.
   280 	// Why? Because if the map itself is moved out of view, the view has to be enlarged
   281 	// to avoid jumping aroung...
   282 	QRect map=mapCenter->getTotalBBox();
   283 
   284 	// right edge - left edge
   285 	int cw= max(map.x() + map.width(),  view.x() + view.width())  - min(map.x(), view.x());
   286 	int ch= max(map.y() + map.height(), view.y() + view.height()) - min(map.y(), view.y());
   287 
   288 
   289 	if ( (cw!=mapCanvas->width()) || (ch!=mapCanvas->height()) ||
   290 		!mapCanvas->onCanvas (map.topLeft()) || !mapCanvas->onCanvas (map.bottomRight())
   291 	)	
   292 	{	
   293 		// move the map on canvas (in order to not move it on screen) this is neccessary
   294 		// a) if topleft corner of canvas is left or above topleft corner of view and also left of
   295 		//    above topleft corner of map. E.g. if map is completly inside view, but it would be possible 
   296 		//    to scroll to an empty area of canvas to the left.
   297 		// b) if topleft corner of map left of or above topleft of canvas
   298 		int dx=0;
   299 		int dy=0;
   300 
   301 		if (cw > mapCanvas->width() )
   302 		{
   303 			if (map.x()<0) dx=-map.x();	
   304 		}
   305 		if (cw <  mapCanvas->width() )
   306 			dx=-min (view.x(),map.x());
   307 		if (ch > mapCanvas->height() )
   308 		{
   309 			if (map.y()<0) dy=-map.y();	
   310 		}
   311 		if (ch <  mapCanvas->height() )
   312 		{
   313 			dy=-min (view.y(),map.y());
   314 		}
   315 		// We really have to resize now. Let's go...
   316 		mapCanvas->resize (cw,ch);
   317 		if ( (dx!=0) || (dy!=0) ) 
   318 		{
   319 			mapCenter->moveAllBy(dx,dy);
   320 			mapCenter->reposition();
   321 
   322 			// scroll the view (in order to not move map on screen)
   323 			scrollBy (dx,dy);
   324 		}	
   325 	}
   326 }
   327 
   328 bool MapEditor::isRepositionBlocked()
   329 {
   330 	return blockReposition;
   331 }
   332 
   333 void MapEditor::makeTmpDirs()
   334 {
   335 	// Create unique temporary directories
   336 	tmpMapDir=tmpVymDir+QString("/mapeditor-%1").arg(mapNum);
   337 	QDir d;
   338 	d.mkdir (tmpMapDir,true);
   339 }
   340 
   341 void MapEditor::delTmpDirs()
   342 {
   343 	removeDir (QDir(tmpMapDir));
   344 }
   345 
   346 QString MapEditor::saveToDir(const QString &tmpdir, const QString &prefix, bool writeflags, const QPoint &offset, LinkableMapObj *saveSelection)
   347 {
   348 	// tmpdir		temporary directory to which data will be written
   349 	// prefix		mapname, which will be appended to images etc.
   350 	// writeflags	Only write flags for "real" save of map, not undo
   351 	// offset		offset of bbox of whole map in canvas. 
   352 	//				Needed for XML export
   353 	
   354 	// Save Header
   355 	QString ls;
   356 	switch (linkstyle)
   357 	{
   358 		case StyleLine: 
   359 			ls="StyleLine";
   360 			break;
   361 		case StyleParabel:
   362 			ls="StyleParabel";
   363 			break;
   364 		case StylePolyLine:	
   365 			ls="StylePolyLine";
   366 			break;
   367 		default:
   368 			ls="StylePolyParabel";
   369 			break;
   370 	}	
   371 
   372 	QString s="<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE vymmap>\n";
   373 	QString colhint="";
   374 	if (linkcolorhint==HeadingColor) 
   375 		colhint=attribut("linkColorHint","HeadingColor");
   376 
   377 	QString mapAttr=attribut("version",__VYM_VERSION);
   378 	if (!saveSelection)
   379 		mapAttr+= attribut("author",mapCenter->getAuthor()) +
   380 				  attribut("comment",mapCenter->getComment()) +
   381 			      attribut("date",mapCenter->getDate()) +
   382 		          attribut("backgroundColor", mapCanvas->backgroundColor().name() ) +
   383 		          attribut("linkStyle", ls ) +
   384 		          attribut("linkColor", defLinkColor.name() ) +
   385 		          attribut("defXLinkColor", defXLinkColor.name() ) +
   386 		          attribut("defXLinkWidth", QString().setNum(defXLinkWidth,10) ) +
   387 		          colhint; 
   388 	s+=beginElement("vymmap",mapAttr);
   389 	incIndent();
   390 
   391 	// Find the used flags while traversing the tree
   392 	standardFlagsDefault->resetUsedCounter();
   393 	
   394 	// Reset the counters before saving
   395 	FloatImageObj (mapCanvas).resetSaveCounter();
   396 
   397 	// Build xml recursivly
   398 	if (!saveSelection)
   399 		s+=mapCenter->saveToDir(tmpdir,prefix,writeflags,offset);
   400 	else
   401 	{
   402 		if ( typeid(*saveSelection) == typeid(BranchObj) )
   403 			s+=((BranchObj*)(saveSelection))->saveToDir(tmpdir,prefix,offset);
   404 		else if ( typeid(*saveSelection) == typeid(FloatImageObj) )
   405 			s+=((FloatImageObj*)(saveSelection))->saveToDir(tmpdir,prefix,offset);
   406 			
   407 		else if (selection && typeid(*selection)==typeid(BranchObj))
   408 				// This is used if selected branch is saved from mainwindow
   409 				s+=((BranchObj*)selection)->saveToDir(tmpdir,prefix,offset);
   410 	}
   411 
   412 	// Save local settings
   413 	s+=settings.getXMLData (destPath);
   414 
   415 	// Save selection
   416 	if (selection && !saveSelection ) 
   417 		s+=valueElement("select",selection->getSelectString());
   418 
   419 	decIndent();
   420 	s+=endElement("vymmap");
   421 
   422 	if (writeflags)
   423 		standardFlagsDefault->saveToDir (tmpdir+"/flags/","",writeflags);
   424 	return s;
   425 }
   426 
   427 void MapEditor::saveState()
   428 {
   429 	// Save complete map
   430 	saveState (CompleteMap,"",NULL,"",NULL);
   431 }
   432 
   433 void MapEditor::saveState(LinkableMapObj *undoSel)
   434 {
   435 	// save the given part of the map 
   436 	saveState (PartOfMap,"",undoSel,"",NULL);
   437 }
   438 
   439 void MapEditor::saveState(const QString &uc, const QString &rc)
   440 {
   441 	// selection does not change during action,
   442 	// so just save commands for undo and redo
   443 	LinkableMapObj *unsel;
   444 	if (selection)
   445 		unsel=selection;
   446 	else
   447 		unsel=NULL;
   448 	saveState (UndoCommand,uc,unsel,rc,unsel);
   449 }
   450 
   451 void MapEditor::saveState(const QString & uncom, LinkableMapObj *unsel) 
   452 {
   453 	saveState (UndoCommand,uncom,unsel,"FIXME-redoCom",NULL);
   454 }
   455 
   456 void MapEditor::saveState(const SaveMode &savemode, const QString &undoCom, LinkableMapObj *undoSel, const QString &redoCom, LinkableMapObj *redoSel)
   457 {
   458 	// Main saveState
   459 
   460 	if (blockSaveState) return;
   461 
   462 	/* TODO remove after testing
   463 	cout << "ME::saveState()  begin\n"<<endl;
   464 	cout << "    undosTotal="<<undosTotal<<endl;
   465 	cout << "    undosAvail="<<undosAvail<<endl;
   466 	cout << "       undoNum="<<undoNum<<endl;
   467 	cout << "    ---------------------------"<<endl;
   468 	*/
   469 	setChanged();
   470 
   471 	// Find out current undo directory
   472 	if (undosAvail<undosTotal) undosAvail++;
   473 	undoNum++;
   474 	if (undoNum>undosTotal) undoNum=1;
   475 	
   476 	QString backupXML;
   477 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(undoNum));
   478 	QString bakMapPath=QDir::convertSeparators(bakMapDir+"/map.xml");
   479 
   480 	// Create bakMapDir if not available
   481 	QDir d(bakMapDir);
   482 	if (!d.exists()) 
   483 		makeSubDirs (bakMapDir);
   484 
   485 	// Save current selection 
   486 	QString redoSelection="";
   487 	if (redoSel)
   488 		redoSelection=redoSel->getSelectString();
   489 
   490 	// Save the object, which should be undone
   491 	QString undoSelection="";
   492 	if (undoSel)
   493 		undoSelection=undoSel->getSelectString();
   494 		
   495 	// Save depending on how much needs to be saved	
   496 	QString undoCommand="";
   497 	if (savemode==UndoCommand)
   498 	{
   499 		undoCommand=undoCom;
   500 		backupXML="";
   501 	}	
   502 	else if (savemode==PartOfMap && undoSel)
   503 	{
   504 		undoCommand="undoPart (\""+ undoSelection+"\",\""+bakMapPath+"\")";
   505 		backupXML=saveToDir (bakMapDir,mapName+"-",false, QPoint (),undoSel);
   506 	} else
   507 	{
   508 		undoCommand="undoMap (\""+bakMapPath+"\")";
   509 		backupXML=saveToDir (bakMapDir,mapName+"-",false, QPoint (),NULL);
   510 		undoSelection="";
   511 	}
   512 	if (!backupXML.isEmpty())
   513 		// Write XML Data to disk
   514 		saveStringToDisk (QString(bakMapPath),backupXML);
   515 
   516 	SimpleSettings set;
   517 	set.setEntry (QString("undoCommand"),undoCommand);
   518 	set.setEntry (QString("undoSelection"),undoSelection);
   519 	set.setEntry (QString("redoCommand"),redoCom);
   520 	set.setEntry (QString("redoSelection"),redoSelection);
   521 	set.writeSettings(QString(bakMapDir+"/commands"));
   522 
   523 	/* TODO remove after testing
   524 	cout << "          into="<< bakMapDir<<endl;
   525 	cout << "    undosAvail="<<undosAvail<<endl;
   526 	cout << "       undoNum="<<undoNum<<endl;
   527 	cout << "    ---------------------------"<<endl;
   528 	cout << "    undoCom="<<undoCommand<<endl;
   529 	cout << "    undoSel="<<undoSelection<<endl;
   530 	cout << "    ---------------------------"<<endl;
   531 	cout << "    redoCom="<<redoCom<<endl;
   532 	cout << "    redoSel="<<redoSelection<<endl;
   533 	cout << "    ---------------------------"<<endl<<endl;
   534 	*/
   535 }
   536 
   537 void MapEditor::parseAtom(const QString &atom)
   538 {
   539 	API api;
   540 	QString s,t;
   541 	int x,y;
   542 	bool ok;
   543 
   544 	// Split string s into command and parameters
   545 	api.parseCommand (atom);
   546 	QString com=api.command();
   547 	
   548 	// External commands
   549 	if (com=="moveBranchUp")
   550 		moveBranchUp();
   551 	else if (com=="moveBranchDown")
   552 		moveBranchDown();
   553 	else if (com=="move")
   554 	{
   555 		if (api.checkParamCount(2) && selection )
   556 		{	
   557 			x=api.parInt (ok,0);
   558 			if (ok)
   559 			{
   560 				y=api.parInt (ok,1);
   561 				if (ok) move (x,y);
   562 			}
   563 		}	
   564 	}
   565 	else if (com=="linkBranchToPos")
   566 	{
   567 		if (selection && typeid(*selection) == typeid(BranchObj) ) 
   568 		{
   569 			if (api.checkParamCount(4))
   570 			{
   571 				s=api.parString(ok,0);
   572 				LinkableMapObj *dst=mapCenter->findObjBySelect (s);
   573 				if (dst)
   574 				{	
   575 					if (typeid(*dst) == typeid(BranchObj) ) 
   576 					{
   577 						// Get number in parent
   578 						x=api.parInt (ok,1);
   579 						if (ok)
   580 							((BranchObj*)selection)->moveBranchTo ((BranchObj*)(dst),x);
   581 					} else if (typeid(*dst) == typeid(MapCenterObj) ) 
   582 					{
   583 						((BranchObj*)selection)->moveBranchTo ((BranchObj*)(dst),-1);
   584 						// Get coordinates of mainbranch
   585 						x=api.parInt (ok,2);
   586 						if (ok)
   587 						{
   588 							y=api.parInt (ok,3);
   589 							if (ok) ((BranchObj*)selection)->move (x,y);
   590 						}
   591 					}	
   592 				}	
   593 			}
   594 		}
   595 	} else if (com=="setHeading")
   596 	{
   597 		if (api.checkParamCount(1))
   598 		{
   599 			s=api.parString (ok,0);
   600 			if (ok) setHeading (s);
   601 		}	
   602 	} else if (com=="setURL")
   603 	{
   604 		if (api.checkParamCount(1))
   605 		{
   606 			s=api.parString (ok,0);
   607 			if (ok) setURL(s);
   608 		}	
   609 	} else if (com=="setVymLink")
   610 	{
   611 		if (api.checkParamCount(1))
   612 		{
   613 			s=api.parString (ok,0);
   614 			if (ok) setVymLink(s);
   615 		}	
   616 	}
   617 	// Internal commands, used for undo etc.	
   618 	else if (com==QString("undoMap"))
   619 	{
   620 		if (api.checkParamCount(1))
   621 			undoXML("",api.parString (ok,0));
   622 	} else if (com==QString("undoPart"))
   623 	{
   624 		if (api.checkParamCount(2))
   625 		{
   626 			s=api.parString (ok,0);
   627 			t=api.parString (ok,1);
   628 			undoXML(s,t);	
   629 		}
   630 	} else if (com=="select")
   631 		if (api.checkParamCount(1))
   632 		{
   633 			s=api.parString(ok,0);
   634 			if (ok) select (s);
   635 		}	
   636 	else
   637 	{
   638 		api.setError ("Unknown command in: "+atom);
   639 		cout << "ME::parse   api should have error now...\n";
   640 	}
   641 
   642 	// Any errors?
   643 	if (api.error())
   644 	{
   645 		cout << "MapEditor::parseAtom: Error!\n";
   646 		cout << "  "<<api.errorDesc()<<endl;
   647 	}	
   648 }
   649 
   650 
   651 void MapEditor::finishedLineEditNoSave()
   652 {
   653 	// This is called by finishedLineEdit or any MapEditor method,
   654 	// which wants to assure, that lineedits finish, before e.g. a branch is 
   655 	// deleted
   656     
   657 	// After calling LineEdit and using the clipboard, the 
   658     // focus is not any longer on the main widget, we
   659     // have to restore it using parentWidget()->setFocus()
   660 
   661     if (editingBO!=NULL) 
   662 	{
   663 		editingBO->setHeading(lineedit->text() );
   664 		editingBO=NULL;
   665 		lineedit->releaseKeyboard();
   666 		lineedit->hide();
   667 		parentWidget()->setFocus();
   668 		mapCenter->reposition();
   669 		adjustCanvasSize();
   670 		ensureSelectionVisible();
   671     }		
   672 }
   673 
   674 
   675 bool MapEditor::isDefault()
   676 {
   677     return mapDefault;
   678 }
   679 
   680 bool MapEditor::isUnsaved()
   681 {
   682     return mapUnsaved;
   683 }
   684 
   685 bool MapEditor::hasChanged()
   686 {
   687     return mapChanged;
   688 }
   689 
   690 void MapEditor::setChanged()
   691 {
   692 	mapChanged=true;
   693 	mapDefault=false;
   694 	mapUnsaved=true;
   695 	actionEditUndo->setEnabled (true);
   696 	actionFileSave->setEnabled (true);
   697 	findReset();
   698 }
   699 
   700 void MapEditor::closeMap()
   701 {
   702 	// Finish open lineEdits
   703 	if (lineedit) finishedLineEditNoSave();
   704 
   705 	// Unselect before disabling the toolbar actions
   706 	if (selection) selection->unselect();
   707 	selection=NULL;
   708 	updateActions();
   709 
   710     clear();
   711 	close();
   712 }
   713 
   714 void MapEditor::setFilePath(QString fname)
   715 {
   716 	setFilePath (fname,fname);
   717 }
   718 
   719 void MapEditor::setFilePath(QString fname, QString destname)
   720 {
   721 	if (fname.isEmpty() || fname=="")
   722 	{
   723 		filePath="";
   724 		fileName="";
   725 		destPath="";
   726 	} else
   727 	{
   728 		filePath=fname;		// becomes absolute path
   729 		fileName=fname;		// gets stripped of path
   730 		destPath=destname;	// needed for vymlinks
   731 
   732 		// If fname is not an absolute path, complete it
   733 		filePath=QDir(fname).absPath();
   734 		fileDir=filePath.left (1+filePath.findRev ("/"));
   735 
   736 		// Set short name, too. Search from behind:
   737 		int i=fileName.findRev("/");
   738 		if (i>=0) fileName=fileName.remove (0,i+1);
   739 
   740 		// Forget the .vym (or .xml) for name of map
   741 		mapName=fileName.left(fileName.findRev(".",-1,true) );
   742 	}
   743 }
   744 
   745 QString MapEditor::getFilePath()
   746 {
   747 	return filePath;
   748 }
   749 
   750 QString MapEditor::getFileName()
   751 {
   752 	return fileName;
   753 }
   754 
   755 QString MapEditor::getMapName()
   756 {
   757 	return mapName;
   758 }
   759 
   760 QString MapEditor::getDestPath()
   761 {
   762 	return destPath;
   763 }
   764 
   765 ErrorCode MapEditor::load (QString fname, LoadMode lmode)
   766 {
   767 	// Finish open lineEdits
   768 	if (lineedit) finishedLineEditNoSave();
   769 
   770 	ErrorCode err=success;
   771 
   772 	if (lmode==NewMap)
   773 	{
   774 		if (selection) selection->unselect();
   775 		selection=NULL;
   776 		mapCenter->clear();
   777 		mapCenter->setMapEditor(this);
   778 		// (map state is set later at end of load...)
   779 	} else
   780 	{
   781 		saveState(selection);
   782 	}	
   783 	
   784     
   785     mapBuilderHandler handler;
   786 	QFile file( fname );
   787 
   788 	// I am paranoid: file should exist anyway
   789 	// according to check in mainwindow.
   790 	if (!file.exists() )
   791 	{
   792 		QMessageBox::critical( 0, tr( "Critical Parse Error" ),
   793 				   tr("Couldn't open map " +fname)+".");
   794 		err=aborted;	
   795 	} else
   796 	{
   797 		blockReposition=true;
   798 		QXmlInputSource source( file);
   799 		QXmlSimpleReader reader;
   800 		reader.setContentHandler( &handler );
   801 		reader.setErrorHandler( &handler );
   802 		handler.setMapEditor( this );
   803 		handler.setTmpDir (filePath.left(filePath.findRev("/",-1)));	// needed to load files with rel. path
   804 		handler.setLoadMode (lmode);
   805 		blockSaveState=true;
   806 		bool ok = reader.parse( source );
   807 		blockReposition=false;
   808 		blockSaveState=false;
   809 		file.close();
   810 		if ( ok ) 
   811 		{
   812 			mapCenter->reposition();
   813 			adjustCanvasSize();
   814 			if (lmode==NewMap)
   815 			{
   816 				mapDefault=false;
   817 				mapChanged=false;
   818 				mapUnsaved=false;
   819 			}
   820 		} else 
   821 		{
   822 			QMessageBox::critical( 0, tr( "Critical Parse Error" ),
   823 					   tr( handler.errorProtocol() ) );
   824 			// returnCode=1;	
   825 			// Still return "success": the map maybe at least
   826 			// partially read by the parser
   827 		}	
   828 	}	
   829 	updateActions();
   830 	return err;
   831 }
   832 
   833 int MapEditor::save (const SaveMode &savemode)
   834 {
   835 	// Finish open lineEdits
   836 	if (lineedit) finishedLineEditNoSave();
   837 
   838 	int returnCode=0;
   839 
   840 	// The SaveMode UndoCommand is not supported here
   841 	if (savemode==UndoCommand) return 1;
   842 
   843 	// Create mapName and fileDir
   844 	makeSubDirs (fileDir);
   845 	QString fname;
   846 	if (saveZipped())
   847 		// save as .xml
   848 		fname=mapName+".xml";
   849 	else
   850 		// use name given by user, even if he chooses .doc
   851 		fname=fileName;
   852 
   853 
   854 	QString saveFile;
   855 	if (savemode==CompleteMap || selection==NULL)
   856 		saveFile=saveToDir (fileDir,mapName+"-",true,QPoint(),NULL);
   857 	else	
   858 		saveFile=saveToDir (fileDir,mapName+"-",true,QPoint(),selection);
   859 
   860 	if (!saveStringToDisk(fileDir+fname,saveFile))
   861 		return 1;
   862 
   863 	if (returnCode==0)
   864 	{
   865 		mapChanged=false;
   866 		mapUnsaved=false;
   867 		actionFileSave->setEnabled(false);
   868 	}
   869 
   870 	return returnCode;
   871 }
   872 
   873 void MapEditor::setZipped (bool z)
   874 {
   875 	zipped=z;
   876 }
   877 
   878 bool MapEditor::saveZipped ()
   879 {
   880 	return zipped;
   881 }
   882 
   883 void MapEditor::print()
   884 {
   885 	// Finish open lineEdits
   886 	if (lineedit) finishedLineEditNoSave();
   887 
   888 	if ( !printer ) 
   889 	{
   890 		printer = new QPrinter;
   891 		printer->setColorMode (QPrinter::Color);
   892 		printer->setPrinterName (settings.readEntry("/vym/mainwindow/printerName",printer->printerName()));
   893 	}
   894 
   895 	QRect totalBBox=mapCenter->getTotalBBox();
   896 
   897 	// Try to set orientation automagically
   898 	// Note: Interpretation of generated postscript is amibiguous, if 
   899 	// there are problems with landscape mode, see
   900 	// http://sdb.suse.de/de/sdb/html/jsmeix_print-cups-landscape-81.html
   901 
   902 	if (totalBBox.width()>totalBBox.height())
   903 		// recommend landscape
   904 		printer->setOrientation (QPrinter::Landscape);
   905 	else	
   906 		// recommend portrait
   907 		printer->setOrientation (QPrinter::Portrait);
   908 
   909 	if ( printer->setup(this) ) 
   910 	// returns false, if printing is canceled
   911 	{
   912 		QPainter pp(printer);
   913 
   914 		// Don't print the visualisation of selection
   915 		LinkableMapObj *oldselection=NULL;
   916 		if (selection) 
   917 		{
   918 			oldselection=selection;
   919 			selection->unselect();
   920 		}
   921 
   922 		// Handle sizes of map and paper:
   923 		//
   924 		// setWindow defines which part of the canvas will be transformed 
   925 		// setViewport defines area on paper in device coordinates (dpi)
   926 		// e.g. (0,50,700,700) is upper part on A4
   927 		// see also /usr/lib/qt3/doc/html/coordsys.html
   928 
   929 		QPaintDeviceMetrics metrics (printer);
   930 
   931 		double paperAspect = (double)metrics.width()   / (double)metrics.height();
   932 		double   mapAspect = (double)totalBBox.width() / (double)totalBBox.height();
   933 
   934 		QRect mapRect=totalBBox;
   935 		QCanvasRectangle *frame=NULL;
   936 		QCanvasText *footerFN=NULL;
   937 		QCanvasText *footerDate=NULL;
   938 		if (printFrame || printFooter)
   939 		{
   940 			
   941 			if (printFrame) 
   942 			{
   943 				// Print frame around map
   944 				mapRect.setRect (totalBBox.x()-10, totalBBox.y()-10, 
   945 					totalBBox.width()+20, totalBBox.height()+20);
   946 				frame=new QCanvasRectangle (mapRect,mapCanvas);
   947 				frame->setBrush (QColor(white));
   948 				frame->setPen (QColor(black));
   949 				frame->setZ(0);
   950 				frame->show();    
   951 			}		
   952 			/* TODO remove after testing 
   953 			QCanvasLine *l=new QCanvasLine (mapCanvas);
   954 			l->setPoints (0,0,mapRect.width(),mapRect.height());
   955 			l->setPen (QPen(QColor(black), 1));
   956 			l->setZ (200);
   957 			l->show();
   958 			*/
   959 
   960 			if (printFooter) 
   961 			{
   962 				// Print footer below map
   963 				QFont font;		
   964 				font.setPointSize(10);
   965 				footerFN=new QCanvasText (mapCanvas);
   966 				footerFN->setText ("VYM - " + fileName);
   967 				footerFN->setFont(font);
   968 				footerFN->move (mapRect.x(), mapRect.y() + mapRect.height() );
   969 				footerFN->setZ(Z_TEXT);
   970 				footerFN->show();    
   971 				footerDate=new QCanvasText (mapCanvas);
   972 				footerDate->setText (QDate::currentDate().toString(Qt::TextDate));
   973 				footerDate->setFont(font);
   974 				footerDate->move (mapRect.x()+mapRect.width()-footerDate->boundingRect().width(), mapRect.y() + mapRect.height() );
   975 				footerDate->setZ(Z_TEXT);
   976 				footerDate->show();    
   977 			}
   978 			pp.setWindow (mapRect.x(), mapRect.y(), mapRect.width(), mapRect.height()+20);
   979 		}	else	
   980 		{
   981 			pp.setWindow (mapRect);
   982 		}	
   983 
   984 		if (mapAspect>=paperAspect)
   985 		{
   986 			// Fit horizontally to paper width
   987 			pp.setViewport(0,0, metrics.width(),(int)(metrics.width()/mapAspect) );	
   988 		}	else
   989 		{
   990 			// Fit vertically to paper height
   991 			pp.setViewport(0,0,(int)(metrics.height()*mapAspect),metrics.height());	
   992 		}	
   993 
   994 		mapCanvas->drawArea(mapRect, &pp);	// draw Canvas to printer
   995 
   996 		// Delete Frame and footer
   997 		if (footerFN) 
   998 		{
   999 			delete (footerFN);
  1000 			delete (footerDate);
  1001 		}	
  1002 		if (frame)  delete (frame);
  1003 
  1004 		// Restore selection
  1005 		if (oldselection) 
  1006 		{
  1007 			selection=oldselection;
  1008 			selection->select();
  1009 		}	
  1010 
  1011 		// Save settings in vymrc
  1012 		settings.writeEntry("/vym/mainwindow/printerName",printer->printerName());
  1013 	}
  1014 }
  1015 
  1016 QPixmap MapEditor::getPixmap()
  1017 {
  1018 	QRect mapRect=mapCenter->getTotalBBox();
  1019 	QPixmap pix (mapRect.size());
  1020 	QPainter pp (&pix);
  1021 
  1022 	// Don't print the visualisation of selection
  1023 	LinkableMapObj *oldselection=NULL;
  1024 	if (selection) 
  1025 	{
  1026 		oldselection=selection;
  1027 		selection->unselect();
  1028 	}
  1029 
  1030 	pp.setWindow (mapRect);
  1031 
  1032 	mapCanvas->drawArea(mapRect, &pp);	// draw Canvas to painter
  1033 
  1034 
  1035 	// Restore selection
  1036 	if (oldselection) 
  1037 	{
  1038 		selection=oldselection;
  1039 		selection->select();
  1040 	}	
  1041 	
  1042 	return pix;
  1043 }
  1044 
  1045 void MapEditor::exportImage(QString fn)
  1046 {
  1047 	// Finish open lineEdits
  1048 	if (lineedit) finishedLineEditNoSave();
  1049 
  1050 	QPixmap pix (getPixmap());
  1051 	pix.save(fn, "PNG");
  1052 }
  1053 
  1054 void MapEditor::exportImage(QString fn, int item)
  1055 {
  1056 	// Finish open lineEdits
  1057 	if (lineedit) finishedLineEditNoSave();
  1058 
  1059 	QPixmap pix (getPixmap());
  1060 	pix.save(fn, exportImageFormatMenu->text(item) );
  1061 }
  1062 
  1063 void MapEditor::exportOOPresentation(const QString &fn, const QString &cf)
  1064 {
  1065 	ExportOO ex;
  1066 	ex.setFile (fn);
  1067 	ex.setMapCenter(mapCenter);
  1068 	if (ex.setConfigFile(cf)) ex.exportPresentation();
  1069 }
  1070 
  1071 
  1072 
  1073 void MapEditor::exportXML(const QString &dir)
  1074 {
  1075 	// Create subdirectories
  1076 	makeSubDirs (dir);
  1077 
  1078 	// write to directory
  1079 	QString saveFile=saveToDir (dir,mapName+"-",true,mapCenter->getTotalBBox().topLeft() ,NULL);
  1080 	QFile file;
  1081 
  1082 	file.setName ( dir + "/"+mapName+".xml");
  1083 	if ( !file.open( IO_WriteOnly ) )
  1084 	{
  1085 		// This should neverever happen
  1086 		QMessageBox::critical (0,tr("Critical Export Error"),tr("MapEditor::exportXML couldn't open %1").arg(file.name()));
  1087 		return;
  1088 	}	
  1089 
  1090 	// Write it finally, and write in UTF8, no matter what 
  1091 	QTextStream ts( &file );
  1092 	ts.setEncoding (QTextStream::UnicodeUTF8);
  1093 	ts << saveFile;
  1094 	file.close();
  1095 
  1096 	// Now write image, too
  1097 	exportImage (dir+"/images/"+mapName+".png");
  1098 }
  1099 
  1100 void MapEditor::clear()
  1101 {
  1102 	if (selection)
  1103 	{
  1104 		selection->unselect();
  1105 		selection=NULL;
  1106 	}	
  1107 
  1108 	mapCenter->clear();
  1109 }
  1110 
  1111 void MapEditor::copy()
  1112 {
  1113 	// Finish open lineEdits
  1114 	if (lineedit) finishedLineEditNoSave();
  1115 
  1116 	if (selection) 
  1117 	{
  1118 		// write to directory
  1119 		QString clipfile="part";
  1120 		QString saveFile=saveToDir (fileDir,clipfile+"-",true,QPoint(),selection);
  1121 		QFile file;
  1122 
  1123 		file.setName ( clipboardDir + "/"+clipfile+".xml");
  1124 		if ( !file.open( IO_WriteOnly ) )
  1125 		{
  1126 			// This should neverever happen
  1127 			QMessageBox::critical (0,tr("Critical Export Error"),tr("MapEditor::exportXML couldn't open %1").arg(file.name()));
  1128 			return;
  1129 		}	
  1130 
  1131 		// Write it finally, and write in UTF8, no matter what 
  1132 		QTextStream ts( &file );
  1133 		ts.setEncoding (QTextStream::UnicodeUTF8);
  1134 		ts << saveFile;
  1135 		file.close();
  1136 
  1137 		clipboardEmpty=false;
  1138 		updateActions();
  1139 	}	    
  1140 }
  1141 
  1142 void MapEditor::redo()
  1143 {
  1144 	// Finish open lineEdits
  1145 	if (lineedit) finishedLineEditNoSave();
  1146 
  1147 	blockSaveState=true;
  1148 	
  1149 	// Find out current undo directory
  1150 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(undoNum));
  1151 
  1152 	// Restore variables
  1153 	QString undoCommand;
  1154 	QString undoSelection;
  1155 	QString redoCommand;
  1156 	QString redoSelection;
  1157 	SimpleSettings set;
  1158 	set.readSettings(QString(bakMapDir+"/commands"));
  1159 	undoCommand=set.readEntry ("undoCommand");
  1160 	undoSelection=set.readEntry ("undoSelection");
  1161 	redoCommand=set.readEntry ("redoCommand");
  1162 	redoSelection=set.readEntry ("redoSelection");
  1163 
  1164 	// select  object before redo
  1165 	if (!redoSelection.isEmpty())
  1166 		select (redoSelection);
  1167 
  1168 /* TODO remove testing
  1169 	cout << "ME::redo() begin\n";
  1170 	cout << "    undosTotal="<<undosTotal<<endl;
  1171 	cout << "    undosAvail="<<undosAvail<<endl;
  1172 	cout << "       undoNum="<<undoNum<<endl;
  1173 	cout << "    ---------------------------"<<endl;
  1174 	cout << "    undoCom="<<undoCommand<<endl;
  1175 	cout << "    undoSel="<<undoSelection<<endl;
  1176 	cout << "    ---------------------------"<<endl;
  1177 	cout << "    redoCom="<<redoCommand<<endl;
  1178 	cout << "    redoSel="<<redoSelection<<endl;
  1179 	cout << "    ---------------------------"<<endl;
  1180 */
  1181 	parseAtom (undoCommand);
  1182 	mapCenter->reposition();
  1183 
  1184 	//if (!redoSelection.isEmpty())
  1185 	//	select (redoSelection);
  1186 
  1187 	undosAvail--;
  1188 	if (undosAvail<1)
  1189 		// Undo not longer available now
  1190 		actionEditUndo->setEnabled (false);
  1191 	else	
  1192 		undoNum--; if (undoNum<1) undoNum=undosTotal;
  1193 
  1194 	blockSaveState=false;
  1195 /* TODO remove testing
  1196 	cout << "ME::redo() end\n";
  1197 	cout << "    undosAvail="<<undosAvail<<endl;
  1198 	cout << "       undoNum="<<undoNum<<endl;
  1199 	cout << "    ---------------------------"<<endl<<endl;
  1200 */	
  1201 }
  1202 
  1203 void MapEditor::undo()
  1204 {
  1205 	// Finish open lineEdits
  1206 	if (lineedit) finishedLineEditNoSave();
  1207 
  1208 	blockSaveState=true;
  1209 	
  1210 	// Find out current undo directory
  1211 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(undoNum));
  1212 
  1213 	// Restore variables
  1214 	QString undoCommand;
  1215 	QString undoSelection;
  1216 	QString redoCommand;
  1217 	QString redoSelection;
  1218 	SimpleSettings set;
  1219 	set.readSettings(QString(bakMapDir+"/commands"));
  1220 	undoCommand=  set.readEntry ("undoCommand");
  1221 	undoSelection=set.readEntry ("undoSelection");
  1222 	redoCommand=  set.readEntry ("redoCommand");
  1223 	redoSelection=set.readEntry ("redoSelection");
  1224 
  1225 	// select  object before undo
  1226 	if (!undoSelection.isEmpty())
  1227 		select (undoSelection);
  1228 
  1229 /* TODO testing
  1230 	cout << "ME::undo() begin\n";
  1231 	cout << "    undosTotal="<<undosTotal<<endl;
  1232 	cout << "    undosAvail="<<undosAvail<<endl;
  1233 	cout << "       undoNum="<<undoNum<<endl;
  1234 	cout << "    ---------------------------"<<endl;
  1235 	cout << "    undoCom="<<undoCommand<<endl;
  1236 	cout << "    undoSel="<<undoSelection<<endl;
  1237 	cout << "    ---------------------------"<<endl;
  1238 	cout << "    redoCom="<<redoCommand<<endl;
  1239 	cout << "    redoSel="<<redoSelection<<endl;
  1240 	cout << "    ---------------------------"<<endl;
  1241 */	
  1242 	parseAtom (undoCommand);
  1243 	mapCenter->reposition();
  1244 
  1245 	//if (!redoSelection.isEmpty())
  1246 	//	select (redoSelection);
  1247 
  1248 	undosAvail--;
  1249 	if (undosAvail<1)
  1250 		// Undo not longer available now
  1251 		actionEditUndo->setEnabled (false);
  1252 	else	
  1253 		undoNum--; if (undoNum<1) undoNum=undosTotal;
  1254 
  1255 	blockSaveState=false;
  1256 /* TODO remove testing
  1257 	cout << "ME::undo() end\n";
  1258 	cout << "    undosAvail="<<undosAvail<<endl;
  1259 	cout << "       undoNum="<<undoNum<<endl;
  1260 	cout << "    ---------------------------"<<endl<<endl;
  1261 */
  1262 }
  1263 
  1264 void MapEditor::undoXML(const QString &undoSel, const QString &bakMapPath)
  1265 {
  1266 	QString bakMapDir=bakMapPath.left(bakMapPath.findRev("/"));
  1267 	QDir d(bakMapDir);
  1268 	QFile file (bakMapPath);
  1269 
  1270 	if (d.exists() )
  1271 	{
  1272 		// We need to parse saved XML data
  1273 		mapBuilderHandler handler;
  1274 		QXmlInputSource source( file);
  1275 		QXmlSimpleReader reader;
  1276 		reader.setContentHandler( &handler );
  1277 		reader.setErrorHandler( &handler );
  1278 		handler.setMapEditor( this );
  1279 		handler.setTmpDir ( bakMapDir );	// needed to load files with rel. path
  1280 		if (undoSel.isEmpty())
  1281 		{
  1282 			unselect();
  1283 			mapCenter->clear();
  1284 			handler.setLoadMode (NewMap);
  1285 		} else	
  1286 		{
  1287 			select (undoSel);
  1288 			handler.setLoadMode (ImportReplace);
  1289 		}	
  1290 		blockReposition=true;
  1291 		bool ok = reader.parse( source );
  1292 		blockReposition=false;
  1293 		if (! ok ) 
  1294 		{	
  1295 			// This should never ever happen
  1296 			QMessageBox::critical( 0, tr( "Critical Parse Error by reading backupFile" ),
  1297 								   tr( handler.errorProtocol() )+" in "+bakMapDir );
  1298 		}
  1299 	} else	
  1300 	{
  1301 		QMessageBox::critical( 0, tr( "Critical Error" ),
  1302 			tr("Temporary directory %1 used for undo is gone. \n"
  1303 			"I will create a new one, but at the moment no undo is available.\n"
  1304 			"Maybe you want to reload your original data.\n\n"
  1305 			"Sorry for any inconveniences.").arg(bakMapDir) );
  1306 		makeTmpDirs();	
  1307 	}							
  1308 }
  1309 
  1310 void MapEditor::pasteNoSave()
  1311 {
  1312 	// Finish open lineEdits
  1313 	if (lineedit) finishedLineEditNoSave();
  1314 
  1315 	load (clipboardDir+"/part.xml",ImportAdd);
  1316 }
  1317 
  1318 void MapEditor::cutNoSave()
  1319 {
  1320 	copy();
  1321 	deleteSelection();
  1322 }
  1323 
  1324 void MapEditor::paste()
  1325 {   
  1326 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  1327 				      typeid(*selection) == typeid(MapCenterObj))) 
  1328 	{
  1329 		saveState(selection);
  1330 		pasteNoSave();
  1331 		mapCenter->reposition();
  1332 		adjustCanvasSize();
  1333 	}
  1334 }
  1335 
  1336 void MapEditor::cut()
  1337 {
  1338 	saveState(selection->getParObj());
  1339 	copy();
  1340 	cutNoSave();
  1341 	mapCenter->reposition();
  1342 	adjustCanvasSize();
  1343 }
  1344 
  1345 void MapEditor::move(const int &x, const int &y)
  1346 {
  1347 	// TODO no saveState, because this is only internal at undo so far
  1348 	if (selection) selection->move(x,y);
  1349 	if (typeid(*selection) == typeid(FloatImageObj))
  1350 		((FloatImageObj*)selection)->setRelPos();
  1351 }
  1352 
  1353 void MapEditor::moveBranchUp()
  1354 {
  1355 	// Finish open lineEdits
  1356 	if (lineedit) finishedLineEditNoSave();
  1357 
  1358 	BranchObj* bo;
  1359 	BranchObj* par;
  1360 	if (typeid(*selection) == typeid(BranchObj)  ) 
  1361 	{
  1362 		bo=(BranchObj*)selection;
  1363 		par=(BranchObj*)(bo->getParObj());
  1364 		selection->unselect();
  1365 		selection=par->moveBranchUp (bo);
  1366 		selection->select();
  1367 		saveState("moveBranchDown ()",bo);
  1368 		mapCenter->reposition();
  1369 		ensureSelectionVisible();
  1370 	}
  1371 }
  1372 
  1373 void MapEditor::moveBranchDown()
  1374 {
  1375 	// Finish open lineEdits
  1376 	if (lineedit) finishedLineEditNoSave();
  1377 
  1378 	BranchObj* bo;
  1379 	BranchObj* par;
  1380 	if (typeid(*selection) == typeid(BranchObj)  ) 
  1381 	{
  1382 		bo=(BranchObj*)selection;
  1383 		par=(BranchObj*)(bo->getParObj());
  1384 		selection->unselect(); 
  1385 		selection=par->moveBranchDown(bo);
  1386 		selection->select();
  1387 		saveState("moveBranchUp ()",bo);
  1388 		mapCenter->reposition();
  1389 		ensureSelectionVisible();
  1390 	}	
  1391 }
  1392 
  1393 void MapEditor::editHeading()
  1394 {
  1395 	// Finish open lineEdits
  1396 	if (lineedit) finishedLineEditNoSave();
  1397 
  1398 	if (selection  &&  
  1399 		 (typeid(*selection) == typeid(BranchObj) || 
  1400 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1401 	{
  1402 		editingBO=(BranchObj*)selection;
  1403 		saveState("setHeading (\""+((BranchObj*)selection)->getHeading()+"\")",editingBO );
  1404 
  1405 		ensureSelectionVisible();
  1406 		QPoint p = worldMatrix().map(QPoint (editingBO->x(),editingBO->y()));
  1407 		lineedit->setGeometry(p.x()-contentsX(),p.y()-contentsY(),200,25);
  1408 		QString s=editingBO->getHeading();
  1409 		lineedit->setText(s);
  1410 		lineedit->setCursorPosition(1);
  1411 		if (actionSettingsAutoselectText->isOn() && !s.isEmpty() && actionSettingsPasteNewHeading->isOn() )
  1412 			lineedit->selectAll();
  1413 		lineedit->show();
  1414 		lineedit->grabKeyboard();
  1415 		lineedit->setFocus();
  1416 	}				
  1417 }
  1418 
  1419 void MapEditor::setHeading(const QString &s)
  1420 {
  1421 	// Internal function, no saveState needed
  1422 	if (selection  &&  
  1423 		 (typeid(*selection) == typeid(BranchObj) || 
  1424 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1425 	{
  1426 		((BranchObj*)selection)->setHeading(s);
  1427 		mapCenter->reposition();
  1428 		adjustCanvasSize();
  1429 		ensureSelectionVisible();
  1430 	}
  1431 }
  1432 
  1433 void MapEditor::setURL (const QString &s)
  1434 {
  1435 	// Internal function, no saveState needed
  1436 	if (selection  &&  
  1437 		 (typeid(*selection) == typeid(BranchObj) || 
  1438 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1439 	{
  1440 		((BranchObj*)selection)->setURL(s);
  1441 		mapCenter->reposition();
  1442 		adjustCanvasSize();
  1443 		ensureSelectionVisible();
  1444 	}
  1445 }
  1446 
  1447 void MapEditor::setVymLink (const QString &s)
  1448 {
  1449 	// Internal function, no saveState needed
  1450 	if (selection  &&  
  1451 		 (typeid(*selection) == typeid(BranchObj) || 
  1452 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1453 	{
  1454 		((BranchObj*)selection)->setVymLink(s);
  1455 		mapCenter->reposition();
  1456 		adjustCanvasSize();
  1457 		ensureSelectionVisible();
  1458 	}
  1459 }
  1460 
  1461 void MapEditor::addNewBranch(int pos)
  1462 {
  1463 	// Finish open lineEdits
  1464 	if (lineedit) finishedLineEditNoSave();
  1465 
  1466 	if (selection  &&  
  1467 		 (typeid(*selection) == typeid(BranchObj) || 
  1468 		  typeid(*selection) == typeid(MapCenterObj) ) ) 
  1469 	{
  1470 		saveState(selection);	//TODO undoCommand
  1471 
  1472 		BranchObj* bo1 = (BranchObj*) selection;
  1473 		bool wasScrolled=false;
  1474 		BranchObj *newbo=NULL;
  1475 		if (pos==0)
  1476 		{
  1477 			// save scroll state. If scrolled, automatically select
  1478 			// new branch in order to tmp unscroll parent...
  1479 			wasScrolled=bo1->isScrolled();
  1480 			newbo=bo1->addBranch();
  1481 		}	else 
  1482 		{
  1483 			BranchObj *parbo=(BranchObj*)(selection->getParObj());
  1484 			if (parbo)
  1485 			{
  1486 				if (pos<0)
  1487 					// add above selection
  1488 					newbo=parbo->insertBranch(bo1->getNum());
  1489 				else
  1490 					// add below selection
  1491 					newbo=parbo->insertBranch(bo1->getNum()+1);
  1492 			} else
  1493 				// This should not happen...
  1494 				return;
  1495 			
  1496 		}	
  1497 
  1498 		LinkableMapObj *oldselection=selection;
  1499 
  1500 		mapCenter->reposition();
  1501 		adjustCanvasSize();
  1502 		if (actionSettingsAutoedit->isOn() ||
  1503 			actionSettingsAutoselectHeading->isOn() )
  1504 		{
  1505 			selection->unselect();
  1506 			selection=newbo;
  1507 			selection->select();
  1508 			if (actionSettingsPasteNewHeading->isOn() )
  1509 			{
  1510 				BranchObj *bo2= (BranchObj*)selection;
  1511 				bo2->setHeading("");
  1512 			}	
  1513 			if (actionSettingsAutoedit->isOn() )
  1514 				editHeading();
  1515 			if (!actionSettingsAutoselectHeading->isOn()
  1516 				&& !wasScrolled)
  1517 			{
  1518 				selection->unselect();
  1519 				selection=oldselection;
  1520 				selection->select();
  1521 			}
  1522 		}	
  1523 	}	
  1524 }
  1525 
  1526 
  1527 void MapEditor::addNewBranchHere()
  1528 {
  1529 	// Finish open lineEdits
  1530 	if (lineedit) finishedLineEditNoSave();
  1531 
  1532 	if (selection  &&  
  1533 		 (typeid(*selection) == typeid(BranchObj) ) )
  1534 	{
  1535 		saveState(selection);
  1536 
  1537 		BranchObj* bo1 = (BranchObj*) selection;
  1538 		bool wasScrolled=false;
  1539 		BranchObj *newbo=NULL;
  1540 		BranchObj *parbo=(BranchObj*)(selection->getParObj());
  1541 		if (parbo)
  1542 		{
  1543 			// add below selection
  1544 			newbo=parbo->insertBranch(bo1->getNum()+1);
  1545 		} 
  1546 
  1547 		LinkableMapObj *oldselection=selection;
  1548 		((BranchObj*)selection)->moveBranchTo (newbo,-1);
  1549 
  1550 		mapCenter->reposition();
  1551 		adjustCanvasSize();
  1552 		if (actionSettingsAutoedit->isOn() ||
  1553 			actionSettingsAutoselectHeading->isOn() )
  1554 		{
  1555 			selection->unselect();
  1556 			selection=newbo;
  1557 			selection->select();
  1558 			if (actionSettingsPasteNewHeading->isOn() )
  1559 			{
  1560 				BranchObj *bo2= (BranchObj*)selection;
  1561 				bo2->setHeading("");
  1562 			}	
  1563 			if (actionSettingsAutoedit->isOn() )
  1564 				editHeading();
  1565 			if (!actionSettingsAutoselectHeading->isOn()
  1566 				&& !wasScrolled)
  1567 			{
  1568 				selection->unselect();
  1569 				selection=oldselection;
  1570 				selection->select();
  1571 			}
  1572 		}	
  1573 	}	
  1574 }
  1575 
  1576 void MapEditor::deleteSelection()
  1577 {
  1578 	// Finish open lineEdits
  1579 	if (lineedit) finishedLineEditNoSave();
  1580 
  1581 	if (selection  && typeid(*selection) ==typeid(BranchObj) ) 
  1582 	{
  1583 		if (selection->getDepth()>1)
  1584 			// Normal branch, save parent with childs
  1585 			saveState(selection->getParObj());
  1586 		else
  1587 			// Mainbranch, save whole map
  1588 			// TODO Better would be to insert mainbranch again at pos
  1589 			// But undoCommand is missing right now
  1590 			saveState();
  1591 		BranchObj* bo=dynamic_cast <BranchObj*> (selection);
  1592 		BranchObj* par=(BranchObj*)(bo->getParObj());
  1593 		bo->unselect();
  1594 		selection=NULL;
  1595 		par->removeBranch(bo);
  1596 		selection=par;
  1597 		selection->select();
  1598 		ensureSelectionVisible();
  1599 		mapCenter->reposition();
  1600 		adjustCanvasSize();
  1601 	}
  1602 	if (selection  && typeid(*selection) ==typeid(FloatImageObj) ) 
  1603 	{
  1604 		saveState(selection->getParObj());
  1605 		FloatImageObj* fio=dynamic_cast <FloatImageObj*> (selection);
  1606 		BranchObj* par=(BranchObj*)(fio->getParObj());
  1607 		fio->unselect();
  1608 		selection=NULL;
  1609 		par->removeFloatImage(fio);
  1610 		selection=par;
  1611 		selection->select();
  1612 		ensureSelectionVisible();
  1613 		mapCenter->reposition();
  1614 		adjustCanvasSize();
  1615 	}
  1616 }
  1617 
  1618 LinkableMapObj* MapEditor::getSelection()
  1619 {
  1620 	return selection;
  1621 }
  1622 
  1623 bool MapEditor::select (const QString &s)
  1624 {
  1625 	LinkableMapObj *lmo=mapCenter->findObjBySelect(s);
  1626 
  1627 	// Finally select the found object
  1628 	if (lmo)
  1629 	{
  1630 		if (selection) unselect();
  1631 		selection=lmo;
  1632 		selection->select();
  1633 		adjustCanvasSize();
  1634 		ensureSelectionVisible();
  1635 		return true;
  1636 	} 
  1637 	return false;
  1638 }
  1639 
  1640 void MapEditor::unselect()
  1641 {
  1642 	if (selection) 
  1643 	{
  1644 		selectionLast=selection;
  1645 		selection->unselect();
  1646 		selection=NULL;
  1647 	}
  1648 }	
  1649 
  1650 void MapEditor::reselect()
  1651 {
  1652 	if (selectionLast)
  1653 	{
  1654 		selection=selectionLast;
  1655 		selection->select();
  1656 		selectionLast=NULL;
  1657 	}
  1658 }	
  1659 
  1660 void MapEditor::selectNextBranch()
  1661 {
  1662 	// Increase number of branch
  1663 	if (selection)
  1664 	{
  1665 		QString s=selection->getSelectString();
  1666 		QString part;
  1667 		QString typ;
  1668 		QString num;
  1669 
  1670 		// Where am I? 
  1671 		part=s.section(",",-1);
  1672 		typ=part.left (3);
  1673 		num=part.right(part.length() - 3);
  1674 
  1675 		s=s.left (s.length() -num.length());
  1676 
  1677 		// Go to next lmo
  1678 		num=QString ("%1").arg(num.toUInt()+1);
  1679 
  1680 		s=s+num;
  1681 		
  1682 		// Try to select this one
  1683 		if (select (s)) return;
  1684 
  1685 		// We have no direct successor, 
  1686 		// try to increase the parental number in order to
  1687 		// find a successor with same depth
  1688 
  1689 		int d=selection->getDepth();
  1690 		int oldDepth=d;
  1691 		int i;
  1692 		bool found=false;
  1693 		bool b;
  1694 		while (!found && d>0)
  1695 		{
  1696 			s=s.section (",",0,d-1);
  1697 			// replace substring of current depth in s with "1"
  1698 			part=s.section(",",-1);
  1699 			typ=part.left (3);
  1700 			num=part.right(part.length() - 3);
  1701 
  1702 			if (d>1)
  1703 			{	
  1704 				// increase number of parent
  1705 				num=QString ("%1").arg(num.toUInt()+1);
  1706 				s=s.section (",",0,d-2) + ","+ typ+num;
  1707 			} else
  1708 			{
  1709 				// Special case, look at orientation
  1710 				if (selection->getOrientation()==OrientRightOfCenter)
  1711 					num=QString ("%1").arg(num.toUInt()+1);
  1712 				else	
  1713 					num=QString ("%1").arg(num.toUInt()-1);
  1714 				s=typ+num;
  1715 			}	
  1716 
  1717 			if (select (s))
  1718 				// pad to oldDepth, select the first branch for each depth
  1719 				for (i=d;i<oldDepth;i++)
  1720 				{
  1721 					b=select (s);
  1722 					if (b)
  1723 					{	
  1724 						if ( ((BranchObj*)selection)->countBranches()>0)
  1725 							s+=",bo:0";
  1726 						else	
  1727 							break;
  1728 					} else
  1729 						break;
  1730 				}	
  1731 
  1732 			// try to select the freshly built string
  1733 			found=select(s);
  1734 			d--;
  1735 		}
  1736 		return;
  1737 	}	
  1738 }
  1739 
  1740 void MapEditor::selectPrevBranch()
  1741 {
  1742 	// Decrease number of branch
  1743 	if (selection)
  1744 	{
  1745 		QString s=selection->getSelectString();
  1746 		QString part;
  1747 		QString typ;
  1748 		QString num;
  1749 
  1750 		// Where am I? 
  1751 		part=s.section(",",-1);
  1752 		typ=part.left (3);
  1753 		num=part.right(part.length() - 3);
  1754 
  1755 		s=s.left (s.length() -num.length());
  1756 
  1757 		// Go to next lmo
  1758 		num=QString ("%1").arg(num.toUInt()-1);
  1759 
  1760 		s=s+num;
  1761 		
  1762 		// Try to select this one
  1763 		if (select (s)) return;
  1764 
  1765 		// We have no direct precessor, 
  1766 		// try to decrease the parental number in order to
  1767 		// find a precessor with same depth
  1768 
  1769 		int d=selection->getDepth();
  1770 		int oldDepth=d;
  1771 		int i;
  1772 		bool found=false;
  1773 		bool b;
  1774 		while (!found && d>0)
  1775 		{
  1776 			s=s.section (",",0,d-1);
  1777 			// replace substring of current depth in s with "1"
  1778 			part=s.section(",",-1);
  1779 			typ=part.left (3);
  1780 			num=part.right(part.length() - 3);
  1781 
  1782 			if (d>1)
  1783 			{
  1784 				// decrease number of parent
  1785 				num=QString ("%1").arg(num.toUInt()-1);
  1786 				s=s.section (",",0,d-2) + ","+ typ+num;
  1787 			} else
  1788 			{
  1789 				// Special case, look at orientation
  1790 				if (selection->getOrientation()==OrientRightOfCenter)
  1791 					num=QString ("%1").arg(num.toUInt()-1);
  1792 				else	
  1793 					num=QString ("%1").arg(num.toUInt()+1);
  1794 				s=typ+num;
  1795 			}	
  1796 
  1797 			if (select(s))
  1798 				// pad to oldDepth, select the last branch for each depth
  1799 				for (i=d;i<oldDepth;i++)
  1800 				{
  1801 					b=select (s);
  1802 					if (b)
  1803 						if ( ((BranchObj*)selection)->countBranches()>0)
  1804 							s+=",bo:"+ QString ("%1").arg( ((BranchObj*)selection)->countBranches()-1 );
  1805 						else	
  1806 							break;
  1807 					else
  1808 						break;
  1809 				}	
  1810 			
  1811 			// try to select the freshly built string
  1812 			found=select(s);
  1813 			d--;
  1814 		}
  1815 		return;
  1816 	}	
  1817 }
  1818 
  1819 void MapEditor::selectUpperBranch()
  1820 {
  1821 	// Finish open lineEdits
  1822 	if (lineedit) finishedLineEditNoSave();
  1823 
  1824 	if (selection) 
  1825 	{
  1826 		if (typeid(*selection) == typeid(BranchObj))
  1827 		{
  1828 			if (selection->getOrientation()==OrientRightOfCenter)
  1829 				selectPrevBranch();
  1830 			else
  1831 				if (selection->getDepth()==1)
  1832 					selectNextBranch();
  1833 				else
  1834 					selectPrevBranch();
  1835 		}		
  1836 	}
  1837 }
  1838 
  1839 void MapEditor::selectLowerBranch()
  1840 {
  1841 	// Finish open lineEdits
  1842 	if (lineedit) finishedLineEditNoSave();
  1843 
  1844 	if (selection) 
  1845 	{
  1846 		if (typeid(*selection) == typeid(BranchObj))
  1847 		{
  1848 			if (selection->getOrientation()==OrientRightOfCenter)
  1849 				selectNextBranch();
  1850 			else
  1851 				if (selection->getDepth()==1)
  1852 					selectPrevBranch();
  1853 				else
  1854 					selectNextBranch();
  1855 		}		
  1856 	}
  1857 }
  1858 
  1859 
  1860 void MapEditor::selectLeftBranch()
  1861 {
  1862 	// Finish open lineEdits
  1863 	if (lineedit) finishedLineEditNoSave();
  1864 
  1865 	BranchObj* bo;
  1866 	BranchObj* par;
  1867 	if (selection) 
  1868 	{
  1869 		if (typeid(*selection) == typeid(MapCenterObj))
  1870 		{
  1871 			par=  (BranchObj*) selection;
  1872 			bo=par->getLastSelectedBranch();
  1873 			if (bo)
  1874 			{
  1875 				// Workaround for reselecting on left and right side
  1876 				if (bo->getOrientation()==OrientRightOfCenter)
  1877 				{
  1878 					bo=par->getLastBranch();
  1879 				}	
  1880 				if (bo)
  1881 				{
  1882 					par->unselect();
  1883 					selection=bo;
  1884 					selection->select();
  1885 					adjustCanvasSize();
  1886 					ensureSelectionVisible();
  1887 				}
  1888 			}	
  1889 		} else
  1890 		{
  1891 			par=(BranchObj*)(selection->getParObj());
  1892 			if (selection->getOrientation()==OrientRightOfCenter)
  1893 			{
  1894 				if (typeid(*selection) == typeid(BranchObj) ||
  1895 					typeid(*selection) == typeid(FloatImageObj))
  1896 				{
  1897 					selection->unselect();
  1898 					selection=par;
  1899 					selection->select();
  1900 					adjustCanvasSize();
  1901 					ensureSelectionVisible();
  1902 				}
  1903 			} else
  1904 			{
  1905 				if (typeid(*selection) == typeid(BranchObj) )
  1906 				{
  1907 					bo=((BranchObj*)selection)->getLastSelectedBranch();
  1908 					if (bo) 
  1909 					{
  1910 						selection->unselect();
  1911 						selection=bo;
  1912 						selection->select();
  1913 						adjustCanvasSize();
  1914 						ensureSelectionVisible();
  1915 					}
  1916 				}
  1917 			}
  1918 		}	
  1919 	}
  1920 }
  1921 
  1922 void MapEditor::selectRightBranch()
  1923 {
  1924 	// Finish open lineEdits
  1925 	if (lineedit) finishedLineEditNoSave();
  1926 
  1927 	BranchObj* bo;
  1928 	BranchObj* par;
  1929 
  1930 	if (selection) 
  1931 	{
  1932 		if (typeid(*selection) == typeid(MapCenterObj))
  1933 		{
  1934 			par=  (BranchObj*) selection;
  1935 			bo=par->getLastSelectedBranch();
  1936 			if (bo)
  1937 			{
  1938 				// Workaround for relecting on left and right side
  1939 				if (bo->getOrientation()==OrientLeftOfCenter)
  1940 					bo=par->getFirstBranch();
  1941 				if (bo)
  1942 				{
  1943 					par->unselect();
  1944 					selection=bo;
  1945 					selection->select();
  1946 					ensureSelectionVisible();
  1947 				}
  1948 			}
  1949 		} else
  1950 		{
  1951 			par=(BranchObj*)(selection->getParObj());
  1952 			if (selection->getOrientation()==OrientLeftOfCenter)
  1953 			{
  1954 				if (typeid(*selection) == typeid(BranchObj) ||
  1955 					typeid(*selection) == typeid(FloatImageObj))
  1956 				{
  1957 					selection->unselect();
  1958 					selection=par;
  1959 					selection->select();
  1960 					adjustCanvasSize();
  1961 					ensureSelectionVisible();
  1962 				}
  1963 			} else
  1964 			{
  1965 				if (typeid(*selection) == typeid(BranchObj) )
  1966 				{
  1967 					bo=((BranchObj*)selection)->getLastSelectedBranch();
  1968 					if (bo) 
  1969 					{
  1970 						selection->unselect();
  1971 						selection=bo;
  1972 						selection->select();
  1973 						adjustCanvasSize();
  1974 						ensureSelectionVisible();
  1975 					}
  1976 				}
  1977 			}
  1978 		}
  1979 	}
  1980 }
  1981 
  1982 void MapEditor::selectFirstBranch()
  1983 {
  1984 	// Finish open lineEdits
  1985 	if (lineedit) finishedLineEditNoSave();
  1986 
  1987 	BranchObj *bo1;
  1988 	BranchObj *bo2;
  1989 	BranchObj* par;
  1990 	if (selection) {
  1991 		if (typeid(*selection) == typeid(BranchObj))
  1992 		{
  1993 			bo1=  (BranchObj*) selection;
  1994 			par=(BranchObj*)(bo1->getParObj());
  1995 			bo2=par->getFirstBranch();
  1996 			if (bo2) {
  1997 				bo1->unselect();
  1998 				selection=bo2;
  1999 				selection->select();
  2000 				ensureSelectionVisible();
  2001 			}
  2002 		}		
  2003 		adjustCanvasSize();
  2004 	}
  2005 }
  2006 
  2007 void MapEditor::selectLastBranch()
  2008 {
  2009 	// Finish open lineEdits
  2010 	if (lineedit) finishedLineEditNoSave();
  2011 
  2012 	BranchObj *bo1;
  2013 	BranchObj *bo2;
  2014 	BranchObj* par;
  2015 	if (selection) {
  2016 		if (typeid(*selection) == typeid(BranchObj))
  2017 		{
  2018 			bo1=  (BranchObj*) selection;
  2019 			par=(BranchObj*)(bo1->getParObj());
  2020 			bo2=par->getLastBranch();
  2021 			if (bo2) {
  2022 				bo1->unselect();
  2023 				selection=bo2;
  2024 				selection->select();
  2025 				ensureSelectionVisible();
  2026 			}
  2027 		}		
  2028 		adjustCanvasSize();
  2029 	}
  2030 }
  2031 
  2032 void MapEditor::setColor(QColor c)
  2033 {
  2034 	actColor=c;
  2035 }
  2036 
  2037 void MapEditor::selectBackgroundColor()
  2038 {
  2039 	// Finish open lineEdits
  2040 	if (lineedit) finishedLineEditNoSave();
  2041 
  2042 	QColor col = QColorDialog::getColor( mapCanvas->backgroundColor(), this );
  2043 	if ( !col.isValid() ) return;
  2044 	setBackgroundColor( col );
  2045 	saveState();
  2046 }
  2047 
  2048 void MapEditor::setBackgroundColor(QColor c)
  2049 {
  2050 	mapCanvas->setBackgroundColor (c);
  2051 }
  2052 
  2053 QColor MapEditor::pickColor()
  2054 {
  2055 	if (selection) 
  2056 	{
  2057 		if (typeid(*selection) == typeid(BranchObj) ||
  2058 			typeid(*selection) == typeid(MapCenterObj))
  2059 		{
  2060 			BranchObj *bo=(BranchObj*)selection;
  2061 			actColor=bo->getColor(); 
  2062 		}    
  2063 	}
  2064 	return actColor;
  2065 }
  2066 
  2067 void MapEditor::colorItem()
  2068 {
  2069 	if (selection) 
  2070 	{
  2071 		if (typeid(*selection) == typeid(BranchObj) ||
  2072 			typeid(*selection) == typeid(MapCenterObj))
  2073 		{
  2074 			saveState(selection);	//TODO undoCommand
  2075 			BranchObj *bo=(BranchObj*)selection;
  2076 			bo->setColor(actColor, false); // color links, color childs
  2077 		}    
  2078 	}
  2079 }
  2080 
  2081 void MapEditor::colorBranch()
  2082 {
  2083 	if (selection) 
  2084 	{
  2085 		if (typeid(*selection) == typeid(BranchObj) ||
  2086 			typeid(*selection) == typeid(MapCenterObj))
  2087 		{
  2088 			saveState(selection);	//TODO undoCommand
  2089 			BranchObj *bo=(BranchObj*)selection;
  2090 			bo->setColor(actColor, true); // color links, color childs
  2091 		}    
  2092 	}
  2093 }
  2094 
  2095 
  2096 void MapEditor::toggleStandardFlag(QString f)
  2097 {
  2098 	if (selection)
  2099 	{
  2100 		saveState(selection);// TODO undoCommand	
  2101 		((BranchObj*)selection)->toggleStandardFlag (f,actionSettingsUseFlagGroups);
  2102 		adjustCanvasSize();
  2103 	}	
  2104 }
  2105 
  2106 void MapEditor::setViewCenter()
  2107 {
  2108 	// transform to CanvasView Coord:
  2109 	QPoint p=worldMatrix().map(movingCenter);
  2110 	center ( p.x(), p.y());
  2111 }
  2112 
  2113 
  2114 BranchObj* MapEditor::findText (QString s, bool cs)
  2115 {
  2116 	if (!itFind) 
  2117 	{	// Nothing found or new find process
  2118 		if (EOFind)
  2119 			// nothing found, start again
  2120 			EOFind=false;
  2121 		itFind=mapCenter->first();
  2122 	}	
  2123 	bool searching=true;
  2124 	bool foundNote=false;
  2125 	while (searching && !EOFind)
  2126 	{
  2127 		if (itFind)
  2128 		{
  2129 			// Searching in Note
  2130 			if (itFind->getNote().contains(s,cs))
  2131 			{
  2132 				if (selection!=itFind) 
  2133 				{
  2134 					if (selection) ((BranchObj*)selection)->unselect();
  2135 					selection=itFind;
  2136 					selection->select();
  2137 					adjustCanvasSize();
  2138 					ensureSelectionVisible();
  2139 				}
  2140 				if (textEditor->findText(s,cs)) 
  2141 				{
  2142 					searching=false;
  2143 					foundNote=true;
  2144 				}	
  2145 			}
  2146 			// Searching in Heading
  2147 			if (searching && itFind->getHeading().contains (s,cs) ) 
  2148 			{
  2149 				if (selection) ((BranchObj*)selection)->unselect();
  2150 				selection=itFind;
  2151 				selection->select();
  2152 				adjustCanvasSize();
  2153 				ensureSelectionVisible();
  2154 				searching=false;
  2155 			}
  2156 		}	
  2157 		if (!foundNote)
  2158 		{
  2159 			itFind=itFind->next();
  2160 			if (!itFind) EOFind=true;
  2161 		}
  2162 	}	
  2163 	if (!searching)
  2164 	{
  2165 		adjustCanvasSize();
  2166 		return (BranchObj*)selection;
  2167 	}	else
  2168 		return NULL;
  2169 }
  2170 
  2171 void MapEditor::findReset()
  2172 {	// Necessary if text to find changes during a find process
  2173 	itFind=NULL;
  2174 	EOFind=false;
  2175 }
  2176 
  2177 void MapEditor::openURL()
  2178 {
  2179 	if (selection )
  2180 	{
  2181 		if (typeid(*selection) == typeid(BranchObj) ||
  2182 			typeid(*selection) == typeid(MapCenterObj))
  2183 		{
  2184 			QString url=((BranchObj*)selection)->getURL();
  2185 
  2186 			QProcess *proc = new QProcess( this );
  2187 
  2188 			proc->addArgument( settings.readEntry("/vym/mainwindow/readerURL" ));
  2189 			proc->addArgument( url);
  2190 
  2191 			if ( !proc->start() ) 
  2192 				// error handling
  2193 				if (mainWindow->settingsURL() ) 
  2194 					openURL();
  2195 		}	
  2196 	}	
  2197 }
  2198 
  2199 void MapEditor::editURL()
  2200 {
  2201 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2202 			typeid(*selection) == typeid(MapCenterObj)) )
  2203 	{		
  2204 		bool ok;
  2205 		BranchObj *bo=(BranchObj*)selection;
  2206 		QString text = QInputDialog::getText(
  2207 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  2208 				bo->getURL(), &ok, this );
  2209 		if ( ok) 
  2210 		{
  2211 			// user entered something and pressed OK
  2212 			saveState("setURL (\""+bo->getURL()+"\")","setURL (\""+text+"\")");	
  2213 			bo->setURL (text);
  2214 			updateActions();
  2215 		}	
  2216 	}
  2217 }
  2218 
  2219 void MapEditor::editHeading2URL()
  2220 {
  2221 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2222 			typeid(*selection) == typeid(MapCenterObj)) )
  2223 	{		
  2224 		BranchObj *bo=(BranchObj*)selection;
  2225 		saveState("setURL (\""+bo->getURL()+"\")","setURL (\""+bo->getHeading()+"\")");	
  2226 		bo->setURL (bo->getHeading());
  2227 		updateActions();
  2228 	}
  2229 }	
  2230 
  2231 void MapEditor::editBugzilla2URL()
  2232 {
  2233 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2234 			typeid(*selection) == typeid(MapCenterObj)) )
  2235 	{		
  2236 		BranchObj *bo=(BranchObj*)selection;
  2237 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
  2238 		saveState("setURL (\""+bo->getURL()+"\")","setURL (\""+url+"\")");	
  2239 		bo->setURL (url);
  2240 		updateActions();
  2241 	}
  2242 }	
  2243 
  2244 void MapEditor::editFATE2URL()
  2245 {
  2246 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2247 			typeid(*selection) == typeid(MapCenterObj)) )
  2248 	{		
  2249 		BranchObj *bo=(BranchObj*)selection;
  2250 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
  2251 		saveState("setURL (\""+bo->getURL()+"\")","setURL (\""+url+"\")");	
  2252 		bo->setURL (url);
  2253 		updateActions();
  2254 	}
  2255 }	
  2256 
  2257 void MapEditor::editVymLink()
  2258 {
  2259 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2260 			typeid(*selection) == typeid(MapCenterObj)) )
  2261 	{		
  2262 		BranchObj *bo=(BranchObj*)selection;
  2263 		QFileDialog *fd=new QFileDialog( this,__VYM " - " +tr("Link to another map"));
  2264 		fd->addFilter (QString (tr("vym map") + " (*.vym)"));
  2265 		fd->setCaption(__VYM " - " +tr("Link to another map"));
  2266 		if (! bo->getVymLink().isEmpty() )
  2267 			fd->setSelection( bo->getVymLink() );
  2268 		fd->show();
  2269 
  2270 		QString fn;
  2271 		if ( fd->exec() == QDialog::Accepted )
  2272 		{
  2273 			saveState("setVymLink (\""+bo->getVymLink()+"\")","setVymLink (\""+fd->selectedFile()+"\")");	
  2274 			bo->setVymLink (fd->selectedFile() );
  2275 			updateActions();
  2276 			mapCenter->reposition();
  2277 			adjustCanvasSize();
  2278 			canvas()->update();
  2279 		}
  2280 	}
  2281 }
  2282 
  2283 void MapEditor::deleteVymLink()
  2284 {
  2285 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2286 			typeid(*selection) == typeid(MapCenterObj)) )
  2287 	{		
  2288 		BranchObj *bo=(BranchObj*)selection;
  2289 		saveState("setVymLink (\""+bo->getVymLink()+"\")","setVymLink (\"\")");	
  2290 		bo->setVymLink ("" );
  2291 		updateActions();
  2292 		mapCenter->reposition();
  2293 		adjustCanvasSize();
  2294 		canvas()->update();
  2295 	}
  2296 }
  2297 
  2298 QString MapEditor::getVymLink()
  2299 {
  2300 	if (selection && (typeid(*selection) == typeid(BranchObj) ||
  2301 			typeid(*selection) == typeid(MapCenterObj)) )
  2302 	{		
  2303 		return ((BranchObj*)selection)->getVymLink();
  2304 	}
  2305 	return "";
  2306 	
  2307 }
  2308 
  2309 void MapEditor::removeBranchHere()
  2310 {
  2311 	if (selection && (typeid(*selection) == typeid(BranchObj) ))
  2312 	{		
  2313 		BranchObj* bo=(BranchObj*)selection;
  2314 		BranchObj* par=(BranchObj*)(bo->getParObj());
  2315 		if (bo->getDepth()==1)
  2316 			saveState();
  2317 		else	
  2318 			saveState(selection->getParObj());	// TODO undoCommand
  2319 		QString sel=selection->getSelectString();
  2320 		unselect();
  2321 		par->removeBranchHere(bo);
  2322 		mapCenter->reposition();
  2323 		select (sel);
  2324 	}	
  2325 }
  2326 
  2327 void MapEditor::removeChilds()
  2328 {
  2329 	if (selection && (typeid(*selection) == typeid(BranchObj) ))
  2330 	{		
  2331 		saveState(selection->getParObj());
  2332 		((BranchObj*)selection)->removeChilds();
  2333 		mapCenter->reposition();
  2334 	}	
  2335 }
  2336 
  2337 void MapEditor::editMapInfo()
  2338 {
  2339 	ExtraInfoDialog dia;
  2340 	dia.setMapName (getFileName() );
  2341 	dia.setAuthor (mapCenter->getAuthor() );
  2342 	dia.setComment(mapCenter->getComment() );
  2343 
  2344 	// Calc some stats
  2345 	QString stats;
  2346     int i=0;
  2347     QCanvasItemList l=canvas()->allItems();
  2348     for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) 
  2349         i++;
  2350     stats+=QString ("%1 items on canvas\n").arg (i,6);
  2351 
  2352 	uint b=0;
  2353 	uint f=0;
  2354 	uint n=0;
  2355 	uint xl=0;
  2356 	BranchObj *bo;
  2357 	bo=mapCenter->first();
  2358 	while (bo) 
  2359 	{
  2360 		if (!bo->getNote().isEmpty() ) n++;
  2361 		f+= bo->countFloatImages();
  2362 		b++;
  2363 		xl+=bo->countXLinks();
  2364 		bo=bo->next();
  2365 	}
  2366     stats+=QString ("%1 branches\n").arg (b-1,6);
  2367     stats+=QString ("%1 xLinks \n").arg (xl,6);
  2368     stats+=QString ("%1 notes\n").arg (n,6);
  2369     stats+=QString ("%1 images\n").arg (f,6);
  2370 	dia.setStats (stats);
  2371 
  2372 	// Finally show dialog
  2373 	if (dia.exec() == QDialog::Accepted)
  2374 	{
  2375 		saveState();	//TODO undoCommand
  2376 		mapCenter->setAuthor (dia.getAuthor() );
  2377 		mapCenter->setComment (dia.getComment() );
  2378 	}
  2379 }
  2380 
  2381 void MapEditor::updateActions()
  2382 {
  2383 	QAction *a;
  2384 	if (getLinkColorHint()==HeadingColor) 
  2385 		actionFormatLinkColorHint->setOn(true);
  2386 	else	
  2387 		actionFormatLinkColorHint->setOn(false);
  2388 
  2389 	switch (linkstyle)
  2390 	{
  2391 		case StyleLine: 
  2392 			actionFormatLinkStyleLine->setOn(true);
  2393 			break;
  2394 		case StyleParabel:
  2395 			actionFormatLinkStyleParabel->setOn(true);
  2396 			break;
  2397 		case StylePolyLine:	
  2398 			actionFormatLinkStylePolyLine->setOn(true);
  2399 			break;
  2400 		case StylePolyParabel:	
  2401 			actionFormatLinkStylePolyParabel->setOn(true);
  2402 			break;
  2403 		default:
  2404 			break;
  2405 	}	
  2406 
  2407 	QPixmap pix( 16, 16 );
  2408     pix.fill( mapCanvas->backgroundColor() );
  2409     actionFormatBackColor->setIconSet( pix );
  2410     pix.fill( defLinkColor );
  2411     actionFormatLinkColor->setIconSet( pix );
  2412 
  2413 	actionEditUndo->setEnabled( mapChanged );
  2414 	actionFileSave->setEnabled( mapUnsaved );
  2415 
  2416 	if (selection)
  2417 	{
  2418 		if ( (typeid(*selection) == typeid(BranchObj)) || 
  2419 			(typeid(*selection) == typeid(MapCenterObj))  )
  2420 		{
  2421 			BranchObj *bo=(BranchObj*)selection;
  2422 			// Take care of links
  2423 			if (bo->countXLinks()==0)
  2424 			{
  2425 				branchLinksContextMenu->clear();
  2426 				branchLinksContextMenu->insertItem ("No xLink available");
  2427 				branchLinksContextMenuDup->clear();
  2428 				branchLinksContextMenuDup->insertItem ("No xLink available");
  2429 				
  2430 			} else
  2431 			{
  2432 				BranchObj *bot;
  2433 				QString s;
  2434 				branchLinksContextMenu->clear();
  2435 				branchLinksContextMenuDup->clear();
  2436 				for (int i=0; i<=bo->countXLinks();i++)
  2437 				{
  2438 					bot=bo->XLinkTargetAt(i);
  2439 					if (bot)
  2440 					{
  2441 						s=bot->getHeading();
  2442 						if (s.length()>25)
  2443 							s=s.left(25)+"...";
  2444 						branchLinksContextMenu->insertItem (s);
  2445 						branchLinksContextMenuDup->insertItem (s);
  2446 					}	
  2447 				}
  2448 			}
  2449 
  2450 			standardFlagsDefault->setEnabled (true);
  2451 
  2452 			if ( bo->getURL().isEmpty() )
  2453 				actionEditOpenURL->setEnabled (false);
  2454 			else	
  2455 				actionEditOpenURL->setEnabled (true);
  2456 
  2457 			if ( bo->getVymLink().isEmpty() )
  2458 			{
  2459 				actionEditOpenVymLink->setEnabled (false);
  2460 				actionEditDeleteVymLink->setEnabled (false);
  2461 			} else	
  2462 			{
  2463 				actionEditOpenVymLink->setEnabled (true);
  2464 				actionEditDeleteVymLink->setEnabled (true);
  2465 			}	
  2466 
  2467 			actionEditCopy->setEnabled (true);	
  2468 			actionEditCut->setEnabled (true);	
  2469 			if (!clipboardEmpty)
  2470 				actionEditPaste->setEnabled (true);	
  2471 			else	
  2472 				actionEditPaste->setEnabled (false);	
  2473 			for (a=actionListBranches.first();a;a=actionListBranches.next())
  2474 				a->setEnabled(true);
  2475 			actionEditDelete->setEnabled (true);
  2476 			actionEditToggleFloatExport->setEnabled (false);
  2477 			switch (selection->getFrameType())
  2478 			{
  2479 				case NoFrame: 
  2480 					actionFormatFrameNone->setOn(true);
  2481 					break;
  2482 				case Rectangle:
  2483 					actionFormatFrameRectangle->setOn(true);
  2484 					break;
  2485 				default:
  2486 					break;
  2487 			}	
  2488 			actionFormatIncludeImagesVer->setOn
  2489 				( ((BranchObj*)selection)->getIncludeImagesVer());
  2490 			actionFormatIncludeImagesHor->setOn
  2491 				( ((BranchObj*)selection)->getIncludeImagesHor());
  2492 			actionFormatHideLinkUnselected->setOn
  2493 				(selection->getHideLinkUnselected());
  2494 		}
  2495 		if ( (typeid(*selection) == typeid(FloatImageObj)) )
  2496 		{
  2497 			standardFlagsDefault->setEnabled (false);
  2498 
  2499 			actionEditOpenURL->setEnabled (false);
  2500 			actionEditOpenVymLink->setEnabled (false);
  2501 			actionEditDeleteVymLink->setEnabled (false);	
  2502 
  2503 			actionEditCopy->setEnabled (true);
  2504 			actionEditCut->setEnabled (true);	
  2505 			actionEditPaste->setEnabled (false);	//FIXME
  2506 			for (a=actionListBranches.first();a;a=actionListBranches.next())
  2507 				a->setEnabled(false);
  2508 			actionEditDelete->setEnabled (true);
  2509 			actionEditToggleFloatExport->setOn
  2510 				( ((FloatImageObj*)selection)->getFloatExport() );
  2511 			actionFormatHideLinkUnselected->setOn
  2512 				( selection->getHideLinkUnselected());
  2513 		}
  2514 
  2515 	} else
  2516 	{
  2517 		standardFlagsDefault->setEnabled (false);
  2518 
  2519 		actionEditCopy->setEnabled (false);	
  2520 		actionEditCut->setEnabled (false);	
  2521 		actionEditPaste->setEnabled (false);	
  2522 		for (a=actionListBranches.first();a;a=actionListBranches.next())
  2523 			a->setEnabled(false);
  2524 
  2525 		actionEditOpenURL->setEnabled (false);
  2526 		actionEditOpenVymLink->setEnabled (false);
  2527 		actionEditDeleteVymLink->setEnabled (false);	
  2528 		actionEditHeading2URL->setEnabled (false);	
  2529 		actionEditDelete->setEnabled (false);
  2530 		actionEditToggleFloatExport->setEnabled (false);
  2531 	}	
  2532 }
  2533 
  2534 void MapEditor::updateNoteFlag()
  2535 {
  2536 	if (selection)
  2537 		if ( (typeid(*selection) == typeid(BranchObj)) || 
  2538 			(typeid(*selection) == typeid(MapCenterObj))  )
  2539 			((BranchObj*)selection)->updateNoteFlag();
  2540 }
  2541 
  2542 void MapEditor::setLinkStyle (LinkStyle ls)
  2543 {
  2544 	linkstyle=ls;
  2545 
  2546 	saveState();	// TODO undoCommand
  2547 	BranchObj *bo;
  2548 	bo=mapCenter->first();
  2549 	bo=bo->next();
  2550 	while (bo) 
  2551 	{
  2552 		bo->setLinkStyle(bo->getDefLinkStyle());
  2553 		bo=bo->next();
  2554 	}
  2555 	mapCenter->reposition();
  2556 }
  2557 
  2558 LinkStyle MapEditor::getLinkStyle ()
  2559 {
  2560 	return linkstyle;
  2561 }	
  2562 
  2563 void MapEditor::setLinkColor(QColor c)
  2564 {
  2565 	defLinkColor=c;
  2566 	updateActions();
  2567 }
  2568 
  2569 void MapEditor::setLinkColorHint()
  2570 {
  2571 	// called from setLinkColorHint(lch) or at end of parse
  2572 	BranchObj *bo;
  2573 	bo=mapCenter->first();
  2574 	while (bo) 
  2575 	{
  2576 		bo->setLinkColor();
  2577 		bo=bo->next();
  2578 	}
  2579 }
  2580 
  2581 void MapEditor::setLinkColorHint(LinkColorHint lch)
  2582 {
  2583 	linkcolorhint=lch;
  2584 	setLinkColorHint();
  2585 }
  2586 
  2587 void MapEditor::toggleLinkColorHint()
  2588 {
  2589 	if (linkcolorhint==HeadingColor)
  2590 		linkcolorhint=DefaultColor;
  2591 	else	
  2592 		linkcolorhint=HeadingColor;
  2593 	BranchObj *bo;
  2594 	bo=mapCenter->first();
  2595 	while (bo) 
  2596 	{
  2597 		bo->setLinkColor();
  2598 		bo=bo->next();
  2599 	}
  2600 }
  2601 
  2602 LinkColorHint MapEditor::getLinkColorHint()
  2603 {
  2604 	return linkcolorhint;
  2605 }
  2606 
  2607 QColor MapEditor::getDefLinkColor()
  2608 {
  2609 	return defLinkColor;
  2610 }
  2611 
  2612 void MapEditor::setDefXLinkColor(QColor col)
  2613 {
  2614 	defXLinkColor=col;
  2615 }
  2616 
  2617 QColor MapEditor::getDefXLinkColor()
  2618 {
  2619 	return defXLinkColor;
  2620 }
  2621 
  2622 void MapEditor::setDefXLinkWidth (int w)
  2623 {
  2624 	defXLinkWidth=w;
  2625 }
  2626 
  2627 int MapEditor::getDefXLinkWidth()
  2628 {
  2629 	return defXLinkWidth;
  2630 }
  2631 
  2632 void MapEditor::selectLinkColor()
  2633 {
  2634 	// Finish open lineEdits
  2635 	if (lineedit) finishedLineEditNoSave();
  2636 
  2637 	QColor col = QColorDialog::getColor( defLinkColor, this );
  2638 	if ( !col.isValid() ) return;
  2639 	setLinkColor( col );
  2640 	saveState();	//TODO undoCommand
  2641 
  2642 }
  2643 
  2644 void MapEditor::toggleScroll()
  2645 {
  2646 	if (selection && (typeid(*selection) == typeid(BranchObj)) )
  2647 	{
  2648 		BranchObj *bo=((BranchObj*)selection);
  2649 		if (bo->countBranches()==0) return;
  2650 		if (bo->getDepth()==0) return;
  2651 		saveState(selection);
  2652 		bo->toggleScroll();
  2653 		adjustCanvasSize();
  2654 		canvas()->update();
  2655 	}
  2656 }
  2657 
  2658 void MapEditor::unScrollAll()
  2659 {
  2660 	BranchObj *bo;
  2661 	bo=mapCenter->first();
  2662 	while (bo) 
  2663 	{
  2664 		if (bo->isScrolled()) bo->toggleScroll();
  2665 		bo=bo->next();
  2666 	}
  2667 }
  2668 
  2669 void MapEditor::loadFloatImage ()
  2670 {
  2671 	if (selection && 
  2672 		(typeid(*selection) == typeid(BranchObj)) || 
  2673 		(typeid(*selection) == typeid(MapCenterObj))  )
  2674 	{
  2675 		BranchObj *bo=((BranchObj*)selection);
  2676 
  2677 		QFileDialog *fd=new QFileDialog( this);
  2678 		fd->setMode (QFileDialog::ExistingFiles);
  2679 		fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  2680 		ImagePreview *p =new ImagePreview (fd);
  2681 		fd->setContentsPreviewEnabled( TRUE );
  2682 		fd->setContentsPreview( p, p );
  2683 		fd->setPreviewMode( QFileDialog::Contents );
  2684 		fd->setCaption(__VYM " - " +tr("Load image"));
  2685 		fd->setDir (lastImageDir);
  2686 		fd->show();
  2687 
  2688 		QString fn;
  2689 		if ( fd->exec() == QDialog::Accepted )
  2690 		{
  2691 			saveState(selection);
  2692 			lastImageDir=fn.left(fn.findRev ("/"));
  2693 			QStringList flist = fd->selectedFiles();
  2694 			QStringList::Iterator it = flist.begin();
  2695 			while( it != flist.end() ) 
  2696 			{
  2697 				fn = *it;
  2698 				bo->addFloatImage();
  2699 				// TODO check if load was successful
  2700 				bo->getLastFloatImage()->load(*it);
  2701 				bo->getLastFloatImage()->setOriginalFilename(fn);
  2702 				++it;
  2703 			}
  2704 
  2705 			mapCenter->reposition();
  2706 			adjustCanvasSize();
  2707 			canvas()->update();
  2708 		}
  2709 		delete (p);
  2710 		delete (fd);
  2711 	}
  2712 }
  2713 
  2714 void MapEditor::saveFloatImage (int item)
  2715 {
  2716 	if (selection && 
  2717 		(typeid(*selection) == typeid(FloatImageObj)) )
  2718 	{
  2719 		FloatImageObj *fio=((FloatImageObj*)selection);
  2720 		const char* fmt = saveImageFormatMenu->text(item);
  2721 
  2722 		QFileDialog *fd=new QFileDialog( this, tr("vym - save image as") + fmt);
  2723 		fd->addFilter ("PNG (*.png)");
  2724 		fd->addFilter ("BMP (*.bmp)");
  2725 		fd->addFilter ("XBM (*.xbm)");
  2726 		fd->addFilter ("JPG (*.jpg)");
  2727 		fd->addFilter ("XPM (*.xpm)");
  2728 		fd->addFilter ("GIF (*.gif)");
  2729 		fd->addFilter ("PNM (*.pnm)");
  2730 		fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  2731 		fd->setCaption(__VYM " - " +tr("Save image as %1").arg(fmt));
  2732 		fd->setMode( QFileDialog::AnyFile );
  2733 		fd->setSelection (fio->getOriginalFilename());
  2734 		fd->show();
  2735 
  2736 		QString fn;
  2737 		if ( fd->exec() == QDialog::Accepted )
  2738 		{
  2739 			if (QFile (fd->selectedFile()).exists() )
  2740 			{
  2741 				QMessageBox mb( __VYM,
  2742 					tr("The file %1 exists already.\n"
  2743 					"Do you want to overwrite it?").arg(fd->selectedFile()),
  2744 				QMessageBox::Warning,
  2745 				QMessageBox::Yes | QMessageBox::Default,
  2746 				QMessageBox::Cancel | QMessageBox::Escape,
  2747 				QMessageBox::QMessageBox::NoButton );
  2748 
  2749 				mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
  2750 				mb.setButtonText( QMessageBox::No, tr("Cancel"));
  2751 				switch( mb.exec() ) 
  2752 				{
  2753 					case QMessageBox::Yes:
  2754 						// save 
  2755 						break;;
  2756 					case QMessageBox::Cancel:
  2757 						// do nothing
  2758 						return;
  2759 						break;
  2760 				}
  2761 			}
  2762 			fio->save (fd->selectedFile(),fmt);
  2763 		}
  2764 	}
  2765 }
  2766 
  2767 void MapEditor::toggleFloatExport()
  2768 {
  2769 	if (selection && 
  2770 		(typeid(*selection) == typeid(FloatImageObj))|| 
  2771 		(typeid(*selection) == typeid(FloatObj)) )
  2772 	{
  2773 		FloatImageObj *fio=((FloatImageObj*)selection);
  2774 		fio->setFloatExport (actionEditToggleFloatExport->isOn() );
  2775 	}
  2776 }
  2777 
  2778 void MapEditor::setFrame(const FrameType &t)
  2779 {
  2780 	if (selection && 
  2781 		(typeid(*selection) == typeid(BranchObj)) || 
  2782 		(typeid(*selection) == typeid(MapCenterObj))  )
  2783 	{
  2784 		selection->setFrameType (t);
  2785 		mapCenter->reposition();
  2786 		selection->updateLink();
  2787 	}
  2788 }
  2789 
  2790 void MapEditor::setIncludeImagesVer(bool b)
  2791 {
  2792 	if (selection && 
  2793 		(typeid(*selection) == typeid(BranchObj)) || 
  2794 		(typeid(*selection) == typeid(MapCenterObj))  )
  2795 		((BranchObj*)selection)->setIncludeImagesVer(b);
  2796 		mapCenter->reposition();
  2797 }
  2798 
  2799 void MapEditor::setIncludeImagesHor(bool b)
  2800 {
  2801 	if (selection && 
  2802 		(typeid(*selection) == typeid(BranchObj)) || 
  2803 		(typeid(*selection) == typeid(MapCenterObj))  )
  2804 		((BranchObj*)selection)->setIncludeImagesHor(b);
  2805 		mapCenter->reposition();
  2806 }
  2807 
  2808 void MapEditor::setHideLinkUnselected (bool b)
  2809 {
  2810 	if (selection && 
  2811 		(typeid(*selection) == typeid(BranchObj)) || 
  2812 		(typeid(*selection) == typeid(MapCenterObj))  ||
  2813 		(typeid(*selection) == typeid(FloatImageObj)) )
  2814 		selection->setHideLinkUnselected(b);
  2815 }
  2816 
  2817 void MapEditor::importDir(BranchObj *dst, QDir d)
  2818 {
  2819 	if (selection && 
  2820 		(typeid(*selection) == typeid(BranchObj)) || 
  2821 		(typeid(*selection) == typeid(MapCenterObj))  )
  2822 	{
  2823 		BranchObj *bo;
  2824 		
  2825 		// Traverse directories
  2826 		d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
  2827 		const QFileInfoList *dirlist = d.entryInfoList();
  2828 		QFileInfoListIterator itdir( *dirlist );
  2829 		QFileInfo *fi;
  2830 
  2831 		while ( (fi = itdir.current()) != 0 ) 
  2832 		{
  2833 			if (fi->fileName() != "." && fi->fileName() != ".." )
  2834 			{
  2835 				dst->addBranch();
  2836 				bo=dst->getLastBranch();
  2837 				bo->setHeading (fi->fileName() );
  2838 				bo->setColor (QColor("blue"),false);
  2839 				bo->toggleScroll();
  2840 				if ( !d.cd(fi->fileName()) ) 
  2841 					QMessageBox::critical (0,tr("Critical Import Error"),tr("Cannot find the directory %1").arg(fi->fileName()));
  2842 				else 
  2843 				{
  2844 					// Recursively add subdirs
  2845 					importDir (bo,d);
  2846 					d.cdUp();
  2847 				}
  2848 			}	
  2849 			++itdir;
  2850 		}		
  2851 		// Traverse files
  2852 		d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
  2853 		const QFileInfoList *filelist = d.entryInfoList();
  2854 		QFileInfoListIterator itfile( *filelist );
  2855 
  2856 		while ( (fi = itfile.current()) != 0 ) 
  2857 		{
  2858 			dst->addBranch();
  2859 			bo=dst->getLastBranch();
  2860 			bo->setHeading (fi->fileName() );
  2861 			bo->setColor (QColor("black"),false);
  2862 			if (fi->fileName().right(4) == ".vym" )
  2863 				bo->setVymLink (fi->filePath());
  2864 
  2865 			++itfile;
  2866 		}	
  2867 	}		
  2868 }
  2869 
  2870 void MapEditor::importDir()
  2871 {
  2872 	if (selection && 
  2873 		(typeid(*selection) == typeid(BranchObj)) || 
  2874 		(typeid(*selection) == typeid(MapCenterObj))  )
  2875 	{
  2876 		QFileDialog *fd=new QFileDialog( this,__VYM " - " +tr("Choose directory structure to import"));
  2877 		fd->setMode (QFileDialog::DirectoryOnly);
  2878 		fd->addFilter (QString (tr("vym map") + " (*.vym)"));
  2879 		fd->setCaption(__VYM " - " +tr("Choose directory structure to import"));
  2880 		fd->show();
  2881 
  2882 		QString fn;
  2883 		if ( fd->exec() == QDialog::Accepted )
  2884 		{
  2885 			BranchObj *bo=((BranchObj*)selection);
  2886 			importDir (bo,QDir(fd->selectedFile()) );
  2887 			mapCenter->reposition();
  2888 			adjustCanvasSize();
  2889 			canvas()->update();
  2890 		}
  2891 	}	
  2892 }
  2893 
  2894 void MapEditor::followXLink(int i)
  2895 {
  2896 	if (selection && 
  2897 		(typeid(*selection) == typeid(BranchObj)) || 
  2898 		(typeid(*selection) == typeid(MapCenterObj))  )
  2899 	{
  2900 		BranchObj *bo=((BranchObj*)selection)->XLinkTargetAt(i);
  2901 		if (bo) 
  2902 		{
  2903 			selection->unselect();
  2904 			selection=bo;
  2905 			selection->select();
  2906 			ensureSelectionVisible();
  2907 		}
  2908 	}
  2909 }
  2910 
  2911 void MapEditor::editXLink(int i)
  2912 {
  2913 	if (selection && 
  2914 		(typeid(*selection) == typeid(BranchObj)) || 
  2915 		(typeid(*selection) == typeid(MapCenterObj))  )
  2916 	{
  2917 		XLinkObj *xlo=((BranchObj*)selection)->XLinkAt(i);
  2918 		if (xlo) 
  2919 		{
  2920 			EditXLinkDialog dia;
  2921 			dia.setXLink (xlo);
  2922 			dia.setSelection(selection);
  2923 			if (dia.exec() == QDialog::Accepted)
  2924 			{
  2925 				if (dia.useSettingsGlobal() )
  2926 				{
  2927 					setDefXLinkColor (xlo->getColor() );
  2928 					setDefXLinkWidth (xlo->getWidth() );
  2929 				}
  2930 				if (dia.deleteXLink())
  2931 					((BranchObj*)selection)->deleteXLinkAt(i);
  2932 				saveState();	//TODO undoCommand
  2933 			}
  2934 		}	
  2935 	}
  2936 }
  2937 
  2938 void MapEditor::testFunction()
  2939 {
  2940 	cout << "MapEditor::testFunction() called\n";
  2941 	adjustCanvasSize();
  2942 
  2943 	/*
  2944 	if (selection && (typeid(*selection) == typeid(BranchObj)))
  2945 	{
  2946 		cout << "Note:\n"<<((BranchObj*)selection)->getNoteOpenDoc()<<endl;
  2947 	}
  2948 	*/
  2949 }
  2950 
  2951 void MapEditor::ensureSelectionVisible()
  2952 {
  2953 	if (selection)
  2954 	{
  2955 		LinkableMapObj* lmo= dynamic_cast <LinkableMapObj*> (selection);
  2956 		QPoint p;
  2957 		if (selection->getOrientation() == OrientLeftOfCenter)
  2958 			p= worldMatrix().map(QPoint (lmo->x(),lmo->y()));
  2959 		else	
  2960 			p= worldMatrix().map(QPoint (lmo->x()+lmo->width(),lmo->y()+lmo->height()));
  2961 		ensureVisible (p.x(), p.y() );
  2962 	}
  2963 
  2964 }
  2965 
  2966 void MapEditor::updateViewCenter()
  2967 {
  2968 	// Update movingCenter, so that we can zoom comfortably later
  2969 	QRect rc = QRect( contentsX(), contentsY(),
  2970 				  visibleWidth(), visibleHeight() );
  2971 	QRect canvasRect = inverseWorldMatrix().mapRect(rc);
  2972 	movingCenter.setX((canvasRect.right() + canvasRect.left())/2);
  2973 	movingCenter.setY((canvasRect.top() + canvasRect.bottom())/2);
  2974 }
  2975 
  2976 void MapEditor::contentsContextMenuEvent ( QContextMenuEvent * e )
  2977 {
  2978 	// Lineedits are already closed by preceding
  2979 	// mouseEvent, we don't need to close here.
  2980 
  2981     QPoint p = inverseWorldMatrix().map(e->pos());
  2982     LinkableMapObj* lmo=mapCenter->findMapObj(p, NULL);
  2983 	
  2984     if (lmo) 
  2985 	{	// MapObj was found
  2986 		if (selection != lmo)
  2987 		{
  2988 			// select the MapObj
  2989 			if (selection) selection->unselect();
  2990 			selection=lmo;
  2991 			selection->select();
  2992 			adjustCanvasSize();
  2993 		}
  2994 		// Context Menu 
  2995 		if (selection) 
  2996 		{
  2997 			if (typeid(*selection)==typeid(BranchObj) ||
  2998 				typeid(*selection)==typeid(MapCenterObj) )
  2999 			{
  3000 				// Context Menu on branch or mapcenter
  3001 				updateActions();
  3002 				branchContextMenu->popup(e->globalPos() );
  3003 			}	
  3004 			if (typeid(*selection)==typeid(FloatImageObj))
  3005 			{
  3006 				// Context Menu on floatimage
  3007 				updateActions();
  3008 				floatimageContextMenu->popup(e->globalPos() );
  3009 			}	
  3010 		}	
  3011 	} else 
  3012 	{ // No MapObj found, we are on the Canvas itself
  3013 		// Context Menu on Canvas
  3014 		updateActions();
  3015 		canvasContextMenu->popup(e->globalPos() );
  3016     } 
  3017 }
  3018 
  3019 void MapEditor::contentsMousePressEvent(QMouseEvent* e)
  3020 {
  3021 	// Finish open lineEdits
  3022 	if (lineedit) finishedLineEditNoSave();
  3023 	
  3024     QPoint p = inverseWorldMatrix().map(e->pos());
  3025     LinkableMapObj* lmo=mapCenter->findMapObj(p, NULL);
  3026 	
  3027 	// Special case: CTRL is pressed
  3028 	if (e->state() & QMouseEvent::ControlButton)
  3029 	{
  3030 		if (actionModModeColor->isOn())
  3031 		{
  3032 			if (e->state() & QMouseEvent::ControlButton)
  3033 			{
  3034 				pickingColor=true;
  3035 				setCursor (pickColorCursor);
  3036 				return;
  3037 			}
  3038 		} 
  3039 		if (actionModModeLink->isOn())
  3040 		{	
  3041 			BranchObj *bo_begin=NULL;
  3042 			if (lmo)
  3043 				bo_begin=(BranchObj*)(lmo);
  3044 			else	
  3045 				if (selection && 
  3046 					((typeid(*selection) == typeid(BranchObj)) || 
  3047 					(typeid(*selection) == typeid(MapCenterObj)))  )
  3048 				bo_begin=(BranchObj*)selection;
  3049 			if (bo_begin)	
  3050 			{
  3051 				drawingLink=true;
  3052 				linkingObj_src=bo_begin;
  3053 				tmpXLink=new XLinkObj (mapCanvas);
  3054 				tmpXLink->setBegin (bo_begin);
  3055 				tmpXLink->setEnd   (p);
  3056 				tmpXLink->setColor(defXLinkColor);
  3057 				tmpXLink->setWidth(defXLinkWidth);
  3058 				tmpXLink->updateXLink();
  3059 				tmpXLink->setVisibility (true);
  3060 				return;
  3061 			} 
  3062 		}	
  3063 	}
  3064 
  3065     if (lmo) 
  3066 	{	// MapObj was found
  3067 		if (selection != lmo)
  3068 		{
  3069 			// select the MapObj
  3070 			if (selection) selection->unselect();
  3071 			selection=lmo;
  3072 			selection->select();
  3073 				
  3074 			adjustCanvasSize();
  3075 		}
  3076 
  3077 		// Check, if systemFlag clicked
  3078 		if (typeid(*selection)==typeid(BranchObj) ||
  3079 			typeid(*selection)==typeid(MapCenterObj) )
  3080 		{
  3081 			QString foname=((BranchObj*)selection)->getSystemFlagName(p);
  3082 			if (!foname.isEmpty())
  3083 			{
  3084 				// Do not move, if systemFlag clicked
  3085 				if (foname=="url") 
  3086 					openURL();
  3087 				else
  3088 					if (foname=="vymLink")
  3089 					{
  3090 						mainWindow->editOpenVymLink();
  3091 						// tabWidget may change, better return now
  3092 						// before segfaulting...
  3093 						return;
  3094 					} else
  3095 						if (foname=="note")
  3096 							mainWindow->windowToggleNoteEditor();
  3097 			}			
  3098 		}	
  3099 			
  3100 		// Left Button	    Move Branches
  3101 		if (e->button() == QMouseEvent::LeftButton )
  3102 		{
  3103 			movingObj_start.setX( p.x() - selection->x() );	
  3104 			movingObj_start.setY( p.y() - selection->y() );	
  3105 			movingObj_orgPos.setX (lmo->x() );
  3106 			movingObj_orgPos.setY (lmo->y() );
  3107 
  3108 			// If modMode==copy, then we want to "move" the _new_ object around
  3109 			// then we need the offset from p to the _old_ selection, because of tmp
  3110 			if (actionModModeCopy->isOn() &&
  3111 				e->state() & QMouseEvent::ControlButton)
  3112 			{
  3113 				if (typeid(*selection)==typeid(BranchObj) )
  3114 				{
  3115 					copyingObj=true;
  3116 					mapCenter->addBranch ((BranchObj*)selection);
  3117 					unselect();
  3118 					selection=mapCenter->getLastBranch();
  3119 					selection->select();
  3120 					mapCenter->reposition();
  3121 				}
  3122 			}	
  3123 			movingObj=selection;	
  3124 		} else
  3125 			// Middle Button    Toggle Scroll
  3126 			// (On Mac OS X this won't work, but we still have 
  3127 			// a button in the toolbar)
  3128 			if (e->button() == QMouseEvent::MidButton )
  3129 				toggleScroll();
  3130 		updateActions();
  3131 	} else 
  3132 	{ // No MapObj found, we are on the Canvas itself
  3133 		// Left Button	    move Pos of CanvasView
  3134 		if (e->button() == QMouseEvent::LeftButton )
  3135 		{
  3136 			movingObj=NULL;	// move Content not Obj
  3137 			movingObj_start=e->globalPos();
  3138 			movingCont_start=QPoint (contentsX(), contentsY() );
  3139 			movingVec=QPoint(0,0);
  3140 			setCursor(handOpenCursor);
  3141 		} 
  3142     } 
  3143 }
  3144 
  3145 void MapEditor::contentsMouseMoveEvent(QMouseEvent* e)
  3146 {
  3147 	QPoint p = inverseWorldMatrix().map(e->pos());
  3148 
  3149     // Move the selected MapObj
  3150     if ( selection && movingObj) 
  3151     {	
  3152 		// To avoid jumping of the CanvasView, only 
  3153 		// ensureSelectionVisible, if not tmp linked
  3154 		if (!selection->hasParObjTmp())
  3155 			ensureSelectionVisible ();
  3156 		
  3157 		// Now move the selection, but add relative position 
  3158 		// (movingObj_start) where selection was chosen with 
  3159 		// mousepointer. (This avoids flickering resp. jumping 
  3160 		// of selection back to absPos)
  3161 		
  3162 		LinkableMapObj *lmosel;
  3163 		lmosel =  dynamic_cast <LinkableMapObj*> (selection);
  3164 
  3165 		// Check if we could link 
  3166 		LinkableMapObj* lmo=mapCenter->findMapObj(p, lmosel);
  3167 		
  3168 
  3169 		if (typeid(*selection) == typeid(FloatImageObj))
  3170 		{
  3171 			FloatObj *fo=(FloatObj*)selection;
  3172 			saveState("move "+qpointToString(movingObj_orgPos),fo->getSelectString() );
  3173 			fo->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3174 			fo->setRelPos();
  3175 			fo->reposition();
  3176 
  3177 			// Relink float to new mapcenter or branch, if shift is pressed	
  3178 			// Only relink, if selection really has a new parent
  3179 			if ( (e->state() & QMouseEvent::ShiftButton) && lmo &&
  3180 				( (typeid(*lmo)==typeid(BranchObj)) ||
  3181 				  (typeid(*lmo)==typeid(MapCenterObj)) ) &&
  3182 				( lmo != fo->getParObj())  
  3183 				)
  3184 			{
  3185 				if (typeid(*fo) == typeid(FloatImageObj)) 
  3186 				{
  3187 					saveState();
  3188 					FloatImageObj *fio=(FloatImageObj*)(fo);
  3189 					((BranchObj*)(lmo))->addFloatImage (fio);
  3190 					fio->unselect();
  3191 					((BranchObj*)(fio->getParObj()))->removeFloatImage (fio);
  3192 					fio=((BranchObj*)(lmo))->getLastFloatImage();
  3193 					fio->setRelPos();
  3194 					fio->reposition();
  3195 					selection=(LinkableMapObj*)(fio);
  3196 					selection->select();
  3197 					movingObj=(MapObj*)(fio);
  3198 				}	
  3199 			}
  3200 		} else	// selection != a FloatObj
  3201 		{
  3202 			if (lmosel->getDepth()==0)
  3203 			{
  3204 				if (e->state() == (LeftButton | !ShiftButton)) 
  3205 					// If mapCenter is moved, move all the rest by default, too.
  3206 					mapCenter->moveAll(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3207 				else	
  3208 					mapCenter->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3209 			} else
  3210 			{	
  3211 				if (lmosel->getDepth()==1)
  3212 				{
  3213 					// depth==1, mainbranch
  3214 					lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  3215 				} else
  3216 				{
  3217 					// depth>1
  3218 					if (lmosel->getOrientation() == OrientLeftOfCenter)
  3219 						// Add width of bbox here, otherwise alignRelTo will cause jumping around
  3220 						lmosel->move(p.x() -movingObj_start.x()+lmosel->getBBox().width(), 
  3221 							p.y()-movingObj_start.y() +lmosel->getTopPad() );		
  3222 					else	
  3223 						lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() -lmosel->getTopPad());
  3224 				} 
  3225 				// reposition subbranch
  3226 				lmosel->reposition();	
  3227 				//ensureSelectionVisible();
  3228 
  3229 				if (lmo && (lmo!=selection) &&  
  3230 					(typeid(*lmo) == typeid(BranchObj) ||
  3231 					(typeid(*lmo) == typeid(MapCenterObj) )
  3232 					) )
  3233 				{
  3234 					if (e->state() & QMouseEvent::ControlButton)
  3235 					{
  3236 						// Special case: CTRL to link below lmo
  3237 						lmosel->setParObjTmp (lmo,p,+1);
  3238 					}
  3239 					else if (e->state() & QMouseEvent::ShiftButton)
  3240 						lmosel->setParObjTmp (lmo,p,-1);
  3241 					else
  3242 						lmosel->setParObjTmp (lmo,p,0);
  3243 				} else	
  3244 				{
  3245 					lmosel->unsetParObjTmp();
  3246 					/* FIXME not needed anymore?
  3247 					if (lmo &&(lmo==selection))   
  3248 						// Could link to myself (happens sometimes...)
  3249 						lmosel->unsetParObjTmp();
  3250 					if (!lmo)  
  3251 						// no Obj under selection, go back to original Parent
  3252 						lmosel->unsetParObjTmp();
  3253 					*/	
  3254 				}		
  3255 			} // depth>0
  3256 
  3257 		} // no FloatImageObj
  3258 
  3259 		canvas()->update();
  3260 		return;
  3261 	} // selection && moving_obj
  3262 		
  3263 	// Draw a link from one branch to another
  3264 	if (drawingLink)
  3265 	{
  3266 		 tmpXLink->setEnd (p);
  3267 		 tmpXLink->updateXLink();
  3268 	}	 
  3269 	
  3270     // Move CanvasView 
  3271     if (!movingObj && !pickingColor &&!drawingLink) 
  3272 	{
  3273 		QPoint p=e->globalPos();
  3274 		movingVec.setX(-p.x() + movingObj_start.x() );
  3275 		movingVec.setY(-p.y() + movingObj_start.y() );
  3276 		setContentsPos( movingCont_start.x() + movingVec.x(),
  3277 	    movingCont_start.y() + movingVec.y());
  3278 
  3279 		updateViewCenter();
  3280     }
  3281 }
  3282 
  3283 
  3284 void MapEditor::contentsMouseReleaseEvent(QMouseEvent* e)
  3285 {
  3286 	LinkableMapObj *dst;
  3287 	// Have we been picking color?
  3288 	if (pickingColor)
  3289 	{
  3290 		pickingColor=false;
  3291 		setCursor (ArrowCursor);
  3292 		// Check if we are over another branch
  3293 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), NULL);
  3294 		if (dst && selection) 
  3295 		{	
  3296 			if (e->state() & QMouseEvent::ShiftButton)
  3297 			{
  3298 				((BranchObj*)selection)->setColor (((BranchObj*)(dst))->getColor(),false);
  3299 				((BranchObj*)selection)->setLinkColor ();
  3300 			}	
  3301 			else	
  3302 			{
  3303 				((BranchObj*)selection)->setColor (((BranchObj*)(dst))->getColor(),true);
  3304 				((BranchObj*)selection)->setLinkColor ();
  3305 			}	
  3306 		} 
  3307 		return;
  3308 	}
  3309 
  3310 	// Have we been drawing a link?
  3311 	if (drawingLink)
  3312 	{
  3313 		drawingLink=false;
  3314 		// Check if we are over another branch
  3315 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), NULL);
  3316 		if (dst && selection) 
  3317 		{	
  3318 			tmpXLink->setEnd ( ((BranchObj*)(dst)) );
  3319 			tmpXLink->updateXLink();
  3320 			tmpXLink->activate();
  3321 			saveState();	//TODO undoCommand
  3322 		} else
  3323 		{
  3324 			delete(tmpXLink);
  3325 			tmpXLink=NULL;
  3326 		}
  3327 		return;
  3328 	}
  3329 	
  3330     // Have we been moving something?
  3331     if ( selection && movingObj ) 
  3332     {	
  3333 		// Moved FloatObj? Maybe we need to reposition
  3334 		if(typeid(*selection)==typeid (FloatImageObj))
  3335 		{
  3336 			selection->getParObj()->requestReposition();
  3337 			mapCenter->reposition();
  3338 		}	
  3339 
  3340 		// Check if we are over another branch, but ignore 
  3341 		// any found LMOs, which are FloatObjs
  3342 		dst=mapCenter->findMapObj(inverseWorldMatrix().map(e->pos() ), 
  3343 			((LinkableMapObj*)selection) );
  3344 
  3345 		if (dst &&
  3346 		(typeid(*dst)!=typeid(BranchObj)&&typeid(*dst)!=typeid(MapCenterObj))) 
  3347 			dst=NULL;
  3348 		
  3349 		// Now check, if we have been moving a branch 
  3350 		if (typeid(*selection) == typeid(BranchObj)  )
  3351 		{
  3352 			// save the position in case we link to mapcenter
  3353 			QPoint savePos=QPoint (selection->x(),selection->y() );
  3354 
  3355 			// Reset the temporary drawn link to the original one
  3356 			((LinkableMapObj*)selection)->unsetParObjTmp();
  3357 
  3358 
  3359 			copyingObj=false;	
  3360 			if (dst ) 
  3361 			{
  3362 				BranchObj* bs=((BranchObj*)selection);
  3363 				QString undoCom="linkBranchToPos (\""+ 
  3364 					(bs->getParObj())->getSelectString()+
  3365 					"\","+
  3366 					QString("%1").arg(bs->getNum())+
  3367 					","+
  3368 					QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+
  3369 					")";
  3370 				// TODO we also could check, if dest and src are on same branch,
  3371 				// then it would be sufficient to saveState of this branch
  3372 
  3373 				// Modifiers allow to insert above/below dst
  3374 				if (e->state() & QMouseEvent::ShiftButton)
  3375 				{
  3376 					bs->moveBranchTo ( (BranchObj*)(dst->getParObj()), ((BranchObj*)(dst))->getNum());
  3377 				} else 
  3378 				if (e->state() & QMouseEvent::ControlButton)
  3379 			{
  3380 					bs->moveBranchTo ( (BranchObj*)(dst->getParObj()), ((BranchObj*)(dst))->getNum()+1);
  3381 				} else	
  3382 				{
  3383 					bs->moveBranchTo ((BranchObj*)(dst),-1);
  3384 					if (dst->getDepth()==0) 
  3385 						bs->move (savePos);
  3386 				} 
  3387 				saveState (undoCom,bs->getSelectString() );
  3388 			} else
  3389 				if (selection->getDepth()==1)
  3390 					// If we have moved mainbranch only save endposition
  3391 					saveState("move "+qpointToString(movingObj_orgPos), selection->getSelectString() );
  3392 			
  3393 			// Draw the original link, before selection was moved around
  3394 			mapCenter->reposition();
  3395 		}
  3396 		// Finally resize canvas, if needed
  3397 		adjustCanvasSize();
  3398 		canvas()->update();
  3399 		movingObj=NULL;		
  3400 	} else 
  3401 		// maybe we moved View: set old cursor
  3402 		setCursor (ArrowCursor);
  3403     
  3404 }
  3405 
  3406 void MapEditor::contentsMouseDoubleClickEvent(QMouseEvent* e)
  3407 {
  3408 	// Finish open lineEdits
  3409 	if (lineedit) finishedLineEditNoSave();
  3410 	
  3411 	if (e->button() == QMouseEvent::LeftButton )
  3412 	{
  3413 		QPoint p = inverseWorldMatrix().map(e->pos());
  3414 		LinkableMapObj *lmo=mapCenter->findMapObj(p, NULL);
  3415 		if (lmo) {	// MapObj was found
  3416 			// First select the MapObj than edit heading
  3417 			if (selection) selection->unselect();
  3418 			selection=lmo;
  3419 			selection->select();
  3420 			saveState(selection);
  3421 			editHeading();
  3422 		}
  3423 	}
  3424 }
  3425 
  3426 void MapEditor::resizeEvent (QResizeEvent* e)
  3427 {
  3428 	QCanvasView::resizeEvent( e );
  3429 	adjustCanvasSize();
  3430 }
  3431 
  3432 void MapEditor::contentsDragEnterEvent(QDragEnterEvent *event) 
  3433 {
  3434 
  3435 //  for (unsigned int i=0;event->format(i);i++) // Debug mime type
  3436 //    cerr << event->format(i) << endl;
  3437 
  3438   if (selection && 
  3439       (typeid(*selection) == typeid(BranchObj)) || 
  3440       (typeid(*selection) == typeid(MapCenterObj))) {
  3441     
  3442     // If QImageDrag can decode mime type 
  3443     if (QImageDrag::canDecode(event)) {
  3444       event->accept();
  3445       return;
  3446     }
  3447     
  3448     // If image are dragged from firefox 
  3449     if (event->provides("application/x-moz-file-promise-url") && 
  3450 	event->provides("application/x-moz-nativeimage")) {
  3451       event->accept(true);
  3452       return;
  3453     }
  3454 
  3455     // If QUriDrag can decode mime type 
  3456     if (QUriDrag::canDecode(event)) {
  3457       event->accept();
  3458       return;
  3459     }
  3460     
  3461 	// If Uri are dragged from firefox 
  3462     if (event->provides("_NETSCAPE_URL")){
  3463       event->accept();
  3464       return;
  3465     }
  3466 
  3467     // If QTextDrag can decode mime type
  3468     if (QTextDrag::canDecode(event)) {
  3469       event->accept();
  3470       return;
  3471     }
  3472 
  3473   }
  3474   event->ignore();
  3475 }
  3476 
  3477 bool isUnicode16(const QByteArray &d) 
  3478 {
  3479   // TODO: make more precise check for unicode 16.
  3480   // Guess unicode16 if any of second bytes are zero
  3481   unsigned int length = max(0,d.size()-2)/2;
  3482   for (unsigned int i = 0; i<length ; i++)
  3483     if (d.at(i*2+1)==0) return true;
  3484   return false;
  3485 }
  3486       
  3487 void MapEditor::contentsDropEvent(QDropEvent *event) 
  3488 {
  3489 	if (selection && 
  3490       (typeid(*selection) == typeid(BranchObj)) || 
  3491       (typeid(*selection) == typeid(MapCenterObj))) 
  3492 	{
  3493 		bool update=false;
  3494 		QStrList uris;
  3495 		QString heading;
  3496 		if (event->provides("image/png")) 
  3497 		{
  3498 			QPixmap pix;
  3499 			if (QImageDrag::decode(event, pix)) 
  3500 			{
  3501 				addFloatImage(pix);
  3502 				event->accept();
  3503 				update=true;
  3504 			} else
  3505 				event->ignore();
  3506 
  3507 		} else if (event->provides("application/x-moz-file-promise-url") && 
  3508 			 event->provides("application/x-moz-nativeimage")) 
  3509 		{
  3510 			// Contains url to the img src in unicode16
  3511 			QByteArray d = event->encodedData("application/x-moz-file-promise-url");
  3512 			QString url = QString((const QChar*)d.data(),d.size()/2);
  3513 			fetchImage(url);
  3514 			event->accept();
  3515 			update=true;
  3516 		} else if (event->provides ("text/uri-list"))
  3517 		{	// Uris provided e.g. by konqueror
  3518 			QUriDrag::decode (event,uris);
  3519 		} else if (event->provides ("_NETSCAPE_URL"))
  3520 		{	// Uris provided by Mozilla
  3521 		  QStringList l = QStringList::split("\n", event->encodedData("_NETSCAPE_URL"));
  3522 		  uris.append(l[0]);
  3523 		  heading = l[1];
  3524 		} else if (event->provides("text/html")) {
  3525 
  3526 		  // Handels text mime types
  3527 		  // Look like firefox allways handle text as unicode16 (2 bytes per char.)
  3528 		  QByteArray d = event->encodedData("text/html");
  3529 		  QString text;
  3530 		  if (isUnicode16(d)) 
  3531 		    text = QString((const QChar*)d.data(),d.size()/2);
  3532 		  else 
  3533 		    text = QString(d);
  3534 
  3535 		  textEditor->setText(text);
  3536 
  3537 		  event->accept();
  3538 		  update=true;
  3539 		} else if (event->provides("text/plain")) {
  3540 		  QByteArray d = event->encodedData("text/plain");
  3541 		  QString text;
  3542 		  if (isUnicode16(d))
  3543 		    text = QString((const QChar*)d.data(),d.size()/2);
  3544 		  else 
  3545 		    text = QString(d);
  3546 
  3547 		  textEditor->setText(text);
  3548 		  
  3549 		  event->accept();
  3550 		  update= true;
  3551 		}
  3552 
  3553 		if (uris.count()>0)
  3554 		{
  3555 			QStringList files;
  3556 			QStringList urls;
  3557 			QString s;
  3558 			BranchObj *bo;
  3559 			for (const char* u=uris.first(); u; u=uris.next())
  3560 			{
  3561 				bo=((BranchObj*)selection)->addBranch();
  3562 				if (bo)
  3563 				{
  3564 					s=QUriDrag::uriToLocalFile(u);
  3565 					if (s) {
  3566                        QString file = QDir::convertSeparators(s);
  3567                        heading = QFileInfo(file).baseName();
  3568                        files.append(file);
  3569                        if (file.endsWith(".vym", false))
  3570                            bo->setVymLink(file);
  3571                        else
  3572                            bo->setURL(u);
  3573                    } else {
  3574                        urls.append (u);
  3575                        bo->setURL(u);
  3576                    }
  3577 
  3578                    if (heading)
  3579                        bo->setHeading(heading);
  3580                    else
  3581                        bo->setHeading(u);
  3582 				}
  3583 			}
  3584 			update=true;
  3585 		}
  3586 
  3587 		if (update) 
  3588 		{
  3589 			saveState();	//TODO undo Command
  3590 			mapCenter->reposition();
  3591 			adjustCanvasSize();
  3592 			canvas()->update();
  3593 		}	
  3594 	}	
  3595 }
  3596 
  3597 void MapEditor::addFloatImage(const QPixmap &img) 
  3598 {
  3599   if (selection && 
  3600       (typeid(*selection) == typeid(BranchObj)) || 
  3601       (typeid(*selection) == typeid(MapCenterObj))  )
  3602   {
  3603     BranchObj *bo=((BranchObj*)selection);
  3604     saveState(selection);
  3605     //QString fn=fd->selectedFile();
  3606     //lastImageDir=fn.left(fn.findRev ("/"));
  3607     bo->addFloatImage();
  3608     // FIXME check if load was successful
  3609     bo->getLastFloatImage()->load(img);
  3610     //bo->getLastFloatImage()->setOriginalFilename(fn);
  3611     mapCenter->reposition();
  3612     adjustCanvasSize();
  3613     canvas()->update();
  3614   }
  3615 }
  3616 
  3617 
  3618 void MapEditor::imageDataFetched(const QByteArray &a, QNetworkOperation */*nop*/) 
  3619 {
  3620   if (!imageBuffer) imageBuffer = new QBuffer();
  3621   if (!imageBuffer->isOpen()) {
  3622     imageBuffer->open(IO_WriteOnly | IO_Append);
  3623   }
  3624   imageBuffer->at(imageBuffer->at()+imageBuffer->writeBlock(a));
  3625 }
  3626 
  3627 
  3628 void MapEditor::imageDataFinished(QNetworkOperation *nop) 
  3629 {
  3630 	if (nop->state()==QNetworkProtocol::StDone) {
  3631 		QPixmap img(imageBuffer->buffer());
  3632 		addFloatImage(img);
  3633 	}
  3634 
  3635 	if (imageBuffer) {
  3636 		imageBuffer->close();
  3637 		if (imageBuffer) {
  3638 			imageBuffer->close();
  3639 			delete imageBuffer;
  3640 			imageBuffer = 0;
  3641 		}
  3642 	}
  3643 }
  3644 
  3645 void MapEditor::fetchImage(const QString &url) 
  3646 {
  3647   if (urlOperator) {
  3648     urlOperator->stop();
  3649     disconnect(urlOperator);
  3650     delete urlOperator;
  3651   }
  3652   
  3653   urlOperator = new QUrlOperator(url);
  3654   connect(urlOperator, SIGNAL(finished(QNetworkOperation *)), 
  3655 	  this, SLOT(imageDataFinished(QNetworkOperation*)));
  3656 
  3657   connect(urlOperator, SIGNAL(data(const QByteArray &, QNetworkOperation *)),
  3658 	  this, SLOT(imageDataFetched(const QByteArray &, QNetworkOperation *)));
  3659   urlOperator->get();
  3660 }