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