mapeditor.cpp
author insilmaril
Mon, 30 Jul 2007 09:47:07 +0000
changeset 569 df32d920b04e
parent 564 b8f0eefe4351
child 571 bc9083a4a7fb
permissions -rw-r--r--
1.9.4 New base class for XML based file parsing (vym & Freemind)
     1 #include "mapeditor.h"
     2 
     3 #include <q3filedialog.h>
     4 
     5 #include <iostream>
     6 #include <cstdlib>
     7 #include <typeinfo>
     8 
     9 #include "version.h"
    10 
    11 #include "parser.h"
    12 #include "editxlinkdialog.h"
    13 #include "exports.h"
    14 #include "exportxhtmldialog.h"
    15 #include "extrainfodialog.h"
    16 #include "file.h"
    17 #include "linkablemapobj.h"
    18 #include "mainwindow.h"
    19 #include "misc.h"
    20 #include "texteditor.h"
    21 #include "warningdialog.h"
    22 #include "xml.h"
    23 #include "xml-fm.h"
    24 
    25 
    26 extern TextEditor *textEditor;
    27 extern int statusbarTime;
    28 extern Main *mainWindow;
    29 extern QString tmpVymDir;
    30 extern QString clipboardDir;
    31 extern QString clipboardFile;
    32 extern bool clipboardEmpty;
    33 extern bool debug;
    34 extern FlagRowObj *standardFlagsDefault;
    35 
    36 extern QMenu* branchContextMenu;
    37 extern QMenu* branchAddContextMenu;
    38 extern QMenu* branchRemoveContextMenu;
    39 extern QMenu* branchLinksContextMenu;
    40 extern QMenu* branchXLinksContextMenuEdit;
    41 extern QMenu* branchXLinksContextMenuFollow;
    42 extern QMenu* floatimageContextMenu;
    43 extern QMenu* canvasContextMenu;
    44 
    45 
    46 extern Settings settings;
    47 extern ImageIO imageIO;
    48 
    49 extern QString vymName;
    50 extern QString vymVersion;
    51 
    52 extern QString iconPath;
    53 extern QDir vymBaseDir;
    54 extern QDir lastImageDir;
    55 extern QDir lastFileDir;
    56 
    57 int MapEditor::mapNum=0;	// make instance
    58 
    59 ///////////////////////////////////////////////////////////////////////
    60 ///////////////////////////////////////////////////////////////////////
    61 MapEditor::MapEditor( QWidget* parent) :
    62   QGraphicsView(parent)  
    63 {
    64 	//cout << "Constructor ME "<<this<<endl;
    65 	mapNum++;
    66 
    67 
    68 	mapScene= new QGraphicsScene(parent);
    69 	//mapScene= new QGraphicsScene(QRectF(0,0,width(),height()), parent);
    70 	mapScene->setBackgroundBrush (QBrush(Qt::white, Qt::SolidPattern));
    71 
    72 
    73     setScene (mapScene);
    74 	
    75     mapCenter = new MapCenterObj(mapScene);
    76     mapCenter->setVisibility (true);
    77 	mapCenter->setMapEditor (this);
    78 	mapCenter->setHeading (tr("New Map","Heading of mapcenter in new map"));
    79 	//mapCenter->move(mapScene->width()/2-mapCenter->width()/2,mapScene->height()/2-mapCenter->height()/2);
    80 	mapCenter->move(0,0);
    81 
    82     printer=NULL;
    83 
    84 	defLinkColor=QColor (0,0,255);
    85 	defXLinkColor=QColor (180,180,180);
    86 	linkcolorhint=LinkableMapObj::DefaultColor;
    87 	linkstyle=LinkableMapObj::PolyParabel;
    88 
    89 	// Create bitmap cursors, platform dependant
    90 	HandOpenCursor=QCursor (QPixmap(iconPath+"cursorhandopen.png"),1,1);		
    91 	PickColorCursor=QCursor ( QPixmap(iconPath+"cursorcolorpicker.png"), 5,27 ); 
    92 	CopyCursor=QCursor ( QPixmap(iconPath+"cursorcopy.png"), 1,1 ); 
    93 	XLinkCursor=QCursor ( QPixmap(iconPath+"cursorxlink.png"), 1,7 ); 
    94 
    95 	setFocusPolicy (Qt::StrongFocus);
    96 
    97 	pickingColor=false;
    98 	drawingLink=false;
    99 	copyingObj=false;
   100 
   101     editingBO=NULL;
   102     movingObj=NULL;
   103 
   104 	xelection.setMapEditor (this);
   105 	xelection.unselect();
   106 
   107 	defXLinkWidth=1;
   108 	defXLinkColor=QColor (230,230,230);
   109 
   110     mapChanged=false;
   111 	mapDefault=true;
   112 	mapUnsaved=false;
   113 	
   114 	zipped=true;
   115 	filePath="";
   116 	fileName=tr("unnamed");
   117 	mapName="";
   118 
   119 	stepsTotal=settings.readNumEntry("/mapeditor/stepsTotal",100);
   120 	undoSet.setEntry ("/history/stepsTotal",QString::number(stepsTotal));
   121 	mainWindow->updateHistory (undoSet);
   122 	
   123 	// Initialize find routine
   124 	itFind=NULL;				
   125 	EOFind=false;
   126 
   127 	printFrame=true;
   128 	printFooter=true;
   129 
   130 	blockReposition=false;
   131 	blockSaveState=false;
   132 
   133 	hidemode=BranchObj::HideNone;
   134 
   135 	// Create temporary files
   136 	makeTmpDirs();
   137 
   138 	curStep=0;
   139 	redosAvail=0;
   140 	undosAvail=0;
   141 
   142 	setAcceptDrops (true);	
   143 
   144 	mapCenter->reposition();	//	for positioning heading
   145 
   146 	// TODO animations
   147 	animObjList.clear();
   148 	//timerId = startTimer(100);  
   149 
   150 	// autosave
   151 	autosaveTimer=new QTimer (this);
   152 	connect(autosaveTimer, SIGNAL(timeout()), this, SLOT(autosave()));
   153 
   154 	// Network
   155 	netstate=Offline;
   156 }
   157 
   158 MapEditor::~MapEditor()
   159 {
   160 	//cout <<"Destructor MapEditor\n";
   161 	autosaveTimer->stop();
   162 }
   163 
   164 MapCenterObj* MapEditor::getMapCenter()
   165 {
   166     return mapCenter;
   167 }
   168 
   169 QGraphicsScene * MapEditor::getScene()
   170 {
   171     return mapScene;
   172 }
   173 
   174 MapEditor::State MapEditor::getState()
   175 {
   176     return state;
   177 }
   178 
   179 void MapEditor::setStateEditHeading(bool s)
   180 {
   181 	if (s)
   182 	{
   183 		if (state==Idle) state=EditHeading;
   184 	}
   185 	else	
   186 		state=Idle;
   187 }
   188 
   189 bool MapEditor::isRepositionBlocked()
   190 {
   191 	return blockReposition;
   192 }
   193 
   194 void MapEditor::setSaveStateBlocked(bool b)
   195 {
   196 	blockSaveState=b;
   197 }
   198 
   199 bool MapEditor::isSelectBlocked()
   200 {
   201 	if (state==EditHeading)
   202 		return true;
   203 	else
   204 		return false; 
   205 }
   206 
   207 QString MapEditor::getName (const LinkableMapObj *lmo)
   208 {
   209 	QString s;
   210 	if (!lmo) return QString("Error: NULL has no name!");
   211 
   212 	if ((typeid(*lmo) == typeid(BranchObj) ||
   213 				      typeid(*lmo) == typeid(MapCenterObj))) 
   214 	{
   215 		
   216 		s=(((BranchObj*)lmo)->getHeading());
   217 		if (s=="") s="unnamed";
   218 		return QString("branch (%1)").arg(s);
   219 		//return QString("branch (<font color=\"#0000ff\">%1</font>)").arg(s);
   220 	}	
   221 	if ((typeid(*lmo) == typeid(FloatImageObj) ))
   222 		return QString ("floatimage [%1]").arg(((FloatImageObj*)lmo)->getOriginalFilename());
   223 		//return QString ("floatimage [<font color=\"#0000ff\">%1</font>]").arg(((FloatImageObj*)lmo)->getOriginalFilename());
   224 	return QString("Unknown type has no name!");
   225 }
   226 
   227 void MapEditor::makeTmpDirs()
   228 {
   229 	// Create unique temporary directories
   230 	tmpMapDir=QDir::convertSeparators (tmpVymDir+QString("/mapeditor-%1").arg(mapNum));
   231 	histPath=QDir::convertSeparators (tmpMapDir+"/history");
   232 	QDir d;
   233 	d.mkdir (tmpMapDir);
   234 }
   235 
   236 QString MapEditor::saveToDir(const QString &tmpdir, const QString &prefix, bool writeflags, const QPointF &offset, LinkableMapObj *saveSel)
   237 {
   238 	// tmpdir		temporary directory to which data will be written
   239 	// prefix		mapname, which will be appended to images etc.
   240 	// writeflags	Only write flags for "real" save of map, not undo
   241 	// offset		offset of bbox of whole map in scene. 
   242 	//				Needed for XML export
   243 	
   244 	// Save Header
   245 	QString ls;
   246 	switch (linkstyle)
   247 	{
   248 		case LinkableMapObj::Line: 
   249 			ls="StyleLine";
   250 			break;
   251 		case LinkableMapObj::Parabel:
   252 			ls="StyleParabel";
   253 			break;
   254 		case LinkableMapObj::PolyLine:	
   255 			ls="StylePolyLine";
   256 			break;
   257 		default:
   258 			ls="StylePolyParabel";
   259 			break;
   260 	}	
   261 
   262 	QString s="<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE vymmap>\n";
   263 	QString colhint="";
   264 	if (linkcolorhint==LinkableMapObj::HeadingColor) 
   265 		colhint=attribut("linkColorHint","HeadingColor");
   266 
   267 	QString mapAttr=attribut("version",vymVersion);
   268 	if (!saveSel || saveSel==mapCenter)
   269 		mapAttr+= attribut("author",mapCenter->getAuthor()) +
   270 				  attribut("comment",mapCenter->getComment()) +
   271 			      attribut("date",mapCenter->getDate()) +
   272 		          attribut("backgroundColor", mapScene->backgroundBrush().color().name() ) +
   273 		          attribut("selectionColor", xelection.getColor().name() ) +
   274 		          attribut("linkStyle", ls ) +
   275 		          attribut("linkColor", defLinkColor.name() ) +
   276 		          attribut("defXLinkColor", defXLinkColor.name() ) +
   277 		          attribut("defXLinkWidth", QString().setNum(defXLinkWidth,10) ) +
   278 		          colhint; 
   279 	s+=beginElement("vymmap",mapAttr);
   280 	incIndent();
   281 
   282 	// Find the used flags while traversing the tree
   283 	standardFlagsDefault->resetUsedCounter();
   284 	
   285 	// Reset the counters before saving
   286 	// TODO constr. of FIO creates lots of objects, better do this in some other way...
   287 	FloatImageObj (mapScene).resetSaveCounter();
   288 
   289 	// Build xml recursivly
   290 	if (!saveSel || typeid (*saveSel) == typeid (MapCenterObj))
   291 		// Save complete map, if saveSel not set
   292 		s+=mapCenter->saveToDir(tmpdir,prefix,writeflags,offset);
   293 	else
   294 	{
   295 		if ( typeid(*saveSel) == typeid(BranchObj) )
   296 			// Save Subtree
   297 			s+=((BranchObj*)(saveSel))->saveToDir(tmpdir,prefix,offset);
   298 		else if ( typeid(*saveSel) == typeid(FloatImageObj) )
   299 			// Save image
   300 			s+=((FloatImageObj*)(saveSel))->saveToDir(tmpdir,prefix);
   301 	}
   302 
   303 	// Save local settings
   304 	s+=settings.getXMLData (destPath);
   305 
   306 	// Save selection
   307 	if (!xelection.isEmpty() && !saveSel ) 
   308 		s+=valueElement("select",xelection.getSelectString());
   309 
   310 	decIndent();
   311 	s+=endElement("vymmap");
   312 
   313 	if (writeflags)
   314 		standardFlagsDefault->saveToDir (tmpdir+"/flags/","",writeflags);
   315 	return s;
   316 }
   317 
   318 QString MapEditor::getHistoryDir()
   319 {
   320 	QString histName=QDir::convertSeparators (QString("history-%1").arg(curStep));
   321 	return QDir::convertSeparators (tmpMapDir +"/"+histName);
   322 }
   323 
   324 void MapEditor::saveState(const SaveMode &savemode, const QString &undoSelection, const QString &undoCom, const QString &redoSelection, const QString &redoCom, const QString &comment, LinkableMapObj *saveSel)
   325 {
   326 	sendData(redoCom);	//FIXME testing
   327 
   328 	// Main saveState
   329 
   330 
   331 	if (blockSaveState) return;
   332 
   333 	if (debug) cout << "ME::saveState() for  "<<mapName.ascii()<<endl;
   334 	
   335 	// Find out current undo directory
   336 	if (undosAvail<stepsTotal) undosAvail++;
   337 	curStep++;
   338 	if (curStep>stepsTotal) curStep=1;
   339 	
   340 	QString backupXML="";
   341 	QString histDir=getHistoryDir();
   342 	QString bakMapPath=QDir::convertSeparators(histDir+"/map.xml");
   343 
   344 	// Create histDir if not available
   345 	QDir d(histDir);
   346 	if (!d.exists()) 
   347 		makeSubDirs (histDir);
   348 
   349 	// Save depending on how much needs to be saved	
   350 	if (saveSel)
   351 		backupXML=saveToDir (histDir,mapName+"-",false, QPointF (),saveSel);
   352 		
   353 	QString undoCommand="";
   354 	if (savemode==UndoCommand)
   355 	{
   356 		undoCommand=undoCom;
   357 	}	
   358 	else if (savemode==PartOfMap )
   359 	{
   360 		undoCommand=undoCom;
   361 		undoCommand.replace ("PATH",bakMapPath);
   362 	}
   363 
   364 	if (!backupXML.isEmpty())
   365 		// Write XML Data to disk
   366 		saveStringToDisk (QString(bakMapPath),backupXML);
   367 
   368 	// We would have to save all actions in a tree, to keep track of 
   369 	// possible redos after a action. Possible, but we are too lazy: forget about redos.
   370 	redosAvail=0;
   371 
   372 	// Write the current state to disk
   373 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
   374 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
   375 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
   376 	undoSet.setEntry (QString("/history/step-%1/undoCommand").arg(curStep),undoCommand);
   377 	undoSet.setEntry (QString("/history/step-%1/undoSelection").arg(curStep),undoSelection);
   378 	undoSet.setEntry (QString("/history/step-%1/redoCommand").arg(curStep),redoCom);
   379 	undoSet.setEntry (QString("/history/step-%1/redoSelection").arg(curStep),redoSelection);
   380 	undoSet.setEntry (QString("/history/step-%1/comment").arg(curStep),comment);
   381 	undoSet.setEntry (QString("/history/version"),vymVersion);
   382 	undoSet.writeSettings(histPath);
   383 
   384 	if (debug)
   385 	{
   386 		// TODO remove after testing
   387 		//cout << "          into="<< histPath.toStdString()<<endl;
   388 		cout << "    stepsTotal="<<stepsTotal<<
   389 		", undosAvail="<<undosAvail<<
   390 		", redosAvail="<<redosAvail<<
   391 		", curStep="<<curStep<<endl;
   392 		cout << "    ---------------------------"<<endl;
   393 		cout << "    comment="<<comment.toStdString()<<endl;
   394 		cout << "    undoCom="<<undoCommand.toStdString()<<endl;
   395 		cout << "    undoSel="<<undoSelection.toStdString()<<endl;
   396 		cout << "    redoCom="<<redoCom.toStdString()<<endl;
   397 		cout << "    redoSel="<<redoSelection.toStdString()<<endl;
   398 		if (saveSel) cout << "    saveSel="<<saveSel->getSelectString().ascii()<<endl;
   399 		cout << "    ---------------------------"<<endl;
   400 	}
   401 
   402 	mainWindow->updateHistory (undoSet);
   403 	setChanged();
   404 	updateActions();
   405 }
   406 
   407 
   408 void MapEditor::saveStateChangingPart(LinkableMapObj *undoSel, LinkableMapObj* redoSel, const QString &rc, const QString &comment)
   409 {
   410 	// save the selected part of the map, Undo will replace part of map 
   411 	QString undoSelection="";
   412 	if (undoSel)
   413 		undoSelection=undoSel->getSelectString();
   414 	else
   415 		qWarning ("MapEditor::saveStateChangingPart  no undoSel given!");
   416 	QString redoSelection="";
   417 	if (redoSel)
   418 		redoSelection=undoSel->getSelectString();
   419 	else
   420 		qWarning ("MapEditor::saveStateChangingPart  no redoSel given!");
   421 		
   422 
   423 	saveState (PartOfMap,
   424 		undoSelection, "addMapReplace (\"PATH\")",
   425 		redoSelection, rc, 
   426 		comment, 
   427 		undoSel);
   428 }
   429 
   430 void MapEditor::saveStateRemovingPart(LinkableMapObj *redoSel, const QString &comment)
   431 {
   432 	if (!redoSel)
   433 	{
   434 		qWarning ("MapEditor::saveStateRemovingPart  no redoSel given!");
   435 		return;
   436 	}
   437 	QString undoSelection=redoSel->getParObj()->getSelectString();
   438 	QString redoSelection=redoSel->getSelectString();
   439 	if (typeid(*redoSel) == typeid(BranchObj)  ) 
   440 	{
   441 		// save the selected branch of the map, Undo will insert part of map 
   442 		saveState (PartOfMap,
   443 			undoSelection, QString("addMapInsert (\"PATH\",%1)").arg(((BranchObj*)redoSel)->getNum()),
   444 			redoSelection, "delete ()", 
   445 			comment, 
   446 			redoSel);
   447 	}
   448 }
   449 
   450 
   451 void MapEditor::saveState(LinkableMapObj *undoSel, const QString &uc, LinkableMapObj *redoSel, const QString &rc, const QString &comment) 
   452 {
   453 	// "Normal" savestate: save commands, selections and comment
   454 	// so just save commands for undo and redo
   455 	// and use current selection
   456 
   457 	QString redoSelection="";
   458 	if (redoSel) redoSelection=redoSel->getSelectString();
   459 	QString undoSelection="";
   460 	if (undoSel) undoSelection=undoSel->getSelectString();
   461 
   462 	saveState (UndoCommand,
   463 		undoSelection, uc,
   464 		redoSelection, rc, 
   465 		comment, 
   466 		NULL);
   467 }
   468 
   469 void MapEditor::saveState(const QString &undoSel, const QString &uc, const QString &redoSel, const QString &rc, const QString &comment) 
   470 {
   471 	// "Normal" savestate: save commands, selections and comment
   472 	// so just save commands for undo and redo
   473 	// and use current selection
   474 	saveState (UndoCommand,
   475 		undoSel, uc,
   476 		redoSel, rc, 
   477 		comment, 
   478 		NULL);
   479 }
   480 
   481 		
   482 void MapEditor::parseAtom(const QString &atom)
   483 {
   484 	BranchObj *selb=xelection.getBranch();
   485 	QString s,t;
   486 	double x,y;
   487 	int n;
   488 	bool b,ok;
   489 
   490 	// Split string s into command and parameters
   491 	parser.parseAtom (atom);
   492 	QString com=parser.getCommand();
   493 	
   494 	// External commands
   495 	/////////////////////////////////////////////////////////////////////
   496 	if (com=="addBranch")
   497 	{
   498 		if (xelection.isEmpty())
   499 		{
   500 			parser.setError (Aborted,"Nothing selected");
   501 		} else if (! selb )
   502 		{				  
   503 			parser.setError (Aborted,"Type of selection is not a branch");
   504 		} else 
   505 		{	
   506 			QList <int> pl;
   507 			pl << 0 <<1;
   508 			if (parser.checkParCount(pl))
   509 			{
   510 				if (parser.parCount()==0)
   511 					addNewBranch (0);
   512 				else
   513 				{
   514 					n=parser.parInt (ok,0);
   515 					if (ok ) addNewBranch (n);
   516 				}
   517 			}
   518 		}
   519 	/////////////////////////////////////////////////////////////////////
   520 	} else if (com=="addBranchBefore")
   521 	{
   522 		if (xelection.isEmpty())
   523 		{
   524 			parser.setError (Aborted,"Nothing selected");
   525 		} else if (! selb )
   526 		{				  
   527 			parser.setError (Aborted,"Type of selection is not a branch");
   528 		} else 
   529 		{	
   530 			if (parser.parCount()==0)
   531 			{
   532 				addNewBranchBefore ();
   533 			}	
   534 		}
   535 	/////////////////////////////////////////////////////////////////////
   536 	} else if (com==QString("addMapReplace"))
   537 	{
   538 		if (xelection.isEmpty())
   539 		{
   540 			parser.setError (Aborted,"Nothing selected");
   541 		} else if (! selb )
   542 		{				  
   543 			parser.setError (Aborted,"Type of selection is not a branch");
   544 		} else if (parser.checkParCount(1))
   545 		{
   546 			//s=parser.parString (ok,0);	// selection
   547 			t=parser.parString (ok,0);	// path to map
   548 			if (QDir::isRelativePath(t)) t=QDir::convertSeparators (tmpMapDir + "/"+t);
   549 			addMapReplaceInt(selb->getSelectString(),t);	
   550 		}
   551 	/////////////////////////////////////////////////////////////////////
   552 	} else if (com==QString("addMapInsert"))
   553 	{
   554 		if (xelection.isEmpty())
   555 		{
   556 			parser.setError (Aborted,"Nothing selected");
   557 		} else if (! selb )
   558 		{				  
   559 			parser.setError (Aborted,"Type of selection is not a branch");
   560 		} else 
   561 		{	
   562 			if (parser.checkParCount(2))
   563 			{
   564 				t=parser.parString (ok,0);	// path to map
   565 				n=parser.parInt(ok,1);		// position
   566 				if (QDir::isRelativePath(t)) t=QDir::convertSeparators (tmpMapDir + "/"+t);
   567 				addMapInsertInt(t,n);	
   568 			}
   569 		}
   570 	/////////////////////////////////////////////////////////////////////
   571 	} else if (com=="clearFlags")
   572 	{
   573 		if (xelection.isEmpty() )
   574 		{
   575 			parser.setError (Aborted,"Nothing selected");
   576 		} else if (! selb )
   577 		{				  
   578 			parser.setError (Aborted,"Type of selection is not a branch");
   579 		} else if (parser.checkParCount(0))
   580 		{
   581 			selb->clearStandardFlags();	
   582 			selb->updateFlagsToolbar();
   583 		}
   584 	/////////////////////////////////////////////////////////////////////
   585 	} else if (com=="colorBranch")
   586 	{
   587 		if (xelection.isEmpty())
   588 		{
   589 			parser.setError (Aborted,"Nothing selected");
   590 		} else if (! selb )
   591 		{				  
   592 			parser.setError (Aborted,"Type of selection is not a branch");
   593 		} else if (parser.checkParCount(1))
   594 		{	
   595 			QColor c=parser.parColor (ok,0);
   596 			if (ok) colorBranch (c);
   597 		}	
   598 	/////////////////////////////////////////////////////////////////////
   599 	} else if (com=="colorSubtree")
   600 	{
   601 		if (xelection.isEmpty())
   602 		{
   603 			parser.setError (Aborted,"Nothing selected");
   604 		} else if (! selb )
   605 		{				  
   606 			parser.setError (Aborted,"Type of selection is not a branch");
   607 		} else if (parser.checkParCount(1))
   608 		{	
   609 			QColor c=parser.parColor (ok,0);
   610 			if (ok) colorSubtree (c);
   611 		}	
   612 	/////////////////////////////////////////////////////////////////////
   613 	} else if (com=="copy")
   614 	{
   615 		if (xelection.isEmpty())
   616 		{
   617 			parser.setError (Aborted,"Nothing selected");
   618 		} else if (! selb )
   619 		{				  
   620 			parser.setError (Aborted,"Type of selection is not a branch");
   621 		} else if (parser.checkParCount(0))
   622 		{	
   623 			//FIXME missing action for copy
   624 		}	
   625 	/////////////////////////////////////////////////////////////////////
   626 	} else if (com=="cut")
   627 	{
   628 		if (xelection.isEmpty())
   629 		{
   630 			parser.setError (Aborted,"Nothing selected");
   631 		} else if ( xelection.type()!=Selection::Branch  && 
   632 					xelection.type()!=Selection::MapCenter  &&
   633 					xelection.type()!=Selection::FloatImage )
   634 		{				  
   635 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
   636 		} else if (parser.checkParCount(0))
   637 		{	
   638 			cut();
   639 		}	
   640 	/////////////////////////////////////////////////////////////////////
   641 	} else if (com=="delete")
   642 	{
   643 		if (xelection.isEmpty())
   644 		{
   645 			parser.setError (Aborted,"Nothing selected");
   646 		} else if (xelection.type() != Selection::Branch && xelection.type() != Selection::FloatImage )
   647 		{
   648 			parser.setError (Aborted,"Type of selection is wrong.");
   649 		} else if (parser.checkParCount(0))
   650 		{	
   651 			deleteSelection();
   652 		}	
   653 	/////////////////////////////////////////////////////////////////////
   654 	} else if (com=="deleteKeepChilds")
   655 	{
   656 		if (xelection.isEmpty())
   657 		{
   658 			parser.setError (Aborted,"Nothing selected");
   659 		} else if (! selb )
   660 		{
   661 			parser.setError (Aborted,"Type of selection is not a branch");
   662 		} else if (parser.checkParCount(0))
   663 		{	
   664 			deleteKeepChilds();
   665 		}	
   666 	/////////////////////////////////////////////////////////////////////
   667 	} else if (com=="deleteChilds")
   668 	{
   669 		if (xelection.isEmpty())
   670 		{
   671 			parser.setError (Aborted,"Nothing selected");
   672 		} else if (! selb)
   673 		{
   674 			parser.setError (Aborted,"Type of selection is not a branch");
   675 		} else if (parser.checkParCount(0))
   676 		{	
   677 			deleteChilds();
   678 		}	
   679 	/////////////////////////////////////////////////////////////////////
   680 	} else if (com=="exportASCII")
   681 	{
   682 		QString fname="";
   683 		ok=true;
   684 		if (parser.parCount()>=2)
   685 			// Hey, we even have a filename
   686 			fname=parser.parString(ok,1); 
   687 		if (!ok)
   688 		{
   689 			parser.setError (Aborted,"Could not read filename");
   690 		} else
   691 		{
   692 				exportASCII (fname,false);
   693 		}
   694 	/////////////////////////////////////////////////////////////////////
   695 	} else if (com=="exportImage")
   696 	{
   697 		QString fname="";
   698 		ok=true;
   699 		if (parser.parCount()>=2)
   700 			// Hey, we even have a filename
   701 			fname=parser.parString(ok,1); 
   702 		if (!ok)
   703 		{
   704 			parser.setError (Aborted,"Could not read filename");
   705 		} else
   706 		{
   707 			QString format="PNG";
   708 			if (parser.parCount()>2)
   709 			{
   710 				format=parser.parString(ok,2);
   711 			}
   712 			exportImage (fname,false,format);
   713 		}
   714 	/////////////////////////////////////////////////////////////////////
   715 	} else if (com=="exportXHTML")
   716 	{
   717 		QString fname="";
   718 		ok=true;
   719 		if (parser.parCount()>=2)
   720 			// Hey, we even have a filename
   721 			fname=parser.parString(ok,1); 
   722 		if (!ok)
   723 		{
   724 			parser.setError (Aborted,"Could not read filename");
   725 		} else
   726 		{
   727 			exportXHTML (fname,false);
   728 		}
   729 	/////////////////////////////////////////////////////////////////////
   730 	} else if (com=="exportXML")
   731 	{
   732 		QString fname="";
   733 		ok=true;
   734 		if (parser.parCount()>=2)
   735 			// Hey, we even have a filename
   736 			fname=parser.parString(ok,1); 
   737 		if (!ok)
   738 		{
   739 			parser.setError (Aborted,"Could not read filename");
   740 		} else
   741 		{
   742 			exportXML (fname,false);
   743 		}
   744 	/////////////////////////////////////////////////////////////////////
   745 	} else if (com=="importDir")
   746 	{
   747 		if (xelection.isEmpty())
   748 		{
   749 			parser.setError (Aborted,"Nothing selected");
   750 		} else if (! selb )
   751 		{				  
   752 			parser.setError (Aborted,"Type of selection is not a branch");
   753 		} else if (parser.checkParCount(1))
   754 		{
   755 			s=parser.parString(ok,0);
   756 			if (ok) importDirInt(s);
   757 		}	
   758 	/////////////////////////////////////////////////////////////////////
   759 	} else if (com=="linkTo")
   760 	{
   761 		if (xelection.isEmpty())
   762 		{
   763 			parser.setError (Aborted,"Nothing selected");
   764 		} else if ( selb)
   765 		{
   766 			if (parser.checkParCount(4))
   767 			{
   768 				// 0	selectstring of parent
   769 				// 1	num in parent (for branches)
   770 				// 2,3	x,y of mainbranch or mapcenter
   771 				s=parser.parString(ok,0);
   772 				LinkableMapObj *dst=mapCenter->findObjBySelect (s);
   773 				if (dst)
   774 				{	
   775 					if (typeid(*dst) == typeid(BranchObj) ) 
   776 					{
   777 						// Get number in parent
   778 						n=parser.parInt (ok,1);
   779 						if (ok)
   780 						{
   781 							selb->linkTo ((BranchObj*)(dst),n);
   782 							xelection.update();
   783 						}	
   784 					} else if (typeid(*dst) == typeid(MapCenterObj) ) 
   785 					{
   786 						selb->linkTo ((BranchObj*)(dst),-1);
   787 						// Get coordinates of mainbranch
   788 						x=parser.parDouble(ok,2);
   789 						if (ok)
   790 						{
   791 							y=parser.parDouble(ok,3);
   792 							if (ok) 
   793 							{
   794 								selb->move (x,y);
   795 								xelection.update();
   796 							}
   797 						}
   798 					}	
   799 				}	
   800 			}	
   801 		} else if ( xelection.type() == Selection::FloatImage) 
   802 		{
   803 			if (parser.checkParCount(1))
   804 			{
   805 				// 0	selectstring of parent
   806 				s=parser.parString(ok,0);
   807 				LinkableMapObj *dst=mapCenter->findObjBySelect (s);
   808 				if (dst)
   809 				{	
   810 					if (typeid(*dst) == typeid(BranchObj) ||
   811 						typeid(*dst) == typeid(MapCenterObj)) 
   812 						linkTo (dst->getSelectString());
   813 				} else	
   814 					parser.setError (Aborted,"Destination is not a branch");
   815 			}		
   816 		} else
   817 			parser.setError (Aborted,"Type of selection is not a floatimage or branch");
   818 	/////////////////////////////////////////////////////////////////////
   819 	} else if (com=="loadImage")
   820 	{
   821 		if (xelection.isEmpty())
   822 		{
   823 			parser.setError (Aborted,"Nothing selected");
   824 		} else if (! selb )
   825 		{				  
   826 			parser.setError (Aborted,"Type of selection is not a branch");
   827 		} else if (parser.checkParCount(1))
   828 		{
   829 			s=parser.parString(ok,0);
   830 			if (ok) loadFloatImageInt (s);
   831 		}	
   832 	/////////////////////////////////////////////////////////////////////
   833 	} else if (com=="moveBranchUp")
   834 	{
   835 		if (xelection.isEmpty() )
   836 		{
   837 			parser.setError (Aborted,"Nothing selected");
   838 		} else if (! selb )
   839 		{				  
   840 			parser.setError (Aborted,"Type of selection is not a branch");
   841 		} else if (parser.checkParCount(0))
   842 		{
   843 			moveBranchUp();
   844 		}	
   845 	/////////////////////////////////////////////////////////////////////
   846 	} else if (com=="moveBranchDown")
   847 	{
   848 		if (xelection.isEmpty() )
   849 		{
   850 			parser.setError (Aborted,"Nothing selected");
   851 		} else if (! selb )
   852 		{				  
   853 			parser.setError (Aborted,"Type of selection is not a branch");
   854 		} else if (parser.checkParCount(0))
   855 		{
   856 			moveBranchDown();
   857 		}	
   858 	/////////////////////////////////////////////////////////////////////
   859 	} else if (com=="move")
   860 	{
   861 		if (xelection.isEmpty() )
   862 		{
   863 			parser.setError (Aborted,"Nothing selected");
   864 		} else if ( xelection.type()!=Selection::Branch  && 
   865 					xelection.type()!=Selection::MapCenter  &&
   866 					xelection.type()!=Selection::FloatImage )
   867 		{				  
   868 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
   869 		} else if (parser.checkParCount(2))
   870 		{	
   871 			x=parser.parDouble (ok,0);
   872 			if (ok)
   873 			{
   874 				y=parser.parDouble (ok,1);
   875 				if (ok) move (x,y);
   876 			}
   877 		}	
   878 	/////////////////////////////////////////////////////////////////////
   879 	} else if (com=="moveRel")
   880 	{
   881 		if (xelection.isEmpty() )
   882 		{
   883 			parser.setError (Aborted,"Nothing selected");
   884 		} else if ( xelection.type()!=Selection::Selection::Branch  && 
   885 					xelection.type()!=Selection::Selection::MapCenter  &&
   886 					xelection.type()!=Selection::Selection::FloatImage )
   887 		{				  
   888 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
   889 		} else if (parser.checkParCount(2))
   890 		{	
   891 			x=parser.parDouble (ok,0);
   892 			if (ok)
   893 			{
   894 				y=parser.parDouble (ok,1);
   895 				if (ok) moveRel (x,y);
   896 			}
   897 		}	
   898 	/////////////////////////////////////////////////////////////////////
   899 	} else if (com=="nop")
   900 	{
   901 	/////////////////////////////////////////////////////////////////////
   902 	} else if (com=="paste")
   903 	{
   904 		if (xelection.isEmpty() )
   905 		{
   906 			parser.setError (Aborted,"Nothing selected");
   907 		} else if (! selb )
   908 		{				  
   909 			parser.setError (Aborted,"Type of selection is not a branch");
   910 		} else if (parser.checkParCount(1))
   911 		{	
   912 			n=parser.parInt (ok,0);
   913 			if (ok) pasteNoSave(n);
   914 		}	
   915 	/////////////////////////////////////////////////////////////////////
   916 	} else if (com=="qa")
   917 	{
   918 		if (xelection.isEmpty() )
   919 		{
   920 			parser.setError (Aborted,"Nothing selected");
   921 		} else if (! selb )
   922 		{				  
   923 			parser.setError (Aborted,"Type of selection is not a branch");
   924 		} else if (parser.checkParCount(4))
   925 		{	
   926 			QString c,u;
   927 			c=parser.parString (ok,0);
   928 			if (!ok)
   929 			{
   930 				parser.setError (Aborted,"No comment given");
   931 			} else
   932 			{
   933 				s=parser.parString (ok,1);
   934 				if (!ok)
   935 				{
   936 					parser.setError (Aborted,"First parameter is not a string");
   937 				} else
   938 				{
   939 					t=parser.parString (ok,2);
   940 					if (!ok)
   941 					{
   942 						parser.setError (Aborted,"Condition is not a string");
   943 					} else
   944 					{
   945 						u=parser.parString (ok,3);
   946 						if (!ok)
   947 						{
   948 							parser.setError (Aborted,"Third parameter is not a string");
   949 						} else
   950 						{
   951 							if (s!="heading")
   952 							{
   953 								parser.setError (Aborted,"Unknown type: "+s);
   954 							} else
   955 							{
   956 								if (! (t=="eq") ) 
   957 								{
   958 									parser.setError (Aborted,"Unknown operator: "+t);
   959 								} else
   960 								{
   961 									if (! selb    )
   962 									{
   963 										parser.setError (Aborted,"Type of selection is not a branch");
   964 									} else
   965 									{
   966 										if (selb->getHeading() == u)
   967 										{
   968 											cout << "PASSED: " << c.ascii() << endl;
   969 										} else
   970 										{
   971 											cout << "FAILED: " << c.ascii() << endl;
   972 										}
   973 									}
   974 								}
   975 							}
   976 						} 
   977 					} 
   978 				} 
   979 			}
   980 		}	
   981 	/////////////////////////////////////////////////////////////////////
   982 	} else if (com=="saveImage")
   983 	{
   984 		FloatImageObj *fio=xelection.getFloatImage();
   985 		if (!fio)
   986 		{
   987 			parser.setError (Aborted,"Type of selection is not an image");
   988 		} else if (parser.checkParCount(2))
   989 		{
   990 			s=parser.parString(ok,0);
   991 			if (ok)
   992 			{
   993 				t=parser.parString(ok,1);
   994 				if (ok) saveFloatImageInt (fio,t,s);
   995 			}
   996 		}	
   997 	/////////////////////////////////////////////////////////////////////
   998 	} else if (com=="scroll")
   999 	{
  1000 		if (xelection.isEmpty() )
  1001 		{
  1002 			parser.setError (Aborted,"Nothing selected");
  1003 		} else if (! selb )
  1004 		{				  
  1005 			parser.setError (Aborted,"Type of selection is not a branch");
  1006 		} else if (parser.checkParCount(0))
  1007 		{	
  1008 			if (!scrollBranch (selb))	
  1009 				parser.setError (Aborted,"Could not scroll branch");
  1010 		}	
  1011 	/////////////////////////////////////////////////////////////////////
  1012 	} else if (com=="select")
  1013 	{
  1014 		if (parser.checkParCount(1))
  1015 		{
  1016 			s=parser.parString(ok,0);
  1017 			if (ok) select (s);
  1018 		}	
  1019 	/////////////////////////////////////////////////////////////////////
  1020 	} else if (com=="selectLastBranch")
  1021 	{
  1022 		if (xelection.isEmpty() )
  1023 		{
  1024 			parser.setError (Aborted,"Nothing selected");
  1025 		} else if (! selb )
  1026 		{				  
  1027 			parser.setError (Aborted,"Type of selection is not a branch");
  1028 		} else if (parser.checkParCount(0))
  1029 		{	
  1030 			BranchObj *bo=selb->getLastBranch();
  1031 			if (!bo)
  1032 				parser.setError (Aborted,"Could not select last branch");
  1033 			selectInt (bo);	
  1034 				
  1035 		}	
  1036 	/////////////////////////////////////////////////////////////////////
  1037 	} else if (com=="selectLastImage")
  1038 	{
  1039 		if (xelection.isEmpty() )
  1040 		{
  1041 			parser.setError (Aborted,"Nothing selected");
  1042 		} else if (! selb )
  1043 		{				  
  1044 			parser.setError (Aborted,"Type of selection is not a branch");
  1045 		} else if (parser.checkParCount(0))
  1046 		{	
  1047 			FloatImageObj *fio=selb->getLastFloatImage();
  1048 			if (!fio)
  1049 				parser.setError (Aborted,"Could not select last image");
  1050 			selectInt (fio);	
  1051 				
  1052 		}	
  1053 	/////////////////////////////////////////////////////////////////////
  1054 	} else if (com=="selectLatestAdded")
  1055 	{
  1056 		if (latestSelection.isEmpty() )
  1057 		{
  1058 			parser.setError (Aborted,"No latest added object");
  1059 		} else
  1060 		{	
  1061 			if (!select (latestSelection))
  1062 				parser.setError (Aborted,"Could not select latest added object "+latestSelection);
  1063 		}	
  1064 	/////////////////////////////////////////////////////////////////////
  1065 	} else if (com=="setFrameType")
  1066 	{
  1067 		if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
  1068 		{
  1069 			parser.setError (Aborted,"Type of selection does not allow setting frame type");
  1070 		}
  1071 		else if (parser.checkParCount(1))
  1072 		{
  1073 			s=parser.parString(ok,0);
  1074 			if (ok) setFrameType (s);
  1075 		}	
  1076 	/////////////////////////////////////////////////////////////////////
  1077 	} else if (com=="setFramePenColor")
  1078 	{
  1079 		if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
  1080 		{
  1081 			parser.setError (Aborted,"Type of selection does not allow setting of pen color");
  1082 		}
  1083 		else if (parser.checkParCount(1))
  1084 		{
  1085 			QColor c=parser.parColor(ok,0);
  1086 			if (ok) setFramePenColor (c);
  1087 		}	
  1088 	/////////////////////////////////////////////////////////////////////
  1089 	} else if (com=="setFrameBrushColor")
  1090 	{
  1091 		if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
  1092 		{
  1093 			parser.setError (Aborted,"Type of selection does not allow setting brush color");
  1094 		}
  1095 		else if (parser.checkParCount(1))
  1096 		{
  1097 			QColor c=parser.parColor(ok,0);
  1098 			if (ok) setFrameBrushColor (c);
  1099 		}	
  1100 	/////////////////////////////////////////////////////////////////////
  1101 	} else if (com=="setFramePadding")
  1102 	{
  1103 		if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
  1104 		{
  1105 			parser.setError (Aborted,"Type of selection does not allow setting frame padding");
  1106 		}
  1107 		else if (parser.checkParCount(1))
  1108 		{
  1109 			n=parser.parInt(ok,0);
  1110 			if (ok) setFramePadding(n);
  1111 		}	
  1112 	/////////////////////////////////////////////////////////////////////
  1113 	} else if (com=="setFrameBorderWidth")
  1114 	{
  1115 		if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
  1116 		{
  1117 			parser.setError (Aborted,"Type of selection does not allow setting frame border width");
  1118 		}
  1119 		else if (parser.checkParCount(1))
  1120 		{
  1121 			n=parser.parInt(ok,0);
  1122 			if (ok) setFrameBorderWidth (n);
  1123 		}	
  1124 	/////////////////////////////////////////////////////////////////////
  1125 	} else if (com=="setMapAuthor")
  1126 	{
  1127 		if (parser.checkParCount(1))
  1128 		{
  1129 			s=parser.parString(ok,0);
  1130 			if (ok) setMapAuthor (s);
  1131 		}	
  1132 	/////////////////////////////////////////////////////////////////////
  1133 	} else if (com=="setMapComment")
  1134 	{
  1135 		if (parser.checkParCount(1))
  1136 		{
  1137 			s=parser.parString(ok,0);
  1138 			if (ok) setMapComment(s);
  1139 		}	
  1140 	/////////////////////////////////////////////////////////////////////
  1141 	} else if (com=="setMapBackgroundColor")
  1142 	{
  1143 		if (xelection.isEmpty() )
  1144 		{
  1145 			parser.setError (Aborted,"Nothing selected");
  1146 		} else if (! xelection.getBranch() )
  1147 		{				  
  1148 			parser.setError (Aborted,"Type of selection is not a branch");
  1149 		} else if (parser.checkParCount(1))
  1150 		{
  1151 			QColor c=parser.parColor (ok,0);
  1152 			if (ok) setMapBackgroundColor (c);
  1153 		}	
  1154 	/////////////////////////////////////////////////////////////////////
  1155 	} else if (com=="setMapDefLinkColor")
  1156 	{
  1157 		if (xelection.isEmpty() )
  1158 		{
  1159 			parser.setError (Aborted,"Nothing selected");
  1160 		} else if (! selb )
  1161 		{				  
  1162 			parser.setError (Aborted,"Type of selection is not a branch");
  1163 		} else if (parser.checkParCount(1))
  1164 		{
  1165 			QColor c=parser.parColor (ok,0);
  1166 			if (ok) setMapDefLinkColor (c);
  1167 		}	
  1168 	/////////////////////////////////////////////////////////////////////
  1169 	} else if (com=="setMapLinkStyle")
  1170 	{
  1171 		if (parser.checkParCount(1))
  1172 		{
  1173 			s=parser.parString (ok,0);
  1174 			if (ok) setMapLinkStyle(s);
  1175 		}	
  1176 	/////////////////////////////////////////////////////////////////////
  1177 	} else if (com=="setHeading")
  1178 	{
  1179 		if (xelection.isEmpty() )
  1180 		{
  1181 			parser.setError (Aborted,"Nothing selected");
  1182 		} else if (! selb )
  1183 		{				  
  1184 			parser.setError (Aborted,"Type of selection is not a branch");
  1185 		} else if (parser.checkParCount(1))
  1186 		{
  1187 			s=parser.parString (ok,0);
  1188 			if (ok) 
  1189 				setHeading (s);
  1190 		}	
  1191 	/////////////////////////////////////////////////////////////////////
  1192 	} else if (com=="setHideExport")
  1193 	{
  1194 		if (xelection.isEmpty() )
  1195 		{
  1196 			parser.setError (Aborted,"Nothing selected");
  1197 		} else if (xelection.type()!=Selection::Branch && xelection.type() != Selection::MapCenter &&xelection.type()!=Selection::FloatImage)
  1198 		{				  
  1199 			parser.setError (Aborted,"Type of selection is not a branch or floatimage");
  1200 		} else if (parser.checkParCount(1))
  1201 		{
  1202 			b=parser.parBool(ok,0);
  1203 			if (ok) setHideExport (b);
  1204 		}
  1205 	/////////////////////////////////////////////////////////////////////
  1206 	} else if (com=="setIncludeImagesHorizontally")
  1207 	{ 
  1208 		if (xelection.isEmpty() )
  1209 		{
  1210 			parser.setError (Aborted,"Nothing selected");
  1211 		} else if (! selb)
  1212 		{				  
  1213 			parser.setError (Aborted,"Type of selection is not a branch");
  1214 		} else if (parser.checkParCount(1))
  1215 		{
  1216 			b=parser.parBool(ok,0);
  1217 			if (ok) setIncludeImagesHor(b);
  1218 		}
  1219 	/////////////////////////////////////////////////////////////////////
  1220 	} else if (com=="setIncludeImagesVertically")
  1221 	{
  1222 		if (xelection.isEmpty() )
  1223 		{
  1224 			parser.setError (Aborted,"Nothing selected");
  1225 		} else if (! selb)
  1226 		{				  
  1227 			parser.setError (Aborted,"Type of selection is not a branch");
  1228 		} else if (parser.checkParCount(1))
  1229 		{
  1230 			b=parser.parBool(ok,0);
  1231 			if (ok) setIncludeImagesVer(b);
  1232 		}
  1233 	/////////////////////////////////////////////////////////////////////
  1234 	} else if (com=="setHideLinkUnselected")
  1235 	{
  1236 		if (xelection.isEmpty() )
  1237 		{
  1238 			parser.setError (Aborted,"Nothing selected");
  1239 		} else if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
  1240 		{				  
  1241 			parser.setError (Aborted,"Type of selection does not allow hiding the link");
  1242 		} else if (parser.checkParCount(1))
  1243 		{
  1244 			b=parser.parBool(ok,0);
  1245 			if (ok) setHideLinkUnselected(b);
  1246 		}
  1247 	/////////////////////////////////////////////////////////////////////
  1248 	} else if (com=="setSelectionColor")
  1249 	{
  1250 		if (parser.checkParCount(1))
  1251 		{
  1252 			QColor c=parser.parColor (ok,0);
  1253 			if (ok) setSelectionColorInt (c);
  1254 		}	
  1255 	/////////////////////////////////////////////////////////////////////
  1256 	} else if (com=="setURL")
  1257 	{
  1258 		if (xelection.isEmpty() )
  1259 		{
  1260 			parser.setError (Aborted,"Nothing selected");
  1261 		} else if (! selb )
  1262 		{				  
  1263 			parser.setError (Aborted,"Type of selection is not a branch");
  1264 		} else if (parser.checkParCount(1))
  1265 		{
  1266 			s=parser.parString (ok,0);
  1267 			if (ok) setURL(s);
  1268 		}	
  1269 	/////////////////////////////////////////////////////////////////////
  1270 	} else if (com=="setVymLink")
  1271 	{
  1272 		if (xelection.isEmpty() )
  1273 		{
  1274 			parser.setError (Aborted,"Nothing selected");
  1275 		} else if (! selb )
  1276 		{				  
  1277 			parser.setError (Aborted,"Type of selection is not a branch");
  1278 		} else if (parser.checkParCount(1))
  1279 		{
  1280 			s=parser.parString (ok,0);
  1281 			if (ok) setVymLinkInt(s);
  1282 		}	
  1283 	}
  1284 	/////////////////////////////////////////////////////////////////////
  1285 	else if (com=="setFlag")
  1286 	{
  1287 		if (xelection.isEmpty() )
  1288 		{
  1289 			parser.setError (Aborted,"Nothing selected");
  1290 		} else if (! selb )
  1291 		{				  
  1292 			parser.setError (Aborted,"Type of selection is not a branch");
  1293 		} else if (parser.checkParCount(1))
  1294 		{
  1295 			s=parser.parString(ok,0);
  1296 			if (ok) 
  1297 			{
  1298 				selb->activateStandardFlag(s);
  1299 				selb->updateFlagsToolbar();
  1300 			}	
  1301 		}
  1302 	/////////////////////////////////////////////////////////////////////
  1303 	} else if (com=="setFrameType")
  1304 	{
  1305 		if (xelection.isEmpty() )
  1306 		{
  1307 			parser.setError (Aborted,"Nothing selected");
  1308 		} else if (! selb )
  1309 		{				  
  1310 			parser.setError (Aborted,"Type of selection is not a branch");
  1311 		} else if (parser.checkParCount(1))
  1312 		{
  1313 			s=parser.parString(ok,0);
  1314 			if (ok) 
  1315 				setFrameType (s);
  1316 		}
  1317 	/////////////////////////////////////////////////////////////////////
  1318 	} else if (com=="toggleFlag")
  1319 	{
  1320 		if (xelection.isEmpty() )
  1321 		{
  1322 			parser.setError (Aborted,"Nothing selected");
  1323 		} else if (! selb )
  1324 		{				  
  1325 			parser.setError (Aborted,"Type of selection is not a branch");
  1326 		} else if (parser.checkParCount(1))
  1327 		{
  1328 			s=parser.parString(ok,0);
  1329 			if (ok) 
  1330 			{
  1331 				selb->toggleStandardFlag(s);	
  1332 				selb->updateFlagsToolbar();
  1333 			}	
  1334 		}
  1335 	/////////////////////////////////////////////////////////////////////
  1336 	} else if (com=="unscroll")
  1337 	{
  1338 		if (xelection.isEmpty() )
  1339 		{
  1340 			parser.setError (Aborted,"Nothing selected");
  1341 		} else if (! selb )
  1342 		{				  
  1343 			parser.setError (Aborted,"Type of selection is not a branch");
  1344 		} else if (parser.checkParCount(0))
  1345 		{	
  1346 			if (!unscrollBranch (selb))	
  1347 				parser.setError (Aborted,"Could not unscroll branch");
  1348 		}	
  1349 	/////////////////////////////////////////////////////////////////////
  1350 	} else if (com=="unscrollChilds")
  1351 	{
  1352 		if (xelection.isEmpty() )
  1353 		{
  1354 			parser.setError (Aborted,"Nothing selected");
  1355 		} else if (! selb )
  1356 		{				  
  1357 			parser.setError (Aborted,"Type of selection is not a branch");
  1358 		} else if (parser.checkParCount(0))
  1359 		{	
  1360 			unscrollChilds ();
  1361 		}	
  1362 	/////////////////////////////////////////////////////////////////////
  1363 	} else if (com=="unsetFlag")
  1364 	{
  1365 		if (xelection.isEmpty() )
  1366 		{
  1367 			parser.setError (Aborted,"Nothing selected");
  1368 		} else if (! selb )
  1369 		{				  
  1370 			parser.setError (Aborted,"Type of selection is not a branch");
  1371 		} else if (parser.checkParCount(1))
  1372 		{
  1373 			s=parser.parString(ok,0);
  1374 			if (ok) 
  1375 			{
  1376 				selb->deactivateStandardFlag(s);
  1377 				selb->updateFlagsToolbar();
  1378 			}	
  1379 		}
  1380 	} else
  1381 		parser.setError (Aborted,"Unknown command");
  1382 
  1383 	// Any errors?
  1384 	if (parser.errorLevel()==NoError)
  1385 	{
  1386 		setChanged();
  1387 		mapCenter->reposition();
  1388 	}	
  1389 	else	
  1390 	{
  1391 		// TODO Error handling
  1392 		qWarning("MapEditor::parseAtom: Error!");
  1393 		qWarning(parser.errorMessage());
  1394 	} 
  1395 }
  1396 
  1397 void MapEditor::runScript (QString script)
  1398 {
  1399 	parser.setScript (script);
  1400 	parser.runScript();
  1401 	while (parser.next() ) 
  1402 		parseAtom(parser.getAtom());
  1403 }
  1404 
  1405 bool MapEditor::isDefault()
  1406 {
  1407     return mapDefault;
  1408 }
  1409 
  1410 bool MapEditor::hasChanged()
  1411 {
  1412     return mapChanged;
  1413 }
  1414 
  1415 void MapEditor::setChanged()
  1416 {
  1417 	if (!mapChanged)
  1418 		autosaveTimer->start(settings.value("/mapeditor/autosave/ms/",300000).toInt());
  1419 	mapChanged=true;
  1420 	mapDefault=false;
  1421 	mapUnsaved=true;
  1422 	findReset();
  1423 
  1424 }
  1425 
  1426 void MapEditor::closeMap()
  1427 {
  1428 	// Unselect before disabling the toolbar actions
  1429 	if (!xelection.isEmpty() ) xelection.unselect();
  1430 	xelection.clear();
  1431 	updateActions();
  1432 
  1433     clear();
  1434 	close();
  1435 }
  1436 
  1437 void MapEditor::setFilePath(QString fpath, QString destname)
  1438 {
  1439 	if (fpath.isEmpty() || fpath=="")
  1440 	{
  1441 		filePath="";
  1442 		fileName="";
  1443 		destPath="";
  1444 	} else
  1445 	{
  1446 		filePath=fpath;		// becomes absolute path
  1447 		fileName=fpath;		// gets stripped of path
  1448 		destPath=destname;	// needed for vymlinks
  1449 
  1450 		// If fpath is not an absolute path, complete it
  1451 		filePath=QDir(fpath).absPath();
  1452 		fileDir=filePath.left (1+filePath.findRev ("/"));
  1453 
  1454 		// Set short name, too. Search from behind:
  1455 		int i=fileName.findRev("/");
  1456 		if (i>=0) fileName=fileName.remove (0,i+1);
  1457 
  1458 		// Forget the .vym (or .xml) for name of map
  1459 		mapName=fileName.left(fileName.findRev(".",-1,true) );
  1460 	}
  1461 }
  1462 
  1463 void MapEditor::setFilePath(QString fpath)
  1464 {
  1465 	setFilePath (fpath,fpath);
  1466 }
  1467 
  1468 QString MapEditor::getFilePath()
  1469 {
  1470 	return filePath;
  1471 }
  1472 
  1473 QString MapEditor::getFileName()
  1474 {
  1475 	return fileName;
  1476 }
  1477 
  1478 QString MapEditor::getMapName()
  1479 {
  1480 	return mapName;
  1481 }
  1482 
  1483 QString MapEditor::getDestPath()
  1484 {
  1485 	return destPath;
  1486 }
  1487 
  1488 ErrorCode MapEditor::load (QString fname, LoadMode lmode)
  1489 {
  1490 	ErrorCode err=success;
  1491 
  1492 	if (lmode==NewMap)
  1493 	{
  1494 		if (xelection.isEmpty() ) xelection.unselect();
  1495 		xelection.clear();
  1496 		mapCenter->clear();
  1497 		mapCenter->setMapEditor(this);
  1498 		// (map state is set later at end of load...)
  1499 	} else
  1500 	{
  1501 		BranchObj *bo=xelection.getBranch();
  1502 		if (!bo) return aborted;
  1503 		if (lmode==ImportAdd)
  1504 			saveStateChangingPart(
  1505 				bo,
  1506 				bo,
  1507 				QString("addMapInsert (%1)").arg(fname),
  1508 				QString("Add map %1 to %2").arg(fname).arg(getName(bo)));
  1509 		else	
  1510 			saveStateChangingPart(
  1511 				bo,
  1512 				bo,
  1513 				QString("addMapReplace(%1)").arg(fname),
  1514 				QString("Add map %1 to %2").arg(fname).arg(getName(bo)));
  1515 	}	
  1516 	
  1517     
  1518     parseVYMHandler handler;
  1519 	QFile file( fname );
  1520 
  1521 	// I am paranoid: file should exist anyway
  1522 	// according to check in mainwindow.
  1523 	if (!file.exists() )
  1524 	{
  1525 		QMessageBox::critical( 0, tr( "Critical Parse Error" ),
  1526 				   tr("Couldn't open map " +fname)+".");
  1527 		err=aborted;	
  1528 	} else
  1529 	{
  1530 		bool blockSaveStateOrg=blockSaveState;
  1531 		blockReposition=true;
  1532 		blockSaveState=true;
  1533 		QXmlInputSource source( file);
  1534 		QXmlSimpleReader reader;
  1535 		reader.setContentHandler( &handler );
  1536 		reader.setErrorHandler( &handler );
  1537 		handler.setMapEditor( this );
  1538 
  1539 
  1540 		// We need to set the tmpDir in order  to load files with rel. path
  1541 		QString tmpdir= fname.left(fname.findRev("/",-1));	
  1542 		handler.setTmpDir (tmpdir);
  1543 		handler.setInputFile (file.name());
  1544 		handler.setLoadMode (lmode);
  1545 		bool ok = reader.parse( source );
  1546 		blockReposition=false;
  1547 		blockSaveState=blockSaveStateOrg;
  1548 		file.close();
  1549 		if ( ok ) 
  1550 		{
  1551 			mapCenter->reposition();
  1552 			xelection.update();
  1553 			if (lmode==NewMap)
  1554 			{
  1555 				mapDefault=false;
  1556 				mapChanged=false;
  1557 				mapUnsaved=false;
  1558 				autosaveTimer->stop();
  1559 			}
  1560 		} else 
  1561 		{
  1562 			QMessageBox::critical( 0, tr( "Critical Parse Error" ),
  1563 					   tr( handler.errorProtocol() ) );
  1564 			// returnCode=1;	
  1565 			// Still return "success": the map maybe at least
  1566 			// partially read by the parser
  1567 		}	
  1568 	}	
  1569 	updateActions();
  1570 	return err;
  1571 }
  1572 
  1573 int MapEditor::save (const SaveMode &savemode)
  1574 {
  1575 	// Create mapName and fileDir
  1576 	makeSubDirs (fileDir);
  1577 	QString fname;
  1578 	if (saveZipped())
  1579 		// save as .xml
  1580 		fname=mapName+".xml";
  1581 	else
  1582 		// use name given by user, even if he chooses .doc
  1583 		fname=fileName;
  1584 
  1585 
  1586 	QString saveFile;
  1587 	if (savemode==CompleteMap || xelection.isEmpty())
  1588 		saveFile=saveToDir (fileDir,mapName+"-",true,QPointF(),NULL);
  1589 	else	
  1590 	{
  1591 		// TODO take care of multiselections
  1592 		if (xelection.type()==Selection::FloatImage)
  1593 			saveFloatImage();
  1594 		else	
  1595 			saveFile=saveToDir (fileDir,mapName+"-",true,QPointF(),xelection.getBranch());	
  1596 		return 0;	
  1597 	}	
  1598 
  1599 	if (!saveStringToDisk(fileDir+fname,saveFile))
  1600 		return 1;
  1601 
  1602 	mapChanged=false;
  1603 	mapUnsaved=false;
  1604 	autosaveTimer->stop();
  1605 	updateActions();
  1606 	return 0;
  1607 }
  1608 
  1609 void MapEditor::setZipped (bool z)
  1610 {
  1611 	zipped=z;
  1612 }
  1613 
  1614 bool MapEditor::saveZipped ()
  1615 {
  1616 	return zipped;
  1617 }
  1618 
  1619 void MapEditor::print()
  1620 {
  1621 	if ( !printer ) 
  1622 	{
  1623 		printer = new QPrinter;
  1624 		printer->setColorMode (QPrinter::Color);
  1625 		printer->setPrinterName (settings.value("/mainwindow/printerName",printer->printerName()).toString());
  1626 		printer->setOutputFormat((QPrinter::OutputFormat)settings.value("/mainwindow/printerFormat",printer->outputFormat()).toInt());
  1627 		printer->setOutputFileName(settings.value("/mainwindow/printerFileName",printer->outputFileName()).toString());
  1628 	}
  1629 
  1630 	QRectF totalBBox=mapCenter->getTotalBBox();
  1631 
  1632 	// Try to set orientation automagically
  1633 	// Note: Interpretation of generated postscript is amibiguous, if 
  1634 	// there are problems with landscape mode, see
  1635 	// http://sdb.suse.de/de/sdb/html/jsmeix_print-cups-landscape-81.html
  1636 
  1637 	if (totalBBox.width()>totalBBox.height())
  1638 		// recommend landscape
  1639 		printer->setOrientation (QPrinter::Landscape);
  1640 	else	
  1641 		// recommend portrait
  1642 		printer->setOrientation (QPrinter::Portrait);
  1643 
  1644 	if ( printer->setup(this) ) 
  1645 	// returns false, if printing is canceled
  1646 	{
  1647 		QPainter pp(printer);
  1648 
  1649 		pp.setRenderHint(QPainter::Antialiasing,true);
  1650 
  1651 		// Don't print the visualisation of selection
  1652 		xelection.unselect();
  1653 
  1654 		QRectF mapRect=totalBBox;
  1655 		QGraphicsRectItem *frame=NULL;
  1656 
  1657 		if (printFrame) 
  1658 		{
  1659 			// Print frame around map
  1660 			mapRect.setRect (totalBBox.x()-10, totalBBox.y()-10, 
  1661 				totalBBox.width()+20, totalBBox.height()+20);
  1662 			frame=mapScene->addRect (mapRect, QPen(Qt::black),QBrush(Qt::NoBrush));
  1663 			frame->setZValue(0);
  1664 			frame->show();    
  1665 		}		
  1666 
  1667 
  1668 		double paperAspect = (double)printer->width()   / (double)printer->height();
  1669 		double   mapAspect = (double)mapRect.width() / (double)mapRect.height();
  1670 		int viewBottom;
  1671 		if (mapAspect>=paperAspect)
  1672 		{
  1673 			// Fit horizontally to paper width
  1674 			//pp.setViewport(0,0, printer->width(),(int)(printer->width()/mapAspect) );	
  1675 			viewBottom=(int)(printer->width()/mapAspect);	
  1676 		}	else
  1677 		{
  1678 			// Fit vertically to paper height
  1679 			//pp.setViewport(0,0,(int)(printer->height()*mapAspect),printer->height());	
  1680 			viewBottom=printer->height();	
  1681 		}	
  1682 		
  1683 		if (printFooter) 
  1684 		{
  1685 			// Print footer below map
  1686 			QFont font;		
  1687 			font.setPointSize(10);
  1688 			pp.setFont (font);
  1689 			QRectF footerBox(0,viewBottom,printer->width(),15);
  1690 			pp.drawText ( footerBox,Qt::AlignLeft,"VYM - " +fileName);
  1691 			pp.drawText ( footerBox, Qt::AlignRight, QDate::currentDate().toString(Qt::TextDate));
  1692 		}
  1693 		mapScene->render (
  1694 			&pp, 
  1695 			QRectF (0,0,printer->width(),printer->height()-15),
  1696 			QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height())
  1697 		);
  1698 		
  1699 		// Viewport has paper dimension
  1700 		if (frame)  delete (frame);
  1701 
  1702 		// Restore selection
  1703 		xelection.reselect();
  1704 
  1705 		// Save settings in vymrc
  1706 		settings.writeEntry("/mainwindow/printerName",printer->printerName());
  1707 		settings.writeEntry("/mainwindow/printerFormat",printer->outputFormat());
  1708 		settings.writeEntry("/mainwindow/printerFileName",printer->outputFileName());
  1709 	}
  1710 }
  1711 
  1712 void MapEditor::setAntiAlias (bool b)
  1713 {
  1714 	setRenderHint(QPainter::Antialiasing,b);
  1715 }
  1716 
  1717 void MapEditor::setSmoothPixmap(bool b)
  1718 {
  1719 	setRenderHint(QPainter::SmoothPixmapTransform,b);
  1720 }
  1721 
  1722 QPixmap MapEditor::getPixmap()
  1723 {
  1724 	QRectF mapRect=mapCenter->getTotalBBox();
  1725 	QPixmap pix((int)mapRect.width()+2,(int)mapRect.height()+1);
  1726 	QPainter pp (&pix);
  1727 	
  1728 	pp.setRenderHints(renderHints());
  1729 
  1730 	// Don't print the visualisation of selection
  1731 	xelection.unselect();
  1732 
  1733 	mapScene->render (	&pp, 
  1734 		QRectF(0,0,mapRect.width()+2,mapRect.height()+2),
  1735 		QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
  1736 
  1737 	// Restore selection
  1738 	xelection.reselect();
  1739 	
  1740 	return pix;
  1741 }
  1742 
  1743 void MapEditor::setHideTmpMode (BranchObj::HideTmpMode mode)
  1744 {
  1745 	hidemode=mode;
  1746 	mapCenter->setHideTmp (hidemode);
  1747 	mapCenter->reposition();
  1748 	scene()->update();
  1749 }
  1750 
  1751 BranchObj::HideTmpMode MapEditor::getHideTmpMode()
  1752 {
  1753 	return hidemode;
  1754 }
  1755 
  1756 void MapEditor::setExportMode (bool b)
  1757 {
  1758 	// should be called before and after exports
  1759 	// depending on the settings
  1760 	if (b && settings.value("/export/useHideExport","yes")=="yes")
  1761 		setHideTmpMode (BranchObj::HideExport);
  1762 	else	
  1763 		setHideTmpMode (BranchObj::HideNone);
  1764 }
  1765 
  1766 void MapEditor::exportASCII(QString fname,bool askName)
  1767 {
  1768 	ExportASCII ex;
  1769 	ex.setMapCenter(mapCenter);
  1770 	if (fname=="") 
  1771 		ex.setFile (mapName+".txt");	
  1772 	else
  1773 		ex.setFile (fname);
  1774 
  1775 	if (askName)
  1776 	{
  1777 		//ex.addFilter ("TXT (*.txt)");
  1778 		ex.setDir(lastImageDir);
  1779 		//ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
  1780 		ex.execDialog() ; 
  1781 	} 
  1782 	if (!ex.canceled())
  1783 	{
  1784 		setExportMode(true);
  1785 		ex.doExport();
  1786 		setExportMode(false);
  1787 	}
  1788 }
  1789 
  1790 void MapEditor::exportImage(QString fname, bool askName, QString format)
  1791 {
  1792 	if (fname=="")
  1793 	{
  1794 		fname=mapName+".png";
  1795 		format="PNG";
  1796 	} 	
  1797 
  1798 	if (askName)
  1799 	{
  1800 		QStringList fl;
  1801 		QFileDialog *fd=new QFileDialog (this);
  1802 		fd->setCaption (tr("Export map as image"));
  1803 		fd->setDirectory (lastImageDir);
  1804 		fd->setFileMode(QFileDialog::AnyFile);
  1805 		fd->setFilters  (imageIO.getFilters() );
  1806 		if (fd->exec())
  1807 		{
  1808 			fl=fd->selectedFiles();
  1809 			fname=fl.first();
  1810 			format=imageIO.getType(fd->selectedFilter());
  1811 		} 
  1812 	}
  1813 
  1814 	setExportMode (true);
  1815 	QPixmap pix (getPixmap());
  1816 	pix.save(fname, format);
  1817 	setExportMode (false);
  1818 }
  1819 
  1820 void MapEditor::exportOOPresentation(const QString &fn, const QString &cf)
  1821 {
  1822 	ExportOO ex;
  1823 	ex.setFile (fn);
  1824 	ex.setMapCenter(mapCenter);
  1825 	if (ex.setConfigFile(cf)) 
  1826 	{
  1827 		setExportMode (true);
  1828 		ex.exportPresentation();
  1829 		setExportMode (false);
  1830 	}
  1831 }
  1832 
  1833 void MapEditor::exportXHTML (const QString &dir, bool askForName)
  1834 {
  1835 			ExportXHTMLDialog dia(this);
  1836 			dia.setFilePath (filePath );
  1837 			dia.setMapName (mapName );
  1838 			dia.readSettings();
  1839 			if (dir!="") dia.setDir (dir);
  1840 
  1841 			bool ok=true;
  1842 			
  1843 			if (askForName)
  1844 			{
  1845 				if (dia.exec()!=QDialog::Accepted) 
  1846 					ok=false;
  1847 				else	
  1848 				{
  1849 					QDir d (dia.getDir());
  1850 					// Check, if warnings should be used before overwriting
  1851 					// the output directory
  1852 					if (d.exists() && d.count()>0)
  1853 					{
  1854 						WarningDialog warn;
  1855 						warn.showCancelButton (true);
  1856 						warn.setText(QString(
  1857 							"The directory %1 is not empty.\n"
  1858 							"Do you risk to overwrite some of its contents?").arg(d.path() ));
  1859 						warn.setCaption("Warning: Directory not empty");
  1860 						warn.setShowAgainName("mainwindow/overwrite-dir-xhtml");
  1861 
  1862 						if (warn.exec()!=QDialog::Accepted) ok=false;
  1863 					}
  1864 				}	
  1865 			}
  1866 
  1867 			if (ok)
  1868 			{
  1869 				exportXML (dia.getDir(),false );
  1870 				dia.doExport(mapName );
  1871 				//if (dia.hasChanged()) setChanged();
  1872 			}
  1873 }
  1874 
  1875 void MapEditor::exportXML(QString dir, bool askForName)
  1876 {
  1877 	if (askForName)
  1878 	{
  1879 		dir=browseDirectory(this,tr("Export XML to directory"));
  1880 		if (dir =="" && !reallyWriteDirectory(dir) )
  1881 		return;
  1882 	}
  1883 
  1884 	// Hide stuff during export, if settings want this
  1885 	setExportMode (true);
  1886 
  1887 	// Create subdirectories
  1888 	makeSubDirs (dir);
  1889 
  1890 	// write to directory
  1891 	QString saveFile=saveToDir (dir,mapName+"-",true,mapCenter->getTotalBBox().topLeft() ,NULL);
  1892 	QFile file;
  1893 
  1894 	file.setName ( dir + "/"+mapName+".xml");
  1895 	if ( !file.open( QIODevice::WriteOnly ) )
  1896 	{
  1897 		// This should neverever happen
  1898 		QMessageBox::critical (0,tr("Critical Export Error"),tr("MapEditor::exportXML couldn't open %1").arg(file.name()));
  1899 		return;
  1900 	}	
  1901 
  1902 	// Write it finally, and write in UTF8, no matter what 
  1903 	QTextStream ts( &file );
  1904 	ts.setEncoding (QTextStream::UnicodeUTF8);
  1905 	ts << saveFile;
  1906 	file.close();
  1907 
  1908 	// Now write image, too
  1909 	exportImage (dir+"/images/"+mapName+".png",false,"PNG");
  1910 
  1911 	setExportMode (false);
  1912 }
  1913 
  1914 void MapEditor::clear()
  1915 {
  1916 	xelection.unselect();
  1917 	mapCenter->clear();
  1918 }
  1919 
  1920 void MapEditor::copy()
  1921 {
  1922 	LinkableMapObj *sel=xelection.single();
  1923 	if (sel)
  1924 	{
  1925 		if (redosAvail == 0)
  1926 		{
  1927 			// Copy to history
  1928 			QString s=sel->getSelectString();
  1929 			saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",sel  );
  1930 			curClipboard=curStep;
  1931 		}
  1932 
  1933 		// Copy also to global clipboard, because we are at last step in history
  1934 		QString bakMapName=QDir::convertSeparators (QString("history-%1").arg(curStep));
  1935 		QString bakMapDir=QDir::convertSeparators (tmpMapDir +"/"+bakMapName);
  1936 		copyDir (bakMapDir,clipboardDir );
  1937 
  1938 		clipboardEmpty=false;
  1939 		updateActions();
  1940 	}	    
  1941 }
  1942 
  1943 void MapEditor::redo()
  1944 {
  1945 	// Can we undo at all?
  1946 	if (redosAvail<1) return;
  1947 
  1948 	bool blockSaveStateOrg=blockSaveState;
  1949 	blockSaveState=true;
  1950 	
  1951 	redosAvail--;
  1952 
  1953 	if (undosAvail<stepsTotal) undosAvail++;
  1954 	curStep++;
  1955 	if (curStep>stepsTotal) curStep=1;
  1956 	QString undoCommand=  undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
  1957 	QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
  1958 	QString redoCommand=  undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
  1959 	QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
  1960 	QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
  1961 	QString version=undoSet.readEntry ("/history/version");
  1962 
  1963 	if (!checkVersion(version))
  1964 		QMessageBox::warning(0,tr("Warning"),
  1965 			tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
  1966 
  1967 
  1968 	// Find out current undo directory
  1969 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(curStep));
  1970 
  1971 	if (debug)
  1972 	{
  1973 		cout << "ME::redo() begin\n";
  1974 		cout << "    undosAvail="<<undosAvail<<endl;
  1975 		cout << "    redosAvail="<<redosAvail<<endl;
  1976 		cout << "       curStep="<<curStep<<endl;
  1977 		cout << "    ---------------------------"<<endl;
  1978 		cout << "    comment="<<comment.toStdString()<<endl;
  1979 		cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  1980 		cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  1981 		cout << "    redoCom="<<redoCommand.toStdString()<<endl;
  1982 		cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  1983 		cout << "    ---------------------------"<<endl<<endl;
  1984 	}
  1985 
  1986 	// select  object before redo
  1987 	if (!redoSelection.isEmpty())
  1988 		select (redoSelection);
  1989 
  1990 
  1991 	parseAtom (redoCommand);
  1992 	mapCenter->reposition();
  1993 
  1994 	blockSaveState=blockSaveStateOrg;
  1995 
  1996 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  1997 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  1998 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  1999 	undoSet.writeSettings(histPath);
  2000 
  2001 	mainWindow->updateHistory (undoSet);
  2002 	updateActions();
  2003 
  2004 	/* TODO remove testing
  2005 	cout << "ME::redo() end\n";
  2006 	cout << "    undosAvail="<<undosAvail<<endl;
  2007 	cout << "    redosAvail="<<redosAvail<<endl;
  2008 	cout << "       curStep="<<curStep<<endl;
  2009 	cout << "    ---------------------------"<<endl<<endl;
  2010 	*/
  2011 
  2012 
  2013 }
  2014 
  2015 bool MapEditor::isRedoAvailable()
  2016 {
  2017 	if (undoSet.readNumEntry("/history/redosAvail",0)>0)
  2018 		return true;
  2019 	else	
  2020 		return false;
  2021 }
  2022 
  2023 void MapEditor::undo()
  2024 {
  2025 	// Can we undo at all?
  2026 	if (undosAvail<1) return;
  2027 
  2028 	mainWindow->statusMessage (tr("Autosave disabled during undo."));
  2029 
  2030 	bool blockSaveStateOrg=blockSaveState;
  2031 	blockSaveState=true;
  2032 	
  2033 	QString undoCommand=  undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
  2034 	QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
  2035 	QString redoCommand=  undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
  2036 	QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
  2037 	QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
  2038 	QString version=undoSet.readEntry ("/history/version");
  2039 
  2040 	if (!checkVersion(version))
  2041 		QMessageBox::warning(0,tr("Warning"),
  2042 			tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
  2043 
  2044 	// Find out current undo directory
  2045 	QString bakMapDir=QDir::convertSeparators (QString(tmpMapDir+"/undo-%1").arg(curStep));
  2046 
  2047 	// select  object before undo
  2048 	if (!undoSelection.isEmpty())
  2049 		select (undoSelection);
  2050 
  2051 	if (debug)
  2052 	{
  2053 		cout << "ME::undo() begin\n";
  2054 		cout << "    undosAvail="<<undosAvail<<endl;
  2055 		cout << "    redosAvail="<<redosAvail<<endl;
  2056 		cout << "       curStep="<<curStep<<endl;
  2057 		cout << "    ---------------------------"<<endl;
  2058 		cout << "    comment="<<comment.toStdString()<<endl;
  2059 		cout << "    undoCom="<<undoCommand.toStdString()<<endl;
  2060 		cout << "    undoSel="<<undoSelection.toStdString()<<endl;
  2061 		cout << "    redoCom="<<redoCommand.toStdString()<<endl;
  2062 		cout << "    redoSel="<<redoSelection.toStdString()<<endl;
  2063 		cout << "    ---------------------------"<<endl<<endl;
  2064 	}	
  2065 	parseAtom (undoCommand);
  2066 	mapCenter->reposition();
  2067 
  2068 	undosAvail--;
  2069 	curStep--; 
  2070 	if (curStep<1) curStep=stepsTotal;
  2071 
  2072 	redosAvail++;
  2073 
  2074 	blockSaveState=blockSaveStateOrg;
  2075 /* TODO remove testing
  2076 	cout << "ME::undo() end\n";
  2077 	cout << "    undosAvail="<<undosAvail<<endl;
  2078 	cout << "    redosAvail="<<redosAvail<<endl;
  2079 	cout << "       curStep="<<curStep<<endl;
  2080 	cout << "    ---------------------------"<<endl<<endl;
  2081 */
  2082 
  2083 	undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
  2084 	undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
  2085 	undoSet.setEntry ("/history/curStep",QString::number(curStep));
  2086 	undoSet.writeSettings(histPath);
  2087 
  2088 	mainWindow->updateHistory (undoSet);
  2089 	updateActions();
  2090 	xelection.update();
  2091 	ensureSelectionVisible();
  2092 }
  2093 
  2094 bool MapEditor::isUndoAvailable()
  2095 {
  2096 	if (undoSet.readNumEntry("/history/undosAvail",0)>0)
  2097 		return true;
  2098 	else	
  2099 		return false;
  2100 }
  2101 
  2102 void MapEditor::gotoHistoryStep (int i)
  2103 {
  2104 	// Restore variables
  2105 	int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
  2106 	int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
  2107 
  2108 	if (i<0) i=undosAvail+redosAvail;
  2109 
  2110 	// Clicking above current step makes us undo things
  2111 	if (i<undosAvail) 
  2112 	{	
  2113 		for (int j=0; j<undosAvail-i; j++) undo();
  2114 		return;
  2115 	}	
  2116 	// Clicking below current step makes us redo things
  2117 	if (i>undosAvail) 
  2118 		for (int j=undosAvail; j<i; j++) 
  2119 		{
  2120 		cout << "redo "<<j<<"/"<<undosAvail<<" i="<<i<<endl;
  2121 		redo();
  2122 		}
  2123 
  2124 	// And ignore clicking the current row ;-)	
  2125 }
  2126 
  2127 void MapEditor::addMapReplaceInt(const QString &undoSel, const QString &path)
  2128 {
  2129 	QString pathDir=path.left(path.findRev("/"));
  2130 	QDir d(pathDir);
  2131 	QFile file (path);
  2132 
  2133 	if (d.exists() )
  2134 	{
  2135 		// We need to parse saved XML data
  2136 		parseVYMHandler handler;
  2137 		QXmlInputSource source( file);
  2138 		QXmlSimpleReader reader;
  2139 		reader.setContentHandler( &handler );
  2140 		reader.setErrorHandler( &handler );
  2141 		handler.setMapEditor( this );
  2142 		handler.setTmpDir ( pathDir );	// needed to load files with rel. path
  2143 		if (undoSel.isEmpty())
  2144 		{
  2145 			unselect();
  2146 			mapCenter->clear();
  2147 			handler.setLoadMode (NewMap);
  2148 		} else	
  2149 		{
  2150 			select (undoSel);
  2151 			handler.setLoadMode (ImportReplace);
  2152 		}	
  2153 		blockReposition=true;
  2154 		bool ok = reader.parse( source );
  2155 		blockReposition=false;
  2156 		if (! ok ) 
  2157 		{	
  2158 			// This should never ever happen
  2159 			QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
  2160 								    handler.errorProtocol());
  2161 		}
  2162 	} else	
  2163 		QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
  2164 }
  2165 
  2166 void MapEditor::addMapInsertInt (const QString &path, int pos)
  2167 {
  2168 	BranchObj *sel=xelection.getBranch();
  2169 	if (sel);
  2170 	{
  2171 		QString pathDir=path.left(path.findRev("/"));
  2172 		QDir d(pathDir);
  2173 		QFile file (path);
  2174 
  2175 		if (d.exists() )
  2176 		{
  2177 			// We need to parse saved XML data
  2178 			parseVYMHandler handler;
  2179 			QXmlInputSource source( file);
  2180 			QXmlSimpleReader reader;
  2181 			reader.setContentHandler( &handler );
  2182 			reader.setErrorHandler( &handler );
  2183 			handler.setMapEditor( this );
  2184 			handler.setTmpDir ( pathDir );	// needed to load files with rel. path
  2185 			handler.setLoadMode (ImportAdd);
  2186 			blockReposition=true;
  2187 			bool ok = reader.parse( source );
  2188 			blockReposition=false;
  2189 			if (! ok ) 
  2190 			{	
  2191 				// This should never ever happen
  2192 				QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
  2193 										handler.errorProtocol());
  2194 			}
  2195 			if (sel!=mapCenter)
  2196 				sel->getLastBranch()->linkTo (sel,pos);
  2197 		} else	
  2198 			QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
  2199 	}		
  2200 }
  2201 
  2202 void MapEditor::pasteNoSave(const int &n)
  2203 {
  2204 	bool old=blockSaveState;
  2205 	blockSaveState=true;
  2206 	if (redosAvail > 0 || n!=0)
  2207 	{
  2208 		// Use the "historical" buffer
  2209 		QString bakMapName=QDir::convertSeparators (QString("history-%1").arg(n));
  2210 		QString bakMapDir=QDir::convertSeparators (tmpMapDir +"/"+bakMapName);
  2211 		load (bakMapDir+"/"+clipboardFile,ImportAdd);
  2212 	} else
  2213 		// Use the global buffer
  2214 		load (clipboardDir+"/"+clipboardFile,ImportAdd);
  2215 	blockSaveState=old;
  2216 }
  2217 
  2218 void MapEditor::paste()		
  2219 {   
  2220 	BranchObj *sel=xelection.getBranch();
  2221 	if (sel)
  2222 	{
  2223 		saveStateChangingPart(
  2224 			sel,
  2225 			sel,
  2226 			QString ("paste (%1)").arg(curClipboard),
  2227 			QString("Paste to %1").arg( getName(sel))
  2228 		);
  2229 		pasteNoSave(0);
  2230 		mapCenter->reposition();
  2231 	}
  2232 }
  2233 
  2234 void MapEditor::cut()
  2235 {
  2236 	LinkableMapObj *sel=xelection.single();
  2237 	if ( sel && (xelection.type() == Selection::Branch ||
  2238 		xelection.type()==Selection::MapCenter ||
  2239 		xelection.type()==Selection::FloatImage))
  2240 	{
  2241 	/* No savestate! savestate is called in cutNoSave
  2242 		saveStateChangingPart(
  2243 			sel->getParObj(),
  2244 			sel,
  2245 			"cut ()",
  2246 			QString("Cut %1").arg(getName(sel ))
  2247 		);
  2248 	*/	
  2249 		copy();
  2250 		deleteSelection();
  2251 		mapCenter->reposition();
  2252 	}
  2253 }
  2254 
  2255 void MapEditor::move(const double &x, const double &y)
  2256 {
  2257 	LinkableMapObj *sel=xelection.single();
  2258 	if (sel)
  2259 	{
  2260 		QString ps=qpointfToString (sel->getAbsPos());
  2261 		QString s=xelection.single()->getSelectString();
  2262 		saveState(
  2263 			s, "move "+ps, 
  2264 			s, "move "+qpointfToString (QPointF (x,y)), 
  2265 			QString("Move %1 to  %2").arg(getName(sel)).arg(ps));
  2266 		sel->move(x,y);
  2267 		mapCenter->reposition();
  2268 		xelection.update();
  2269 	}
  2270 
  2271 }
  2272 
  2273 void MapEditor::moveRel (const double &x, const double &y)
  2274 {
  2275 	LinkableMapObj *sel=xelection.single();
  2276 	if (sel)
  2277 	{
  2278 		QString ps=qpointfToString (sel->getRelPos());
  2279 		QString s=sel->getSelectString();
  2280 		saveState(
  2281 			s, "moveRel "+ps, 
  2282 			s, "moveRel "+qpointfToString (QPointF (x,y)), 
  2283 			QString("Move %1 to relativ position %2").arg(getName(sel)).arg(ps));
  2284 		((OrnamentedObj*)sel)->move2RelPos (x,y);
  2285 		mapCenter->reposition();
  2286 		sel->updateLink();
  2287 		xelection.update();
  2288 	}
  2289 }
  2290 
  2291 void MapEditor::moveBranchUp()
  2292 {
  2293 	BranchObj* bo=xelection.getBranch();
  2294 	BranchObj* par;
  2295 	if (bo)
  2296 	{
  2297 		if (!bo->canMoveBranchUp()) return;
  2298 		par=(BranchObj*)(bo->getParObj());
  2299 		BranchObj *obo=par->moveBranchUp (bo);	// bo will be the one below selection
  2300 		saveState (bo->getSelectString(),"moveBranchDown ()",obo->getSelectString(),"moveBranchUp ()",QString("Move up %1").arg(getName(bo)));
  2301 		mapCenter->reposition();
  2302 		scene()->update();
  2303 		xelection.update();
  2304 		ensureSelectionVisible();
  2305 	}
  2306 }
  2307 
  2308 void MapEditor::moveBranchDown()
  2309 {
  2310 	BranchObj* bo=xelection.getBranch();
  2311 	BranchObj* par;
  2312 	if (bo)
  2313 	{
  2314 		if (!bo->canMoveBranchDown()) return;
  2315 		par=(BranchObj*)(bo->getParObj());
  2316 		BranchObj *obo=par->moveBranchDown(bo);	// bo will be the one above selection
  2317 		saveState(bo->getSelectString(),"moveBranchUp ()",obo->getSelectString(),"moveBranchDown ()",QString("Move down %1").arg(getName(bo)));
  2318 		mapCenter->reposition();
  2319 		scene()->update();
  2320 		xelection.update();
  2321 		ensureSelectionVisible();
  2322 	}	
  2323 }
  2324 
  2325 void MapEditor::linkTo(const QString &dstString)	
  2326 {
  2327 	FloatImageObj *fio=xelection.getFloatImage();
  2328 	if (fio)
  2329 	{
  2330 		BranchObj *dst=(BranchObj*)(mapCenter->findObjBySelect(dstString));
  2331 		if (dst && (typeid(*dst)==typeid (BranchObj) || 
  2332 					typeid(*dst)==typeid (MapCenterObj)))
  2333 		{			
  2334 			LinkableMapObj *dstPar=dst->getParObj();
  2335 			QString parString=dstPar->getSelectString();
  2336 			QString fioPreSelectString=fio->getSelectString();
  2337 			QString fioPreParentSelectString=fio->getParObj()->getSelectString();
  2338 			((BranchObj*)(dst))->addFloatImage (fio);
  2339 			xelection.unselect();
  2340 			((BranchObj*)(fio->getParObj()))->removeFloatImage (fio);
  2341 			fio=((BranchObj*)(dst))->getLastFloatImage();
  2342 			fio->setRelPos();
  2343 			fio->reposition();
  2344 			xelection.select(fio);
  2345 			saveState(
  2346 				fio->getSelectString(),
  2347 				QString("linkTo (\"%1\")").arg(fioPreParentSelectString), 
  2348 				fioPreSelectString, 
  2349 				QString ("linkTo (\"%1\")").arg(dstString),
  2350 				QString ("Link floatimage to %1").arg(getName(dst)));
  2351 		}
  2352 	}
  2353 }
  2354 
  2355 QString MapEditor::getHeading(bool &ok, QPoint &p)
  2356 {
  2357 	BranchObj *bo=xelection.getBranch();
  2358 	if (bo)
  2359 	{
  2360 		ok=true;
  2361 		p=mapFromScene(bo->getAbsPos());
  2362 		return bo->getHeading();
  2363 	}
  2364 	ok=false;
  2365 	return QString();
  2366 }
  2367 
  2368 void MapEditor::setHeading(const QString &s)
  2369 {
  2370 	BranchObj *sel=xelection.getBranch();
  2371 	if (sel)
  2372 	{
  2373 		saveState(
  2374 			sel,
  2375 			"setHeading (\""+sel->getHeading()+"\")", 
  2376 			sel,
  2377 			"setHeading (\""+s+"\")", 
  2378 			QString("Set heading of %1 to \"%2\"").arg(getName(sel)).arg(s) );
  2379 		sel->setHeading(s );
  2380 		mapCenter->reposition();
  2381 		xelection.update();
  2382 		ensureSelectionVisible();
  2383 	}
  2384 }
  2385 
  2386 void MapEditor::setHeadingInt(const QString &s)
  2387 {
  2388 	BranchObj *bo=xelection.getBranch();
  2389 	if (bo)
  2390 	{
  2391 		bo->setHeading(s);
  2392 		mapCenter->reposition();
  2393 		xelection.update();
  2394 		ensureSelectionVisible();
  2395 	}
  2396 }
  2397 
  2398 void MapEditor::setVymLinkInt (const QString &s)
  2399 {
  2400 	// Internal function, no saveState needed
  2401 	BranchObj *bo=xelection.getBranch();
  2402 	if (bo)
  2403 	{
  2404 		bo->setVymLink(s);
  2405 		mapCenter->reposition();
  2406 		updateActions();
  2407 		xelection.update();
  2408 		ensureSelectionVisible();
  2409 	}
  2410 }
  2411 
  2412 BranchObj* MapEditor::addNewBranchInt(int num)
  2413 {
  2414 	// Depending on pos:
  2415 	// -3		insert in childs of parent  above selection 
  2416 	// -2		add branch to selection 
  2417 	// -1		insert in childs of parent below selection 
  2418 	// 0..n		insert in childs of parent at pos
  2419 	BranchObj *newbo=NULL;
  2420 	BranchObj *bo=xelection.getBranch();
  2421 	if (bo)
  2422 	{
  2423 		if (num==-2)
  2424 		{
  2425 			// save scroll state. If scrolled, automatically select
  2426 			// new branch in order to tmp unscroll parent...
  2427 			newbo=bo->addBranch();
  2428 			
  2429 		}else if (num==-1)
  2430 		{
  2431 			num=bo->getNum()+1;
  2432 			bo=(BranchObj*)bo->getParObj();
  2433 			if (bo) newbo=bo->insertBranch(num);
  2434 		}else if (num==-3)
  2435 		{
  2436 			num=bo->getNum();
  2437 			bo=(BranchObj*)bo->getParObj();
  2438 			if (bo) newbo=bo->insertBranch(num);
  2439 		}
  2440 		if (!newbo) return NULL;
  2441 	}	
  2442 	return newbo;
  2443 }	
  2444 
  2445 BranchObj* MapEditor::addNewBranch(int pos)
  2446 {
  2447 	// Different meaning than num in addNewBranchInt!
  2448 	// -1	add above
  2449 	//  0	add as child
  2450 	// +1	add below
  2451 	BranchObj *bo = xelection.getBranch();
  2452 	BranchObj *newbo=NULL;
  2453 
  2454 	if (bo)
  2455 	{
  2456 		setCursor (Qt::ArrowCursor);
  2457 
  2458 		newbo=addNewBranchInt (pos-2);
  2459 
  2460 		if (newbo)
  2461 		{
  2462 			saveState(
  2463 				newbo,		
  2464 				"delete ()",
  2465 				bo,
  2466 				QString ("addBranch (%1)").arg(pos),
  2467 				QString ("Add new branch to %1").arg(getName(bo)));	
  2468 
  2469 			mapCenter->reposition();
  2470 			xelection.update();
  2471 			latestSelection=newbo->getSelectString();
  2472 			// In Network mode, the client needs to know where the new branch is,
  2473 			// so we have to pass on this information via saveState.
  2474 			// TODO: Get rid of this positioning workaround
  2475 			QString ps=qpointfToString (newbo->getAbsPos());
  2476 			sendData ("selectLatestAdded ()");
  2477 			sendData (QString("move %1").arg(ps));
  2478 			sendSelection();
  2479 		}
  2480 	}	
  2481 	return newbo;
  2482 }
  2483 
  2484 
  2485 BranchObj* MapEditor::addNewBranchBefore()
  2486 {
  2487 	BranchObj *newbo=NULL;
  2488 	BranchObj *bo = xelection.getBranch();
  2489 	if (bo && xelection.type()==Selection::Branch)
  2490 		 // We accept no MapCenterObj here, so we _have_ a parent
  2491 	{
  2492 		QPointF p=bo->getRelPos();
  2493 
  2494 
  2495 		BranchObj *parbo=(BranchObj*)(bo->getParObj());
  2496 
  2497 		// add below selection
  2498 		newbo=parbo->insertBranch(bo->getNum()+1);
  2499 		if (newbo)
  2500 		{
  2501 			newbo->move2RelPos (p);
  2502 
  2503 			// Move selection to new branch
  2504 			bo->linkTo (newbo,-1);
  2505 
  2506 			saveState (newbo, "deleteKeepChilds ()", newbo, "addBranchBefore ()", 
  2507 				QString ("Add branch before %1").arg(getName(bo)));
  2508 
  2509 			mapCenter->reposition();
  2510 			xelection.update();
  2511 		}
  2512 	}	
  2513 	latestSelection=xelection.getSelectString();
  2514 	return newbo;
  2515 }
  2516 
  2517 void MapEditor::deleteSelection()
  2518 {
  2519 	BranchObj *bo = xelection.getBranch();
  2520 	if (bo && xelection.type()==Selection::Branch)
  2521 	{
  2522 		BranchObj* par=(BranchObj*)(bo->getParObj());
  2523 		xelection.unselect();
  2524 		saveStateRemovingPart (bo, QString ("Delete %1").arg(getName(bo)));
  2525 		par->removeBranch(bo);
  2526 		xelection.select (par);
  2527 		ensureSelectionVisible();
  2528 		mapCenter->reposition();
  2529 		xelection.update();
  2530 		xelection.update();
  2531 		return;
  2532 	}
  2533 	FloatImageObj *fio=xelection.getFloatImage();
  2534 	if (fio)
  2535 	{
  2536 		BranchObj* par=(BranchObj*)(fio->getParObj());
  2537 		saveStateChangingPart(
  2538 			par, 
  2539 			fio,
  2540 			"delete ()",
  2541 			QString("Delete %1").arg(getName(fio))
  2542 		);
  2543 		xelection.unselect();
  2544 		par->removeFloatImage(fio);
  2545 		xelection.select (par);
  2546 		mapCenter->reposition();
  2547 		xelection.update();
  2548 		ensureSelectionVisible();
  2549 		return;
  2550 	}
  2551 }
  2552 
  2553 LinkableMapObj* MapEditor::getSelection()
  2554 {
  2555 	return xelection.single();
  2556 }
  2557 
  2558 BranchObj* MapEditor::getSelectedBranch()
  2559 {
  2560 	return xelection.getBranch();
  2561 }
  2562 
  2563 FloatImageObj* MapEditor::getSelectedFloatImage()
  2564 {
  2565 	return xelection.getFloatImage();
  2566 }
  2567 
  2568 void MapEditor::unselect()
  2569 {
  2570 	xelection.unselect();
  2571 }	
  2572 
  2573 void MapEditor::reselect()
  2574 {
  2575 	xelection.reselect();
  2576 }	
  2577 
  2578 bool MapEditor::select (const QString &s)
  2579 {
  2580 	LinkableMapObj *lmo=mapCenter->findObjBySelect(s);
  2581 
  2582 	// Finally select the found object
  2583 	if (lmo)
  2584 	{
  2585 		xelection.unselect();
  2586 		xelection.select(lmo);
  2587 		xelection.update();
  2588 		ensureSelectionVisible();
  2589 		sendSelection ();
  2590 		return true;
  2591 	} 
  2592 	return false;
  2593 }
  2594 
  2595 QString MapEditor::getSelectString()
  2596 {
  2597 	return xelection.getSelectString();
  2598 }
  2599 
  2600 void MapEditor::selectInt (LinkableMapObj *lmo)
  2601 {
  2602 	if (lmo && xelection.single()!= lmo && isSelectBlocked()==false )
  2603 	{
  2604 		xelection.select(lmo);
  2605 		xelection.update();
  2606 		sendSelection ();
  2607 	}	
  2608 }
  2609 
  2610 void MapEditor::selectNextBranchInt()
  2611 {
  2612 	// Increase number of branch
  2613 	LinkableMapObj *sel=xelection.single();
  2614 	if (sel)
  2615 	{
  2616 		QString s=sel->getSelectString();
  2617 		QString part;
  2618 		QString typ;
  2619 		QString num;
  2620 
  2621 		// Where am I? 
  2622 		part=s.section(",",-1);
  2623 		typ=part.left (3);
  2624 		num=part.right(part.length() - 3);
  2625 
  2626 		s=s.left (s.length() -num.length());
  2627 
  2628 		// Go to next lmo
  2629 		num=QString ("%1").arg(num.toUInt()+1);
  2630 
  2631 		s=s+num;
  2632 		
  2633 		// Try to select this one
  2634 		if (select (s)) return;
  2635 
  2636 		// We have no direct successor, 
  2637 		// try to increase the parental number in order to
  2638 		// find a successor with same depth
  2639 
  2640 		int d=xelection.single()->getDepth();
  2641 		int oldDepth=d;
  2642 		int i;
  2643 		bool found=false;
  2644 		bool b;
  2645 		while (!found && d>0)
  2646 		{
  2647 			s=s.section (",",0,d-1);
  2648 			// replace substring of current depth in s with "1"
  2649 			part=s.section(",",-1);
  2650 			typ=part.left (3);
  2651 			num=part.right(part.length() - 3);
  2652 
  2653 			if (d>1)
  2654 			{	
  2655 				// increase number of parent
  2656 				num=QString ("%1").arg(num.toUInt()+1);
  2657 				s=s.section (",",0,d-2) + ","+ typ+num;
  2658 			} else
  2659 			{
  2660 				// Special case, look at orientation
  2661 				if (xelection.single()->getOrientation()==LinkableMapObj::RightOfCenter)
  2662 					num=QString ("%1").arg(num.toUInt()+1);
  2663 				else	
  2664 					num=QString ("%1").arg(num.toUInt()-1);
  2665 				s=typ+num;
  2666 			}	
  2667 
  2668 			if (select (s))
  2669 				// pad to oldDepth, select the first branch for each depth
  2670 				for (i=d;i<oldDepth;i++)
  2671 				{
  2672 					b=select (s);
  2673 					if (b)
  2674 					{	
  2675 						if ( xelection.getBranch()->countBranches()>0)
  2676 							s+=",bo:0";
  2677 						else	
  2678 							break;
  2679 					} else
  2680 						break;
  2681 				}	
  2682 
  2683 			// try to select the freshly built string
  2684 			found=select(s);
  2685 			d--;
  2686 		}
  2687 		return;
  2688 	}	
  2689 }
  2690 
  2691 void MapEditor::selectPrevBranchInt()
  2692 {
  2693 	// Decrease number of branch
  2694 	BranchObj *bo=xelection.getBranch();
  2695 	if (bo)
  2696 	{
  2697 		QString s=bo->getSelectString();
  2698 		QString part;
  2699 		QString typ;
  2700 		QString num;
  2701 
  2702 		// Where am I? 
  2703 		part=s.section(",",-1);
  2704 		typ=part.left (3);
  2705 		num=part.right(part.length() - 3);
  2706 
  2707 		s=s.left (s.length() -num.length());
  2708 
  2709 		int n=num.toInt()-1;
  2710 		
  2711 		// Go to next lmo
  2712 		num=QString ("%1").arg(n);
  2713 		s=s+num;
  2714 		
  2715 		// Try to select this one
  2716 		if (n>=0 && select (s)) return;
  2717 
  2718 		// We have no direct precessor, 
  2719 		// try to decrease the parental number in order to
  2720 		// find a precessor with same depth
  2721 
  2722 		int d=xelection.single()->getDepth();
  2723 		int oldDepth=d;
  2724 		int i;
  2725 		bool found=false;
  2726 		bool b;
  2727 		while (!found && d>0)
  2728 		{
  2729 			s=s.section (",",0,d-1);
  2730 			// replace substring of current depth in s with "1"
  2731 			part=s.section(",",-1);
  2732 			typ=part.left (3);
  2733 			num=part.right(part.length() - 3);
  2734 
  2735 			if (d>1)
  2736 			{
  2737 				// decrease number of parent
  2738 				num=QString ("%1").arg(num.toInt()-1);
  2739 				s=s.section (",",0,d-2) + ","+ typ+num;
  2740 			} else
  2741 			{
  2742 				// Special case, look at orientation
  2743 				if (xelection.single()->getOrientation()==LinkableMapObj::RightOfCenter)
  2744 					num=QString ("%1").arg(num.toInt()-1);
  2745 				else	
  2746 					num=QString ("%1").arg(num.toInt()+1);
  2747 				s=typ+num;
  2748 			}	
  2749 
  2750 			if (select(s))
  2751 				// pad to oldDepth, select the last branch for each depth
  2752 				for (i=d;i<oldDepth;i++)
  2753 				{
  2754 					b=select (s);
  2755 					if (b)
  2756 						if ( xelection.getBranch()->countBranches()>0)
  2757 							s+=",bo:"+ QString ("%1").arg( xelection.getBranch()->countBranches()-1 );
  2758 						else	
  2759 							break;
  2760 					else
  2761 						break;
  2762 				}	
  2763 			
  2764 			// try to select the freshly built string
  2765 			found=select(s);
  2766 			d--;
  2767 		}
  2768 		return;
  2769 	}	
  2770 }
  2771 
  2772 void MapEditor::selectUpperBranch()
  2773 {
  2774 	if (isSelectBlocked() ) return;
  2775 
  2776 	BranchObj *bo=xelection.getBranch();
  2777 	if (bo && xelection.type()==Selection::Branch)
  2778 	{
  2779 		if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  2780 			selectPrevBranchInt();
  2781 		else
  2782 			if (bo->getDepth()==1)
  2783 				selectNextBranchInt();
  2784 			else
  2785 				selectPrevBranchInt();
  2786 	}
  2787 }
  2788 
  2789 void MapEditor::selectLowerBranch()
  2790 {
  2791 	if (isSelectBlocked() ) return;
  2792 
  2793 	BranchObj *bo=xelection.getBranch();
  2794 	if (bo && xelection.type()==Selection::Branch)
  2795 		if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  2796 			selectNextBranchInt();
  2797 		else
  2798 			if (bo->getDepth()==1)
  2799 				selectPrevBranchInt();
  2800 			else
  2801 				selectNextBranchInt();
  2802 }
  2803 
  2804 
  2805 void MapEditor::selectLeftBranch()
  2806 {
  2807 	if (isSelectBlocked() ) return;
  2808 
  2809 	BranchObj* bo;
  2810 	BranchObj* par;
  2811 	LinkableMapObj *sel=xelection.single();
  2812 	if (sel)
  2813 	{
  2814 		if (xelection.type()== Selection::MapCenter)
  2815 		{
  2816 			par=xelection.getBranch();
  2817 			bo=par->getLastSelectedBranch();
  2818 			if (bo)
  2819 			{
  2820 				// Workaround for reselecting on left and right side
  2821 				if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
  2822 					bo=par->getLastBranch();
  2823 				if (bo)
  2824 				{
  2825 					bo=par->getLastBranch();
  2826 					xelection.select(bo);
  2827 					xelection.update();
  2828 					ensureSelectionVisible();
  2829 					sendSelection();
  2830 				}
  2831 			}	
  2832 		} else
  2833 		{
  2834 			par=(BranchObj*)(sel->getParObj());
  2835 			if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
  2836 			{
  2837 				if (xelection.type() == Selection::Branch ||
  2838 					xelection.type() == Selection::FloatImage)
  2839 				{
  2840 					xelection.select(par);
  2841 					xelection.update();
  2842 					ensureSelectionVisible();
  2843 					sendSelection();
  2844 				}
  2845 			} else
  2846 			{
  2847 				if (xelection.type() == Selection::Branch )
  2848 				{
  2849 					bo=xelection.getBranch()->getLastSelectedBranch();
  2850 					if (bo) 
  2851 					{
  2852 						xelection.select(bo);
  2853 						xelection.update();
  2854 						ensureSelectionVisible();
  2855 					sendSelection();
  2856 					}
  2857 				}
  2858 			}
  2859 		}	
  2860 	}
  2861 }
  2862 
  2863 void MapEditor::selectRightBranch()
  2864 {
  2865 	if (isSelectBlocked() ) return;
  2866 
  2867 	BranchObj* bo;
  2868 	BranchObj* par;
  2869 	LinkableMapObj *sel=xelection.single();
  2870 	if (sel)
  2871 	{
  2872 		if (xelection.type()==Selection::MapCenter) 
  2873 		{
  2874 			par=xelection.getBranch();
  2875 			bo=par->getLastSelectedBranch();
  2876 			if (bo)
  2877 			{
  2878 				// Workaround for reselecting on left and right side
  2879 				if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
  2880 					bo=par->getFirstBranch();
  2881 				if (bo)
  2882 				{
  2883 					xelection.select(bo);
  2884 					xelection.update();
  2885 					ensureSelectionVisible();
  2886 					sendSelection();
  2887 				}
  2888 			}
  2889 		} else
  2890 		{
  2891 			par=(BranchObj*)(xelection.single()->getParObj());
  2892 			if (xelection.single()->getOrientation()==LinkableMapObj::LeftOfCenter)
  2893 			{
  2894 				if (xelection.type() == Selection::Branch ||
  2895 					xelection.type() == Selection::FloatImage)
  2896 				{
  2897 					xelection.select(par);
  2898 					xelection.update();
  2899 					ensureSelectionVisible();
  2900 					sendSelection();
  2901 				}
  2902 			} else
  2903 			{
  2904 				if (xelection.type()  == Selection::Branch) 
  2905 				{
  2906 					bo=xelection.getBranch()->getLastSelectedBranch();
  2907 					if (bo) 
  2908 					{
  2909 						xelection.select(bo);
  2910 						xelection.update();
  2911 						ensureSelectionVisible();
  2912 					sendSelection();
  2913 					}
  2914 				}
  2915 			}
  2916 		}
  2917 	}
  2918 }
  2919 
  2920 void MapEditor::selectFirstBranch()
  2921 {
  2922 	BranchObj *bo1=xelection.getBranch();
  2923 	BranchObj *bo2;
  2924 	BranchObj* par;
  2925 	if (bo1)
  2926 	{
  2927 		par=(BranchObj*)(bo1->getParObj());
  2928 		bo2=par->getFirstBranch();
  2929 		if (bo2) {
  2930 			xelection.select(bo2);
  2931 			xelection.update();
  2932 			ensureSelectionVisible();
  2933 			sendSelection();
  2934 		}
  2935 	}		
  2936 }
  2937 
  2938 void MapEditor::selectLastBranch()
  2939 {
  2940 	BranchObj *bo1=xelection.getBranch();
  2941 	BranchObj *bo2;
  2942 	BranchObj* par;
  2943 	if (bo1)
  2944 	{
  2945 		par=(BranchObj*)(bo1->getParObj());
  2946 		bo2=par->getLastBranch();
  2947 		if (bo2) 
  2948 		{
  2949 			xelection.select(bo2);
  2950 			xelection.update();
  2951 			ensureSelectionVisible();
  2952 			sendSelection();
  2953 		}
  2954 	}		
  2955 }
  2956 
  2957 void MapEditor::selectMapBackgroundImage ()
  2958 {
  2959 	Q3FileDialog *fd=new Q3FileDialog( this);
  2960 	fd->setMode (Q3FileDialog::ExistingFile);
  2961 	fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  2962 	ImagePreview *p =new ImagePreview (fd);
  2963 	fd->setContentsPreviewEnabled( TRUE );
  2964 	fd->setContentsPreview( p, p );
  2965 	fd->setPreviewMode( Q3FileDialog::Contents );
  2966 	fd->setCaption(vymName+" - " +tr("Load background image"));
  2967 	fd->setDir (lastImageDir);
  2968 	fd->show();
  2969 
  2970 	if ( fd->exec() == QDialog::Accepted )
  2971 	{
  2972 		// TODO selectMapBackgroundImg in QT4 use:	lastImageDir=fd->directory();
  2973 		lastImageDir=QDir (fd->dirPath());
  2974 		setMapBackgroundImage (fd->selectedFile());
  2975 	}
  2976 }	
  2977 
  2978 void MapEditor::setMapBackgroundImage (const QString &fn)	//FIXME missing savestate
  2979 {
  2980 	QColor oldcol=mapScene->backgroundBrush().color();
  2981 	/*
  2982 	saveState(
  2983 		selection,
  2984 		QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
  2985 		selection,
  2986 		QString ("setMapBackgroundImage (%1)").arg(col.name()),
  2987 		QString("Set background color of map to %1").arg(col.name()));
  2988 	*/	
  2989 	QBrush brush;
  2990 	brush.setTextureImage (QPixmap (fn));
  2991 	mapScene->setBackgroundBrush(brush);
  2992 }
  2993 
  2994 void MapEditor::selectMapBackgroundColor()
  2995 {
  2996 	QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), this );
  2997 	if ( !col.isValid() ) return;
  2998 	setMapBackgroundColor( col );
  2999 }
  3000 
  3001 
  3002 void MapEditor::setMapBackgroundColor(QColor col)
  3003 {
  3004 	QColor oldcol=mapScene->backgroundBrush().color();
  3005 	saveState(
  3006 		mapCenter,
  3007 		QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
  3008 		mapCenter,
  3009 		QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
  3010 		QString("Set background color of map to %1").arg(col.name()));
  3011 	mapScene->setBackgroundBrush(col);
  3012 }
  3013 
  3014 QColor MapEditor::getMapBackgroundColor()
  3015 {
  3016     return mapScene->backgroundBrush().color();
  3017 }
  3018 
  3019 QColor MapEditor::getCurrentHeadingColor()
  3020 {
  3021 	BranchObj *bo=xelection.getBranch();
  3022 	if (bo) return bo->getColor(); 
  3023 	
  3024 	QMessageBox::warning(0,tr("Warning"),tr("Can't get color of heading,\nthere's no branch selected"));
  3025 	return Qt::black;
  3026 }
  3027 
  3028 void MapEditor::colorBranch (QColor c)
  3029 {
  3030 	BranchObj *bo=xelection.getBranch();
  3031 	if (bo)
  3032 	{
  3033 		saveState(
  3034 			bo, 
  3035 			QString ("colorBranch (\"%1\")").arg(bo->getColor().name()),
  3036 			bo,
  3037 			QString ("colorBranch (\"%1\")").arg(c.name()),
  3038 			QString("Set color of %1 to %2").arg(getName(bo)).arg(c.name())
  3039 		);	
  3040 		bo->setColor(c); // color branch
  3041 	}
  3042 }
  3043 
  3044 void MapEditor::colorSubtree (QColor c)
  3045 {
  3046 	BranchObj *bo=xelection.getBranch();
  3047 	if (bo) 
  3048 	{
  3049 		saveStateChangingPart(
  3050 			bo, 
  3051 			bo,
  3052 			QString ("colorSubtree (\"%1\")").arg(c.name()),
  3053 			QString ("Set color of %1 and childs to %2").arg(getName(bo)).arg(c.name())
  3054 		);	
  3055 		bo->setColorSubtree (c); // color links, color childs
  3056 	}
  3057 }
  3058 
  3059 
  3060 void MapEditor::toggleStandardFlag(QString f)
  3061 {
  3062 	BranchObj *bo=xelection.getBranch();
  3063 	if (bo) 
  3064 	{
  3065 		QString u,r;
  3066 		if (bo->isSetStandardFlag(f))
  3067 		{
  3068 			r="unsetFlag";
  3069 			u="setFlag";
  3070 		}	
  3071 		else
  3072 		{
  3073 			u="unsetFlag";
  3074 			r="setFlag";
  3075 		}	
  3076 		saveState(
  3077 			bo,
  3078 			QString("%1 (\"%2\")").arg(u).arg(f), 
  3079 			bo,
  3080 			QString("%1 (\"%2\")").arg(r).arg(f),
  3081 			QString("Toggling standard flag \"%1\" of %2").arg(f).arg(getName(bo)));
  3082 		bo->toggleStandardFlag (f,mainWindow->useFlagGroups());
  3083 		xelection.update();
  3084 	}
  3085 }
  3086 
  3087 
  3088 BranchObj* MapEditor::findText (QString s, bool cs)
  3089 {
  3090 	QTextDocument::FindFlags flags=0;
  3091 	if (cs) flags=QTextDocument::FindCaseSensitively;
  3092 
  3093 	if (!itFind) 
  3094 	{	// Nothing found or new find process
  3095 		if (EOFind)
  3096 			// nothing found, start again
  3097 			EOFind=false;
  3098 		itFind=mapCenter->first();
  3099 	}	
  3100 	bool searching=true;
  3101 	bool foundNote=false;
  3102 	while (searching && !EOFind)
  3103 	{
  3104 		if (itFind)
  3105 		{
  3106 			// Searching in Note
  3107 			if (itFind->getNote().contains(s,cs))
  3108 			{
  3109 				if (xelection.single()!=itFind) 
  3110 				{
  3111 					xelection.select(itFind);
  3112 					ensureSelectionVisible();
  3113 				}
  3114 				if (textEditor->findText(s,flags)) 
  3115 				{
  3116 					searching=false;
  3117 					foundNote=true;
  3118 				}	
  3119 			}
  3120 			// Searching in Heading
  3121 			if (searching && itFind->getHeading().contains (s,cs) ) 
  3122 			{
  3123 				xelection.select(itFind);
  3124 				ensureSelectionVisible();
  3125 				searching=false;
  3126 			}
  3127 		}	
  3128 		if (!foundNote)
  3129 		{
  3130 			itFind=itFind->next();
  3131 			if (!itFind) EOFind=true;
  3132 		}
  3133 	}	
  3134 	if (!searching)
  3135 		return xelection.getBranch();
  3136 	else
  3137 		return NULL;
  3138 }
  3139 
  3140 void MapEditor::findReset()
  3141 {	// Necessary if text to find changes during a find process
  3142 	itFind=NULL;
  3143 	EOFind=false;
  3144 }
  3145 void MapEditor::setURL(const QString &url)
  3146 {
  3147 	BranchObj *bo=xelection.getBranch();
  3148 	if (bo)
  3149 	{
  3150 		QString oldurl=bo->getURL();
  3151 		bo->setURL (url);
  3152 		saveState (
  3153 			bo,
  3154 			QString ("setURL (\"%1\")").arg(oldurl),
  3155 			bo,
  3156 			QString ("setURL (\"%1\")").arg(url),
  3157 			QString ("set URL of %1 to %2").arg(getName(bo)).arg(url)
  3158 		);
  3159 		updateActions();
  3160 		mapCenter->reposition();
  3161 		xelection.update();
  3162 		ensureSelectionVisible();
  3163 	}
  3164 }	
  3165 
  3166 void MapEditor::editURL()
  3167 {
  3168 	BranchObj *bo=xelection.getBranch();
  3169 	if (bo)
  3170 	{		
  3171 		bool ok;
  3172 		QString text = QInputDialog::getText(
  3173 				"VYM", tr("Enter URL:"), QLineEdit::Normal,
  3174 				bo->getURL(), &ok, this );
  3175 		if ( ok) 
  3176 			// user entered something and pressed OK
  3177 			setURL (text);
  3178 	}
  3179 }
  3180 
  3181 void MapEditor::editLocalURL()
  3182 {
  3183 	BranchObj *bo=xelection.getBranch();
  3184 	if (bo)
  3185 	{		
  3186 		QStringList filters;
  3187 		filters <<"All files (*)";
  3188 		filters << tr("Text","Filedialog") + " (*.txt)";
  3189 		filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
  3190 		filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
  3191 		filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
  3192 		QFileDialog *fd=new QFileDialog( this,vymName+" - " +tr("Set URL to a local file"));
  3193 		fd->setFilters (filters);
  3194 		fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
  3195 		fd->setDirectory (lastFileDir);
  3196 		if (! bo->getVymLink().isEmpty() )
  3197 			fd->selectFile( bo->getURL() );
  3198 		fd->show();
  3199 
  3200 		if ( fd->exec() == QDialog::Accepted )
  3201 		{
  3202 			lastFileDir=QDir (fd->directory().path());
  3203 			setURL (fd->selectedFile() );
  3204 		}
  3205 	}
  3206 }
  3207 
  3208 QString MapEditor::getURL()
  3209 {
  3210 	BranchObj *bo=xelection.getBranch();
  3211 	if (bo)
  3212 		return bo->getURL();
  3213 	else
  3214 		return "";
  3215 }
  3216 
  3217 QStringList MapEditor::getURLs()
  3218 {
  3219 	QStringList urls;
  3220 	BranchObj *bo=xelection.getBranch();
  3221 	if (bo)
  3222 	{		
  3223 		bo=bo->first();	
  3224 		while (bo) 
  3225 		{
  3226 			if (!bo->getURL().isEmpty()) urls.append( bo->getURL());
  3227 			bo=bo->next();
  3228 		}	
  3229 	}	
  3230 	return urls;
  3231 }
  3232 
  3233 
  3234 void MapEditor::editHeading2URL()
  3235 {
  3236 	BranchObj *bo=xelection.getBranch();
  3237 	if (bo)
  3238 		setURL (bo->getHeading());
  3239 }	
  3240 
  3241 void MapEditor::editBugzilla2URL()
  3242 {
  3243 	BranchObj *bo=xelection.getBranch();
  3244 	if (bo)
  3245 	{		
  3246 		QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
  3247 		setURL (url);
  3248 	}
  3249 }	
  3250 
  3251 void MapEditor::editFATE2URL()
  3252 {
  3253 	BranchObj *bo=xelection.getBranch();
  3254 	if (bo)
  3255 	{		
  3256 		QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
  3257 		saveState(
  3258 			bo,
  3259 			"setURL (\""+bo->getURL()+"\")",
  3260 			bo,
  3261 			"setURL (\""+url+"\")",
  3262 			QString("Use heading of %1 as link to FATE").arg(getName(bo))
  3263 		);	
  3264 		bo->setURL (url);
  3265 		updateActions();
  3266 	}
  3267 }	
  3268 
  3269 void MapEditor::editVymLink()
  3270 {
  3271 	BranchObj *bo=xelection.getBranch();
  3272 	if (bo)
  3273 	{		
  3274 		QStringList filters;
  3275 		filters <<"VYM map (*.vym)";
  3276 		QFileDialog *fd=new QFileDialog( this,vymName+" - " +tr("Link to another map"));
  3277 		fd->setFilters (filters);
  3278 		fd->setCaption(vymName+" - " +tr("Link to another map"));
  3279 		fd->setDirectory (lastFileDir);
  3280 		if (! bo->getVymLink().isEmpty() )
  3281 			fd->selectFile( bo->getVymLink() );
  3282 		fd->show();
  3283 
  3284 		QString fn;
  3285 		if ( fd->exec() == QDialog::Accepted )
  3286 		{
  3287 			lastFileDir=QDir (fd->directory().path());
  3288 			saveState(
  3289 				bo,
  3290 				"setVymLink (\""+bo->getVymLink()+"\")",
  3291 				bo,
  3292 				"setVymLink (\""+fd->selectedFile()+"\")",
  3293 				QString("Set vymlink of %1 to %2").arg(getName(bo)).arg(fd->selectedFile())
  3294 			);	
  3295 			setVymLinkInt (fd->selectedFile() );
  3296 		}
  3297 	}
  3298 }
  3299 
  3300 void MapEditor::deleteVymLink()
  3301 {
  3302 	BranchObj *bo=xelection.getBranch();
  3303 	if (bo)
  3304 	{		
  3305 		saveState(
  3306 			bo,
  3307 			"setVymLink (\""+bo->getVymLink()+"\")",
  3308 			bo,
  3309 			"setVymLink (\"\")",
  3310 			QString("Unset vymlink of %1").arg(getName(bo))
  3311 		);	
  3312 		bo->setVymLink ("" );
  3313 		updateActions();
  3314 		mapCenter->reposition();
  3315 		scene()->update();
  3316 	}
  3317 }
  3318 
  3319 void MapEditor::setHideExport(bool b)
  3320 {
  3321 	BranchObj *bo=xelection.getBranch();
  3322 	if (bo)
  3323 	{
  3324 		bo->setHideInExport (b);
  3325 		QString u= b ? "false" : "true";
  3326 		QString r=!b ? "false" : "true";
  3327 		
  3328 		saveState(
  3329 			bo,
  3330 			QString ("setHideExport (%1)").arg(u),
  3331 			bo,
  3332 			QString ("setHideExport (%1)").arg(r),
  3333 			QString ("Set HideExport flag of %1 to %2").arg(getName(bo)).arg (r)
  3334 		);	
  3335 		updateActions();
  3336 		mapCenter->reposition();
  3337 		xelection.update();
  3338 		scene()->update();
  3339 	}
  3340 }
  3341 
  3342 void MapEditor::toggleHideExport()
  3343 {
  3344 	BranchObj *bo=xelection.getBranch();
  3345 	if (bo)
  3346 		setHideExport ( !bo->hideInExport() );
  3347 }
  3348 
  3349 QString MapEditor::getVymLink()
  3350 {
  3351 	BranchObj *bo=xelection.getBranch();
  3352 	if (bo)
  3353 		return bo->getVymLink();
  3354 	else	
  3355 		return "";
  3356 	
  3357 }
  3358 
  3359 QStringList MapEditor::getVymLinks()
  3360 {
  3361 	QStringList links;
  3362 	BranchObj *bo=xelection.getBranch();
  3363 	if (bo)
  3364 	{		
  3365 		bo=bo->first();	
  3366 		while (bo) 
  3367 		{
  3368 			if (!bo->getVymLink().isEmpty()) links.append( bo->getVymLink());
  3369 			bo=bo->next();
  3370 		}	
  3371 	}	
  3372 	return links;
  3373 }
  3374 
  3375 
  3376 void MapEditor::deleteKeepChilds()
  3377 {
  3378 	BranchObj *bo=xelection.getBranch();
  3379 	BranchObj *par;
  3380 	if (bo)
  3381 	{
  3382 		par=(BranchObj*)(bo->getParObj());
  3383 		QPointF p=bo->getRelPos();
  3384 		saveStateChangingPart(
  3385 			bo->getParObj(),
  3386 			bo,
  3387 			"deleteKeepChilds ()",
  3388 			QString("Remove %1 and keep its childs").arg(getName(bo))
  3389 		);
  3390 
  3391 		QString sel=bo->getSelectString();
  3392 		unselect();
  3393 		par->removeBranchHere(bo);
  3394 		mapCenter->reposition();
  3395 		select (sel);
  3396 		xelection.getBranch()->move2RelPos (p);
  3397 		mapCenter->reposition();
  3398 	}	
  3399 }
  3400 
  3401 void MapEditor::deleteChilds()
  3402 {
  3403 	BranchObj *bo=xelection.getBranch();
  3404 	if (bo)
  3405 	{		
  3406 		saveStateChangingPart(
  3407 			bo, 
  3408 			bo,
  3409 			"deleteChilds ()",
  3410 			QString( "Remove childs of branch %1").arg(getName(bo))
  3411 		);
  3412 		bo->removeChilds();
  3413 		mapCenter->reposition();
  3414 	}	
  3415 }
  3416 
  3417 void MapEditor::editMapInfo()
  3418 {
  3419 	ExtraInfoDialog dia;
  3420 	dia.setMapName (getFileName() );
  3421 	dia.setAuthor (mapCenter->getAuthor() );
  3422 	dia.setComment(mapCenter->getComment() );
  3423 
  3424 	// Calc some stats
  3425 	QString stats;
  3426     stats+=tr("%1 items on map\n","Info about map").arg (mapScene->items().size(),6);
  3427 
  3428 	uint b=0;
  3429 	uint f=0;
  3430 	uint n=0;
  3431 	uint xl=0;
  3432 	BranchObj *bo;
  3433 	bo=mapCenter->first();
  3434 	while (bo) 
  3435 	{
  3436 		if (!bo->getNote().isEmpty() ) n++;
  3437 		f+= bo->countFloatImages();
  3438 		b++;
  3439 		xl+=bo->countXLinks();
  3440 		bo=bo->next();
  3441 	}
  3442     stats+=QString ("%1 branches\n").arg (b-1,6);
  3443     stats+=QString ("%1 xLinks \n").arg (xl,6);
  3444     stats+=QString ("%1 notes\n").arg (n,6);
  3445     stats+=QString ("%1 images\n").arg (f,6);
  3446 	dia.setStats (stats);
  3447 
  3448 	// Finally show dialog
  3449 	if (dia.exec() == QDialog::Accepted)
  3450 	{
  3451 		setMapAuthor (dia.getAuthor() );
  3452 		setMapComment (dia.getComment() );
  3453 	}
  3454 }
  3455 
  3456 void MapEditor::ensureSelectionVisible()
  3457 {
  3458 	LinkableMapObj *lmo=xelection.single();
  3459 	if (lmo) ensureVisible (lmo->getBBox() );
  3460 	
  3461 }
  3462 
  3463 void MapEditor::updateSelection()
  3464 {
  3465 	// Tell selection to update geometries
  3466 	xelection.update();
  3467 }
  3468 
  3469 void MapEditor::updateActions()
  3470 {
  3471 	// Tell mainwindow to update states of actions
  3472 	mainWindow->updateActions();
  3473 	// TODO maybe don't update if blockReposition is set
  3474 }
  3475 
  3476 void MapEditor::updateNoteFlag()
  3477 {
  3478 	setChanged();
  3479 	BranchObj *bo=xelection.getBranch();
  3480 	if (bo) 
  3481 	{
  3482 		bo->updateNoteFlag();
  3483 		mainWindow->updateActions();
  3484 	}	
  3485 }
  3486 
  3487 void MapEditor::setMapAuthor (const QString &s)
  3488 {
  3489 	saveState (
  3490 		mapCenter,
  3491 		QString ("setMapAuthor (\"%1\")").arg(mapCenter->getAuthor()),
  3492 		mapCenter,
  3493 		QString ("setMapAuthor (\"%1\")").arg(s),
  3494 		QString ("Set author of map to \"%1\"").arg(s)
  3495 	);
  3496 	mapCenter->setAuthor (s);
  3497 }
  3498 
  3499 void MapEditor::setMapComment (const QString &s)
  3500 {
  3501 	saveState (
  3502 		mapCenter,
  3503 		QString ("setMapComment (\"%1\")").arg(mapCenter->getComment()),
  3504 		mapCenter,
  3505 		QString ("setMapComment (\"%1\")").arg(s),
  3506 		QString ("Set comment of map")
  3507 	);
  3508 	mapCenter->setComment (s);
  3509 }
  3510 
  3511 void MapEditor::setMapLinkStyle (const QString & s)
  3512 {
  3513 	saveStateChangingPart (
  3514 		mapCenter,
  3515 		mapCenter,
  3516 		QString("setMapLinkStyle (\"%1\")").arg(s),
  3517 		QString("Set map link style (\"%1\")").arg(s)
  3518 	);	
  3519 
  3520 	if (s=="StyleLine")
  3521 		linkstyle=LinkableMapObj::Line;
  3522 	else if (s=="StyleParabel")
  3523 		linkstyle=LinkableMapObj::Parabel;
  3524 	else if (s=="StylePolyLine")
  3525 		linkstyle=LinkableMapObj::PolyLine;
  3526 	else	
  3527 		linkstyle=LinkableMapObj::PolyParabel;
  3528 
  3529 	BranchObj *bo;
  3530 	bo=mapCenter->first();
  3531 	bo=bo->next();
  3532 	while (bo) 
  3533 	{
  3534 		bo->setLinkStyle(bo->getDefLinkStyle());
  3535 		bo=bo->next();
  3536 	}
  3537 	mapCenter->reposition();
  3538 }
  3539 
  3540 LinkableMapObj::Style MapEditor::getMapLinkStyle ()
  3541 {
  3542 	return linkstyle;
  3543 }	
  3544 
  3545 void MapEditor::setMapDefLinkColor(QColor c)
  3546 {
  3547 	defLinkColor=c;
  3548 	BranchObj *bo;
  3549 	bo=mapCenter->first();
  3550 	while (bo) 
  3551 	{
  3552 		bo->setLinkColor();
  3553 		bo=bo->next();
  3554 	}
  3555 	updateActions();
  3556 }
  3557 
  3558 void MapEditor::setMapLinkColorHintInt()
  3559 {
  3560 	// called from setMapLinkColorHint(lch) or at end of parse
  3561 	BranchObj *bo;
  3562 	bo=mapCenter->first();
  3563 	while (bo) 
  3564 	{
  3565 		bo->setLinkColor();
  3566 		bo=bo->next();
  3567 	}
  3568 }
  3569 
  3570 void MapEditor::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
  3571 {
  3572 	linkcolorhint=lch;
  3573 	setMapLinkColorHintInt();
  3574 }
  3575 
  3576 void MapEditor::toggleMapLinkColorHint()
  3577 {
  3578 	if (linkcolorhint==LinkableMapObj::HeadingColor)
  3579 		linkcolorhint=LinkableMapObj::DefaultColor;
  3580 	else	
  3581 		linkcolorhint=LinkableMapObj::HeadingColor;
  3582 	BranchObj *bo;
  3583 	bo=mapCenter->first();
  3584 	while (bo) 
  3585 	{
  3586 		bo->setLinkColor();
  3587 		bo=bo->next();
  3588 	}
  3589 }
  3590 
  3591 LinkableMapObj::ColorHint MapEditor::getMapLinkColorHint()
  3592 {
  3593 	return linkcolorhint;
  3594 }
  3595 
  3596 QColor MapEditor::getMapDefLinkColor()
  3597 {
  3598 	return defLinkColor;
  3599 }
  3600 
  3601 void MapEditor::setMapDefXLinkColor(QColor col)
  3602 {
  3603 	defXLinkColor=col;
  3604 }
  3605 
  3606 QColor MapEditor::getMapDefXLinkColor()
  3607 {
  3608 	return defXLinkColor;
  3609 }
  3610 
  3611 void MapEditor::setMapDefXLinkWidth (int w)
  3612 {
  3613 	defXLinkWidth=w;
  3614 }
  3615 
  3616 int MapEditor::getMapDefXLinkWidth()
  3617 {
  3618 	return defXLinkWidth;
  3619 }
  3620 
  3621 void MapEditor::selectMapLinkColor()
  3622 {
  3623 	QColor col = QColorDialog::getColor( defLinkColor, this );
  3624 	if ( !col.isValid() ) return;
  3625 	saveState (
  3626 		mapCenter,
  3627 		QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
  3628 		mapCenter,
  3629 		QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
  3630 		QString("Set map link color to %1").arg(col.name())
  3631 	);
  3632 	setMapDefLinkColor( col );
  3633 }
  3634 
  3635 void MapEditor::selectMapSelectionColor()
  3636 {
  3637 	QColor col = QColorDialog::getColor( defLinkColor, this );
  3638 	setSelectionColor (col);
  3639 }
  3640 
  3641 void MapEditor::setSelectionColorInt (QColor col)
  3642 {
  3643 	if ( !col.isValid() ) return;
  3644 	xelection.setColor (col);
  3645 }
  3646 
  3647 void MapEditor::setSelectionColor(QColor col)
  3648 {
  3649 	if ( !col.isValid() ) return;
  3650 	saveState (
  3651 		mapCenter,
  3652 		QString("setSelectionColor (%1)").arg(xelection.getColor().name()),
  3653 		mapCenter,
  3654 		QString("setSelectionColor (%1)").arg(col.name()),
  3655 		QString("Set color of selection box to %1").arg(col.name())
  3656 	);
  3657 	setSelectionColorInt (col);
  3658 }
  3659 
  3660 QColor MapEditor::getSelectionColor()
  3661 {
  3662 	return xelection.getColor();
  3663 }
  3664 
  3665 bool MapEditor::scrollBranch(BranchObj *bo)
  3666 {
  3667 	if (bo)
  3668 	{
  3669 		if (bo->isScrolled()) return false;
  3670 		if (bo->countBranches()==0) return false;
  3671 		if (bo->getDepth()==0) return false;
  3672 		QString u,r;
  3673 		r="scroll";
  3674 		u="unscroll";
  3675 		saveState(
  3676 			bo,
  3677 			QString ("%1 ()").arg(u),
  3678 			bo,
  3679 			QString ("%1 ()").arg(r),
  3680 			QString ("%1 %2").arg(r).arg(getName(bo))
  3681 		);
  3682 		bo->toggleScroll();
  3683 		xelection.update();
  3684 		scene()->update();
  3685 		return true;
  3686 	}	
  3687 	return false;
  3688 }
  3689 
  3690 bool MapEditor::unscrollBranch(BranchObj *bo)
  3691 {
  3692 	if (bo)
  3693 	{
  3694 		if (!bo->isScrolled()) return false;
  3695 		if (bo->countBranches()==0) return false;
  3696 		if (bo->getDepth()==0) return false;
  3697 		QString u,r;
  3698 		u="scroll";
  3699 		r="unscroll";
  3700 		saveState(
  3701 			bo,
  3702 			QString ("%1 ()").arg(u),
  3703 			bo,
  3704 			QString ("%1 ()").arg(r),
  3705 			QString ("%1 %2").arg(r).arg(getName(bo))
  3706 		);
  3707 		bo->toggleScroll();
  3708 		xelection.update();
  3709 		scene()->update();
  3710 		return true;
  3711 	}	
  3712 	return false;
  3713 }
  3714 
  3715 void MapEditor::toggleScroll()
  3716 {
  3717 	BranchObj *bo=xelection.getBranch();
  3718 	if (xelection.type()==Selection::Branch )
  3719 	{
  3720 		if (bo->isScrolled())
  3721 			unscrollBranch (bo);
  3722 		else
  3723 			scrollBranch (bo);
  3724 	}
  3725 }
  3726 
  3727 void MapEditor::unscrollChilds() 
  3728 {
  3729 	BranchObj *bo=xelection.getBranch();
  3730 	if (bo)
  3731 	{
  3732 		bo->first();
  3733 		while (bo) 
  3734 		{
  3735 			if (bo->isScrolled()) unscrollBranch (bo);
  3736 			bo=bo->next();
  3737 		}
  3738 	}	
  3739 }
  3740 
  3741 FloatImageObj* MapEditor::loadFloatImageInt (QString fn)
  3742 {
  3743 	BranchObj *bo=xelection.getBranch();
  3744 	if (bo)
  3745 	{
  3746 		FloatImageObj *fio;
  3747 		bo->addFloatImage();
  3748 		fio=bo->getLastFloatImage();
  3749 		fio->load(fn);
  3750 		mapCenter->reposition();
  3751 		scene()->update();
  3752 		return fio;
  3753 	}
  3754 	return NULL;
  3755 }	
  3756 
  3757 void MapEditor::loadFloatImage ()
  3758 {
  3759 	BranchObj *bo=xelection.getBranch();
  3760 	if (bo)
  3761 	{
  3762 
  3763 		Q3FileDialog *fd=new Q3FileDialog( this);
  3764 		fd->setMode (Q3FileDialog::ExistingFiles);
  3765 		fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
  3766 		ImagePreview *p =new ImagePreview (fd);
  3767 		fd->setContentsPreviewEnabled( TRUE );
  3768 		fd->setContentsPreview( p, p );
  3769 		fd->setPreviewMode( Q3FileDialog::Contents );
  3770 		fd->setCaption(vymName+" - " +tr("Load image"));
  3771 		fd->setDir (lastImageDir);
  3772 		fd->show();
  3773 
  3774 		if ( fd->exec() == QDialog::Accepted )
  3775 		{
  3776 			// TODO loadFIO in QT4 use:	lastImageDir=fd->directory();
  3777 			lastImageDir=QDir (fd->dirPath());
  3778 			QString s;
  3779 			FloatImageObj *fio;
  3780 			for (int j=0; j<fd->selectedFiles().count(); j++)
  3781 			{
  3782 				s=fd->selectedFiles().at(j);
  3783 				fio=loadFloatImageInt (s);
  3784 				if (fio)
  3785 					saveState(
  3786 						(LinkableMapObj*)fio,
  3787 						"delete ()",
  3788 						bo, 
  3789 						QString ("loadImage (%1)").arg(s ),
  3790 						QString("Add image %1 to %2").arg(s).arg(getName(bo))
  3791 					);
  3792 				else
  3793 					// TODO loadFIO error handling
  3794 					qWarning ("Failed to load "+s);
  3795 			}
  3796 		}
  3797 		delete (p);
  3798 		delete (fd);
  3799 	}
  3800 }
  3801 
  3802 void MapEditor::saveFloatImageInt  (FloatImageObj *fio, const QString &type, const QString &fn)
  3803 {
  3804 	fio->save (fn,type);
  3805 }
  3806 
  3807 void MapEditor::saveFloatImage ()
  3808 {
  3809 	FloatImageObj *fio=xelection.getFloatImage();
  3810 	if (fio)
  3811 	{
  3812 		QFileDialog *fd=new QFileDialog( this);
  3813 		fd->setFilters (imageIO.getFilters());
  3814 		fd->setCaption(vymName+" - " +tr("Save image"));
  3815 		fd->setFileMode( QFileDialog::AnyFile );
  3816 		fd->setDirectory (lastImageDir);
  3817 //		fd->setSelection (fio->getOriginalFilename());
  3818 		fd->show();
  3819 
  3820 		QString fn;
  3821 		if ( fd->exec() == QDialog::Accepted && fd->selectedFiles().count()==1)
  3822 		{
  3823 			fn=fd->selectedFiles().at(0);
  3824 			if (QFile (fn).exists() )
  3825 			{
  3826 				QMessageBox mb( vymName,
  3827 					tr("The file %1 exists already.\n"
  3828 					"Do you want to overwrite it?").arg(fn),
  3829 				QMessageBox::Warning,
  3830 				QMessageBox::Yes | QMessageBox::Default,
  3831 				QMessageBox::Cancel | QMessageBox::Escape,
  3832 				QMessageBox::QMessageBox::NoButton );
  3833 
  3834 				mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
  3835 				mb.setButtonText( QMessageBox::No, tr("Cancel"));
  3836 				switch( mb.exec() ) 
  3837 				{
  3838 					case QMessageBox::Yes:
  3839 						// save 
  3840 						break;;
  3841 					case QMessageBox::Cancel:
  3842 						// do nothing
  3843 						delete (fd);
  3844 						return;
  3845 						break;
  3846 				}
  3847 			}
  3848 			saveFloatImageInt (fio,fd->selectedFilter(),fn );
  3849 		}
  3850 		delete (fd);
  3851 	}
  3852 }
  3853 
  3854 void MapEditor::setFrameType(const FrameObj::FrameType &t)
  3855 {
  3856 	BranchObj *bo=xelection.getBranch();
  3857 	if (bo)
  3858 	{
  3859 		QString s=bo->getFrameTypeName();
  3860 		bo->setFrameType (t);
  3861 		saveState (bo, QString("setFrameType (\"%1\")").arg(s),
  3862 			bo, QString ("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),QString ("set type of frame to %1").arg(s));
  3863 		mapCenter->reposition();
  3864 		bo->updateLink();
  3865 	}
  3866 }
  3867 
  3868 void MapEditor::setFrameType(const QString &s)	
  3869 {
  3870 	BranchObj *bo=xelection.getBranch();
  3871 	if (bo)
  3872 	{
  3873 		saveState (bo, QString("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),
  3874 			bo, QString ("setFrameType (\"%1\")").arg(s),QString ("set type of frame to %1").arg(s));
  3875 		bo->setFrameType (s);
  3876 		mapCenter->reposition();
  3877 		bo->updateLink();
  3878 	}
  3879 }
  3880 
  3881 void MapEditor::setFramePenColor(const QColor &c)	
  3882 {
  3883 	BranchObj *bo=xelection.getBranch();
  3884 	if (bo)
  3885 	{
  3886 		saveState (bo, QString("setFramePenColor (\"%1\")").arg(bo->getFramePenColor().name() ),
  3887 			bo, QString ("setFramePenColor (\"%1\")").arg(c.name() ),QString ("set pen color of frame to %1").arg(c.name() ));
  3888 		bo->setFramePenColor (c);
  3889 	}	
  3890 }
  3891 
  3892 void MapEditor::setFrameBrushColor(const QColor &c)	
  3893 {
  3894 	BranchObj *bo=xelection.getBranch();
  3895 	if (bo)
  3896 	{
  3897 		saveState (bo, QString("setFrameBrushColor (\"%1\")").arg(bo->getFrameBrushColor().name() ),
  3898 			bo, QString ("setFrameBrushColor (\"%1\")").arg(c.name() ),QString ("set brush color of frame to %1").arg(c.name() ));
  3899 		bo->setFrameBrushColor (c);
  3900 	}	
  3901 }
  3902 
  3903 void MapEditor::setFramePadding (const int &i)
  3904 {
  3905 	BranchObj *bo=xelection.getBranch();
  3906 	if (bo)
  3907 	{
  3908 		saveState (bo, QString("setFramePadding (\"%1\")").arg(bo->getFramePadding() ),
  3909 			bo, QString ("setFramePadding (\"%1\")").arg(i),QString ("set brush color of frame to %1").arg(i));
  3910 		bo->setFramePadding (i);
  3911 		mapCenter->reposition();
  3912 		bo->updateLink();
  3913 	}	
  3914 }
  3915 
  3916 void MapEditor::setFrameBorderWidth(const int &i)
  3917 {
  3918 	BranchObj *bo=xelection.getBranch();
  3919 	if (bo)
  3920 	{
  3921 		saveState (bo, QString("setFrameBorderWidth (\"%1\")").arg(bo->getFrameBorderWidth() ),
  3922 			bo, QString ("setFrameBorderWidth (\"%1\")").arg(i),QString ("set border width of frame to %1").arg(i));
  3923 		bo->setFrameBorderWidth (i);
  3924 		mapCenter->reposition();
  3925 		bo->updateLink();
  3926 	}	
  3927 }
  3928 
  3929 void MapEditor::setIncludeImagesVer(bool b)	
  3930 {
  3931 	BranchObj *bo=xelection.getBranch();
  3932 	if (bo)
  3933 	{
  3934 		QString u= b ? "false" : "true";
  3935 		QString r=!b ? "false" : "true";
  3936 		
  3937 		saveState(
  3938 			bo,
  3939 			QString("setIncludeImagesVertically (%1)").arg(u),
  3940 			bo, 
  3941 			QString("setIncludeImagesVertically (%1)").arg(r),
  3942 			QString("Include images vertically in %1").arg(getName(bo))
  3943 		);	
  3944 		bo->setIncludeImagesVer(b);
  3945 		mapCenter->reposition();
  3946 	}	
  3947 }
  3948 
  3949 void MapEditor::setIncludeImagesHor(bool b)	
  3950 {
  3951 	BranchObj *bo=xelection.getBranch();
  3952 	if (bo)
  3953 	{
  3954 		QString u= b ? "false" : "true";
  3955 		QString r=!b ? "false" : "true";
  3956 		
  3957 		saveState(
  3958 			bo,
  3959 			QString("setIncludeImagesHorizontally (%1)").arg(u),
  3960 			bo, 
  3961 			QString("setIncludeImagesHorizontally (%1)").arg(r),
  3962 			QString("Include images horizontally in %1").arg(getName(bo))
  3963 		);	
  3964 		bo->setIncludeImagesHor(b);
  3965 		mapCenter->reposition();
  3966 	}	
  3967 }
  3968 
  3969 void MapEditor::setHideLinkUnselected (bool b)
  3970 {
  3971 	LinkableMapObj *sel=xelection.single();
  3972 	if (sel &&
  3973 		(xelection.type() == Selection::Branch || 
  3974 		xelection.type() == Selection::MapCenter  ||
  3975 		xelection.type() == Selection::FloatImage ))
  3976 	{
  3977 		QString u= b ? "false" : "true";
  3978 		QString r=!b ? "false" : "true";
  3979 		
  3980 		saveState(
  3981 			sel,
  3982 			QString("setHideLinkUnselected (%1)").arg(u),
  3983 			sel, 
  3984 			QString("setHideLinkUnselected (%1)").arg(r),
  3985 			QString("Hide link of %1 if unselected").arg(getName(sel))
  3986 		);	
  3987 		sel->setHideLinkUnselected(b);
  3988 	}
  3989 }
  3990 
  3991 void MapEditor::importDirInt(BranchObj *dst, QDir d)
  3992 {
  3993 	BranchObj *bo=xelection.getBranch();
  3994 	if (bo)
  3995 	{
  3996 		// Traverse directories
  3997 		d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
  3998 		QFileInfoList list = d.entryInfoList();
  3999 		QFileInfo fi;
  4000 
  4001 		for (int i = 0; i < list.size(); ++i) 
  4002 		{
  4003 			fi=list.at(i);
  4004 			if (fi.fileName() != "." && fi.fileName() != ".." )
  4005 			{
  4006 				dst->addBranch();
  4007 				bo=dst->getLastBranch();
  4008 				bo->setHeading (fi.fileName() );
  4009 				bo->setColor (QColor("blue"));
  4010 				bo->toggleScroll();
  4011 				if ( !d.cd(fi.fileName()) ) 
  4012 					QMessageBox::critical (0,tr("Critical Import Error"),tr("Cannot find the directory %1").arg(fi.fileName()));
  4013 				else 
  4014 				{
  4015 					// Recursively add subdirs
  4016 					importDirInt (bo,d);
  4017 					d.cdUp();
  4018 				}
  4019 			}	
  4020 		}		
  4021 		// Traverse files
  4022 		d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
  4023 		list = d.entryInfoList();
  4024 
  4025 		for (int i = 0; i < list.size(); ++i) 
  4026 		{
  4027 			fi=list.at(i);
  4028 			dst->addBranch();
  4029 			bo=dst->getLastBranch();
  4030 			bo->setHeading (fi.fileName() );
  4031 			bo->setColor (QColor("black"));
  4032 			if (fi.fileName().right(4) == ".vym" )
  4033 				bo->setVymLink (fi.filePath());
  4034 		}	
  4035 	}		
  4036 }
  4037 
  4038 void MapEditor::importDirInt (const QString &s)
  4039 {
  4040 	BranchObj *bo=xelection.getBranch();
  4041 	if (bo)
  4042 	{
  4043 		saveStateChangingPart (bo,bo,QString ("importDir (\"%1\")").arg(s),QString("Import directory structure from %1").arg(s));
  4044 
  4045 		QDir d(s);
  4046 		importDirInt (bo,d);
  4047 	}
  4048 }	
  4049 
  4050 void MapEditor::importDir()
  4051 {
  4052 	BranchObj *bo=xelection.getBranch();
  4053 	if (bo)
  4054 	{
  4055 		QStringList filters;
  4056 		filters <<"VYM map (*.vym)";
  4057 		QFileDialog *fd=new QFileDialog( this,vymName+ " - " +tr("Choose directory structure to import"));
  4058 		fd->setMode (QFileDialog::DirectoryOnly);
  4059 		fd->setFilters (filters);
  4060 		fd->setCaption(vymName+" - " +tr("Choose directory structure to import"));
  4061 		fd->show();
  4062 
  4063 		QString fn;
  4064 		if ( fd->exec() == QDialog::Accepted )
  4065 		{
  4066 			importDirInt (fd->selectedFile() );
  4067 			mapCenter->reposition();
  4068 			scene()->update();
  4069 		}
  4070 	}	
  4071 }
  4072 
  4073 void MapEditor::followXLink(int i)
  4074 {
  4075 	BranchObj *bo=xelection.getBranch();
  4076 	if (bo)
  4077 	{
  4078 		bo=bo->XLinkTargetAt(i);
  4079 		if (bo) 
  4080 		{
  4081 			xelection.select(bo);
  4082 			ensureSelectionVisible();
  4083 		}
  4084 	}
  4085 }
  4086 
  4087 void MapEditor::editXLink(int i)	// FIXME missing saveState
  4088 {
  4089 	BranchObj *bo=xelection.getBranch();
  4090 	if (bo)
  4091 	{
  4092 		XLinkObj *xlo=bo->XLinkAt(i);
  4093 		if (xlo) 
  4094 		{
  4095 			EditXLinkDialog dia;
  4096 			dia.setXLink (xlo);
  4097 			dia.setSelection(bo);
  4098 			if (dia.exec() == QDialog::Accepted)
  4099 			{
  4100 				if (dia.useSettingsGlobal() )
  4101 				{
  4102 					setMapDefXLinkColor (xlo->getColor() );
  4103 					setMapDefXLinkWidth (xlo->getWidth() );
  4104 				}
  4105 				if (dia.deleteXLink())
  4106 					bo->deleteXLinkAt(i);
  4107 			}
  4108 		}	
  4109 	}
  4110 }
  4111 
  4112 void MapEditor::testFunction1()
  4113 {
  4114 	ErrorCode err=success;
  4115 	LoadMode lmode=NewMap;
  4116 
  4117 	//QString fname="test/freemind/doc/freemind.xml";
  4118 	QString fname="test/freemind/doc/icons.mm";
  4119     parseFMHandler handler;
  4120 	QFile file( fname );
  4121 
  4122 	// I am paranoid: file should exist anyway
  4123 	// according to check in mainwindow.
  4124 	if (!file.exists() )
  4125 	{
  4126 		QMessageBox::critical( 0, tr( "Critical Parse Error" ),
  4127 				   tr("Couldn't open map " +fname)+".");
  4128 		err=aborted;	
  4129 	} else
  4130 	{
  4131 		bool blockSaveStateOrg=blockSaveState;
  4132 		blockReposition=true;
  4133 		blockSaveState=true;
  4134 		QXmlInputSource source( file);
  4135 		QXmlSimpleReader reader;
  4136 		reader.setContentHandler( &handler );
  4137 		reader.setErrorHandler( &handler );
  4138 		handler.setMapEditor( this );
  4139 
  4140 
  4141 		// We need to set the tmpDir in order  to load files with rel. path
  4142 		QString tmpdir= fname.left(fname.findRev("/",-1));	
  4143 		handler.setTmpDir (tmpdir);
  4144 		handler.setInputFile (file.name());
  4145 		//handler.setLoadMode (lmode);
  4146 		bool ok = reader.parse( source );
  4147 		blockReposition=false;
  4148 		blockSaveState=blockSaveStateOrg;
  4149 		file.close();
  4150 		if ( ok ) 
  4151 		{
  4152 			mapCenter->reposition();
  4153 			xelection.update();
  4154 			if (lmode==NewMap)
  4155 			{
  4156 				mapDefault=false;
  4157 				mapChanged=false;
  4158 				mapUnsaved=false;
  4159 				autosaveTimer->stop();
  4160 			}
  4161 		} else 
  4162 		{
  4163 			QMessageBox::critical( 0, tr( "Critical Parse Error" ),
  4164 					   tr( handler.errorProtocol() ) );
  4165 			// returnCode=1;	
  4166 			// Still return "success": the map maybe at least
  4167 			// partially read by the parser
  4168 		}	
  4169 	}	
  4170 	updateActions();
  4171 	//return err;
  4172 /*
  4173 	BranchObj *bo=xelection.getBranch();
  4174 	if (bo) animObjList.append( bo );
  4175 */	
  4176 	
  4177 /*
  4178 	WarningDialog dia;
  4179 	dia.showCancelButton (true);
  4180 	dia.setText("This is a longer \nWarning");
  4181 	dia.setCaption("Warning: Flux problem");
  4182 	dia.setShowAgainName("mapeditor/testDialog");
  4183 	if (dia.exec()==QDialog::Accepted)
  4184 		cout << "accepted!\n";
  4185 	else	
  4186 		cout << "canceled!\n";
  4187 	return;
  4188 */
  4189 
  4190 /* TODO Hide hidden stuff temporary, maybe add this as regular function somewhere
  4191 	if (hidemode==HideNone)
  4192 	{
  4193 		setHideTmpMode (HideExport);
  4194 		mapCenter->calcBBoxSizeWithChilds();
  4195 		QRectF totalBBox=mapCenter->getTotalBBox();
  4196 		QRectF mapRect=totalBBox;
  4197 		QCanvasRectangle *frame=NULL;
  4198 
  4199 		cout << "  map has =("<<totalBBox.x()<<","<<totalBBox.y()<<","<<totalBBox.width()<<","<<totalBBox.height()<<")\n";
  4200 	
  4201 		mapRect.setRect (totalBBox.x(), totalBBox.y(), 
  4202 			totalBBox.width(), totalBBox.height());
  4203 		frame=new QCanvasRectangle (mapRect,mapScene);
  4204 		frame->setBrush (QColor(white));
  4205 		frame->setPen (QColor(black));
  4206 		frame->setZValue(0);
  4207 		frame->show();    
  4208 	}	
  4209 	else	
  4210 	{
  4211 		setHideTmpMode (HideNone);
  4212 	}	
  4213 	cout <<"  hidemode="<<hidemode<<endl;
  4214 	*/
  4215 }	
  4216 	
  4217 void MapEditor::testFunction2()
  4218 {
  4219 }
  4220 
  4221 void MapEditor::contextMenuEvent ( QContextMenuEvent * e )
  4222 {
  4223 	// Lineedits are already closed by preceding
  4224 	// mouseEvent, we don't need to close here.
  4225 
  4226     QPointF p = mapToScene(e->pos());
  4227     LinkableMapObj* lmo=mapCenter->findMapObj(p, NULL);
  4228 	
  4229     if (lmo) 
  4230 	{	// MapObj was found
  4231 		if (xelection.single() != lmo)
  4232 		{
  4233 			// select the MapObj
  4234 			xelection.select(lmo);
  4235 		}
  4236 		// Context Menu 
  4237 		if (xelection.getBranch() ) 
  4238 		{
  4239 			// Context Menu on branch or mapcenter
  4240 			updateActions();
  4241 			branchContextMenu->popup(e->globalPos() );
  4242 		} else
  4243 		{
  4244 			if (xelection.getFloatImage() )
  4245 			{
  4246 				// Context Menu on floatimage
  4247 				updateActions();
  4248 				floatimageContextMenu->popup(e->globalPos() );
  4249 			}	
  4250 		}	
  4251 	} else 
  4252 	{ // No MapObj found, we are on the Canvas itself
  4253 		// Context Menu on scene
  4254 		updateActions();
  4255 		canvasContextMenu->popup(e->globalPos() );
  4256     } 
  4257 	e->accept();
  4258 }
  4259 
  4260 void MapEditor::keyPressEvent(QKeyEvent* e)
  4261 {
  4262 	if (e->modifiers() & Qt::ControlModifier)
  4263 	{
  4264 		switch (mainWindow->getModMode())
  4265 		{
  4266 			case Main::ModModeColor: 
  4267 				setCursor (PickColorCursor);
  4268 				break;
  4269 			case Main::ModModeCopy: 
  4270 				setCursor (CopyCursor);
  4271 				break;
  4272 			case Main::ModModeXLink: 
  4273 				setCursor (XLinkCursor);
  4274 				break;
  4275 			default :
  4276 				setCursor (Qt::ArrowCursor);
  4277 				break;
  4278 		} 
  4279 	}	
  4280 }
  4281 
  4282 void MapEditor::keyReleaseEvent(QKeyEvent* e)
  4283 {
  4284 	if (!(e->modifiers() & Qt::ControlModifier))
  4285 		setCursor (Qt::ArrowCursor);
  4286 }
  4287 
  4288 void MapEditor::mousePressEvent(QMouseEvent* e)
  4289 {
  4290 	// Ignore right clicks, these will go to context menus
  4291 	if (e->button() == Qt::RightButton )
  4292 	{
  4293 		e->ignore();
  4294 		return;
  4295 	}
  4296 
  4297 	//Ignore clicks while editing heading
  4298 	if (isSelectBlocked() ) 
  4299 	{
  4300 		e->ignore();
  4301 		return;
  4302 	}
  4303 
  4304     QPointF p = mapToScene(e->pos());
  4305     LinkableMapObj* lmo=mapCenter->findMapObj(p, NULL);
  4306 	
  4307 	e->accept();
  4308 
  4309 	//Take care of  system flags _or_ modifier modes
  4310 	//
  4311 	if (lmo && (typeid(*lmo)==typeid(BranchObj) ||
  4312 		typeid(*lmo)==typeid(MapCenterObj) ))
  4313 	{
  4314 		QString foname=((BranchObj*)lmo)->getSystemFlagName(p);
  4315 		if (!foname.isEmpty())
  4316 		{
  4317 			// systemFlag clicked
  4318 			selectInt (lmo);
  4319 			if (foname=="url") 
  4320 			{
  4321 				if (e->state() & Qt::ControlModifier)
  4322 					mainWindow->editOpenURLTab();
  4323 				else	
  4324 					mainWindow->editOpenURL();
  4325 			}	
  4326 			else if (foname=="vymLink")
  4327 			{
  4328 				mainWindow->editOpenVymLink();
  4329 				// tabWidget may change, better return now
  4330 				// before segfaulting...
  4331 			} else if (foname=="note")
  4332 				mainWindow->windowToggleNoteEditor();
  4333 			else if (foname=="hideInExport")		
  4334 				toggleHideExport();
  4335 			xelection.update();	
  4336 			return;	
  4337 		} 
  4338 	} 
  4339 
  4340 	// No system flag clicked, take care of modmodes (CTRL-Click)
  4341 	if (e->state() & Qt::ControlModifier)
  4342 	{
  4343 		if (mainWindow->getModMode()==Main::ModModeColor)
  4344 		{
  4345 				pickingColor=true;
  4346 				setCursor (PickColorCursor);
  4347 				return;
  4348 		} 
  4349 		if (mainWindow->getModMode()==Main::ModModeXLink)
  4350 		{	
  4351 			BranchObj *bo_begin=NULL;
  4352 			if (lmo)
  4353 				bo_begin=(BranchObj*)(lmo);
  4354 			else	
  4355 				if (xelection.getBranch() ) 
  4356 					bo_begin=xelection.getBranch();
  4357 			if (bo_begin)	
  4358 			{
  4359 				drawingLink=true;
  4360 				linkingObj_src=bo_begin;
  4361 				tmpXLink=new XLinkObj (mapScene);
  4362 				tmpXLink->setBegin (bo_begin);
  4363 				tmpXLink->setEnd   (p);
  4364 				tmpXLink->setColor(defXLinkColor);
  4365 				tmpXLink->setWidth(defXLinkWidth);
  4366 				tmpXLink->updateXLink();
  4367 				tmpXLink->setVisibility (true);
  4368 				return;
  4369 			} 
  4370 		}
  4371 	}	// End of modmodes
  4372 
  4373     if (lmo) 
  4374 	{	
  4375 		// Select the clicked object
  4376 		selectInt (lmo);
  4377 
  4378 		// Left Button	    Move Branches
  4379 		if (e->button() == Qt::LeftButton )
  4380 		{
  4381 			//movingObj_start.setX( p.x() - selection->x() );// TODO replaced selection->lmo here	
  4382 			//movingObj_start.setY( p.y() - selection->y() );	
  4383 			movingObj_start.setX( p.x() - lmo->x() );	
  4384 			movingObj_start.setY( p.y() - lmo->y() );	
  4385 			movingObj_orgPos.setX (lmo->x() );
  4386 			movingObj_orgPos.setY (lmo->y() );
  4387 			movingObj_orgRelPos=lmo->getRelPos();
  4388 
  4389 			// If modMode==copy, then we want to "move" the _new_ object around
  4390 			// then we need the offset from p to the _old_ selection, because of tmp
  4391 			if (mainWindow->getModMode()==Main::ModModeCopy &&
  4392 				e->state() & Qt::ControlModifier)
  4393 			{
  4394 				if (xelection.type()==Selection::Branch)
  4395 				{
  4396 					copyingObj=true;
  4397 					mapCenter->addBranch ((BranchObj*)xelection.single());
  4398 					unselect();
  4399 					xelection.select(mapCenter->getLastBranch());
  4400 					mapCenter->reposition();
  4401 				}
  4402 			} 
  4403 
  4404 			movingObj=xelection.single();	
  4405 		} else
  4406 			// Middle Button    Toggle Scroll
  4407 			// (On Mac OS X this won't work, but we still have 
  4408 			// a button in the toolbar)
  4409 			if (e->button() == Qt::MidButton )
  4410 				toggleScroll();
  4411 		updateActions();
  4412 		xelection.update();
  4413 	} else 
  4414 	{ // No MapObj found, we are on the scene itself
  4415 		// Left Button	    move Pos of sceneView
  4416 		if (e->button() == Qt::LeftButton )
  4417 		{
  4418 			movingObj=NULL;	// move Content not Obj
  4419 			movingObj_start=e->globalPos();
  4420 			movingCont_start=QPointF (
  4421 				horizontalScrollBar()->value(),
  4422 				verticalScrollBar()->value());
  4423 			movingVec=QPointF(0,0);
  4424 			setCursor(HandOpenCursor);
  4425 		} 
  4426     } 
  4427 }
  4428 
  4429 void MapEditor::mouseMoveEvent(QMouseEvent* e)
  4430 {
  4431     QPointF p = mapToScene(e->pos());
  4432 	LinkableMapObj *lmosel=xelection.single();
  4433 
  4434     // Move the selected MapObj
  4435     if ( lmosel && movingObj) 
  4436     {	
  4437 		// reset cursor if we are moving and don't copy
  4438 		if (mainWindow->getModMode()!=Main::ModModeCopy)
  4439 			setCursor (Qt::ArrowCursor);
  4440 
  4441 		// To avoid jumping of the sceneView, only 
  4442 		// ensureSelectionVisible, if not tmp linked
  4443 		if (!lmosel->hasParObjTmp())
  4444 			ensureSelectionVisible ();
  4445 		
  4446 		// Now move the selection, but add relative position 
  4447 		// (movingObj_start) where selection was chosen with 
  4448 		// mousepointer. (This avoids flickering resp. jumping 
  4449 		// of selection back to absPos)
  4450 		
  4451 		// Check if we could link 
  4452 		LinkableMapObj* lmo=mapCenter->findMapObj(p, lmosel);
  4453 		
  4454 
  4455 		FloatObj *fio=xelection.getFloatImage();
  4456 		if (fio)
  4457 		{
  4458 			fio->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  4459 			fio->setRelPos();
  4460 			fio->updateLink(); //no need for reposition, if we update link here
  4461 			xelection.update();
  4462 
  4463 			// Relink float to new mapcenter or branch, if shift is pressed	
  4464 			// Only relink, if selection really has a new parent
  4465 			if ( (e->modifiers()==Qt::ShiftModifier) && lmo &&
  4466 				( (typeid(*lmo)==typeid(BranchObj)) ||
  4467 				  (typeid(*lmo)==typeid(MapCenterObj)) ) &&
  4468 				( lmo != fio->getParObj())  
  4469 				)
  4470 			{
  4471 				if (typeid(*fio) == typeid(FloatImageObj) && 
  4472 				( (typeid(*lmo)==typeid(BranchObj) ||
  4473 				  typeid(*lmo)==typeid(MapCenterObj)) ))  
  4474 				{
  4475 
  4476 					// Also save the move which was done so far
  4477 					QString pold=qpointfToString(movingObj_orgRelPos);
  4478 					QString pnow=qpointfToString(fio->getRelPos());
  4479 					saveState(
  4480 						fio,
  4481 						"moveRel "+pold,
  4482 						fio,
  4483 						"moveRel "+pnow,
  4484 						QString("Move %1 to relativ position %2").arg(getName(fio)).arg(pnow));
  4485 					fio->getParObj()->requestReposition();
  4486 					mapCenter->reposition();
  4487 
  4488 					linkTo (lmo->getSelectString());
  4489 					//movingObj=lmosel;
  4490 					//movingObj_orgRelPos=lmosel->getRelPos();	
  4491 
  4492 					mapCenter->reposition();
  4493 				}	
  4494 			}
  4495 		} else	
  4496 		{	// selection != a FloatObj
  4497 			if (lmosel->getDepth()==0)
  4498 			{
  4499 				// Move MapCenter
  4500 				if (e->buttons()== Qt::LeftButton && e->modifiers()==Qt::ShiftModifier) 
  4501 					mapCenter->moveAll(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  4502 				else	
  4503 					mapCenter->move   (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  4504 				mapCenter->updateRelPositions();	
  4505 			} else
  4506 			{	
  4507 				if (lmosel->getDepth()==1)
  4508 				{
  4509 					// Move mainbranch
  4510 					lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );		
  4511 					lmosel->setRelPos();
  4512 				} else
  4513 				{
  4514 					// Move ordinary branch
  4515 					if (lmosel->getOrientation() == LinkableMapObj::LeftOfCenter)
  4516 						// Add width of bbox here, otherwise alignRelTo will cause jumping around
  4517 						lmosel->move(p.x() -movingObj_start.x()+lmosel->getBBox().width(), 
  4518 							p.y()-movingObj_start.y() +lmosel->getTopPad() );		
  4519 					else	
  4520 						lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() -lmosel->getTopPad());
  4521 				} 
  4522 
  4523 				// Maybe we can relink temporary?
  4524 				if (lmo && (lmo!=lmosel) && xelection.getBranch() && 
  4525 					 (typeid(*lmo)==typeid(BranchObj) ||
  4526 					  typeid(*lmo)==typeid(MapCenterObj)) ) 
  4527 
  4528 				{
  4529 					if (e->modifiers()==Qt::ControlModifier)
  4530 					{
  4531 						// Special case: CTRL to link below lmo
  4532 						lmosel->setParObjTmp (lmo,p,+1);
  4533 					}
  4534 					else if (e->modifiers()==Qt::ShiftModifier)
  4535 						lmosel->setParObjTmp (lmo,p,-1);
  4536 					else
  4537 						lmosel->setParObjTmp (lmo,p,0);
  4538 				} else	
  4539 				{
  4540 					lmosel->unsetParObjTmp();
  4541 				}		
  4542 				// reposition subbranch
  4543 				lmosel->reposition();	
  4544 			} // depth>0
  4545 
  4546 			xelection.update();
  4547 		} // no FloatImageObj
  4548 
  4549 		scene()->update();
  4550 		return;
  4551 	} // selection && moving_obj
  4552 		
  4553 	// Draw a link from one branch to another
  4554 	if (drawingLink)
  4555 	{
  4556 		 tmpXLink->setEnd (p);
  4557 		 tmpXLink->updateXLink();
  4558 	}	 
  4559 	
  4560     // Move sceneView 
  4561     if (!movingObj && !pickingColor &&!drawingLink && e->buttons() == Qt::LeftButton ) 
  4562 	{
  4563 		QPointF p=e->globalPos();
  4564 		movingVec.setX(-p.x() + movingObj_start.x() );
  4565 		movingVec.setY(-p.y() + movingObj_start.y() );
  4566 		horizontalScrollBar()->setSliderPosition((int)( movingCont_start.x()+movingVec.x() ));
  4567 		verticalScrollBar()->setSliderPosition((int)( movingCont_start.y()+movingVec.y() ) );
  4568     }
  4569 }
  4570 
  4571 
  4572 void MapEditor::mouseReleaseEvent(QMouseEvent* e)
  4573 {
  4574     QPointF p = mapToScene(e->pos());
  4575 	LinkableMapObj *dst;
  4576 	LinkableMapObj *lmosel=xelection.single();
  4577 	// Have we been picking color?
  4578 	if (pickingColor)
  4579 	{
  4580 		pickingColor=false;
  4581 		setCursor (Qt::ArrowCursor);
  4582 		// Check if we are over another branch
  4583 		dst=mapCenter->findMapObj(p, NULL);
  4584 		if (dst && lmosel) 
  4585 		{	
  4586 			if (e->state() & Qt::ShiftModifier)
  4587 				colorBranch (((BranchObj*)(dst))->getColor());
  4588 			else	
  4589 				colorSubtree (((BranchObj*)(dst))->getColor());
  4590 		} 
  4591 		return;
  4592 	}
  4593 
  4594 	// Have we been drawing a link?
  4595 	if (drawingLink)	
  4596 	{
  4597 		drawingLink=false;
  4598 		// Check if we are over another branch
  4599 		dst=mapCenter->findMapObj(p, NULL);
  4600 		if (dst && lmosel) 
  4601 		{	
  4602 			tmpXLink->setEnd ( ((BranchObj*)(dst)) );
  4603 			tmpXLink->updateXLink();
  4604 			tmpXLink->activate(); //FIXME savestate missing
  4605 			//saveStateComplete(QString("Activate xLink from %1 to %2").arg(getName(tmpXLink->getBegin())).arg(getName(tmpXLink->getEnd())) );	
  4606 		} else
  4607 		{
  4608 			delete(tmpXLink);
  4609 			tmpXLink=NULL;
  4610 		}
  4611 		return;
  4612 	}
  4613 	
  4614     // Have we been moving something?
  4615     if ( lmosel && movingObj ) 
  4616     {	
  4617 		FloatImageObj *fo=xelection.getFloatImage();
  4618 		if(fo)
  4619 		{
  4620 			// Moved FloatObj. Maybe we need to reposition
  4621 		    QString pold=qpointfToString(movingObj_orgRelPos);
  4622 		    QString pnow=qpointfToString(fo->getRelPos());
  4623 			saveState(
  4624 				fo,
  4625 				"moveRel "+pold,
  4626 				fo,
  4627 				"moveRel "+pnow,
  4628 				QString("Move %1 to relativ position %2").arg(getName(fo)).arg(pnow));
  4629 
  4630 			fo->getParObj()->requestReposition();
  4631 			mapCenter->reposition();
  4632 		}	
  4633 
  4634 		// Check if we are over another branch, but ignore 
  4635 		// any found LMOs, which are FloatObjs
  4636 		dst=mapCenter->findMapObj(mapToScene(e->pos() ), lmosel);
  4637 
  4638 		if (dst && (typeid(*dst)!=typeid(BranchObj) && typeid(*dst)!=typeid(MapCenterObj))) 
  4639 			dst=NULL;
  4640 		
  4641 		if (xelection.type() == Selection::MapCenter )
  4642 		{	
  4643 			// TODO: Check for problems if graphicsview is resized for 
  4644 			// undo/redo...
  4645 		    QString pold=qpointfToString(movingObj_orgPos);
  4646 		    QString pnow=qpointfToString(mapCenter->getAbsPos());
  4647 			saveState(
  4648 				fo,
  4649 				"move "+pold,
  4650 				fo,
  4651 				"move "+pnow,
  4652 				QString("Move mapcenter %1 to position %2").arg(getName(mapCenter)).arg(pnow));
  4653 		}
  4654 		
  4655 		if (xelection.type() == Selection::Branch )
  4656 		{	// A branch was moved
  4657 			
  4658 			// save the position in case we link to mapcenter
  4659 			QPointF savePos=QPointF (lmosel->getAbsPos()  );
  4660 
  4661 			// Reset the temporary drawn link to the original one
  4662 			lmosel->unsetParObjTmp();
  4663 
  4664 			// For Redo we may need to save original selection
  4665 			QString preSelStr=lmosel->getSelectString();
  4666 
  4667 			copyingObj=false;	
  4668 			if (dst ) 
  4669 			{
  4670 				BranchObj* bsel=xelection.getBranch();
  4671 				BranchObj* bdst=(BranchObj*)dst;
  4672 
  4673 				QString preParStr=(bsel->getParObj())->getSelectString();
  4674 				QString preNum=QString::number (bsel->getNum(),10);
  4675 				QString preDstParStr;
  4676 
  4677 				if (e->state() & Qt::ShiftModifier && dst->getParObj())
  4678 				{	// Link above dst
  4679 					preDstParStr=dst->getParObj()->getSelectString();
  4680 					bsel->linkTo ( (BranchObj*)(bdst->getParObj()), bdst->getNum());
  4681 				} else 
  4682 				if (e->state() & Qt::ControlModifier && dst->getParObj())
  4683 				{
  4684 					// Link below dst
  4685 					preDstParStr=dst->getParObj()->getSelectString();
  4686 					bsel->linkTo ( (BranchObj*)(bdst->getParObj()), bdst->getNum()+1);
  4687 				} else	
  4688 				{	// Append to dst
  4689 					preDstParStr=dst->getSelectString();
  4690 					bsel->linkTo (bdst,-1);
  4691 					if (dst->getDepth()==0) bsel->move (savePos);
  4692 				} 
  4693 				QString postSelStr=lmosel->getSelectString();
  4694 				QString postNum=QString::number (bsel->getNum(),10);
  4695 
  4696 				QString undoCom="linkTo (\""+ 
  4697 					preParStr+ "\"," + preNum  +"," + 
  4698 					QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+ ")";
  4699 
  4700 				QString redoCom="linkTo (\""+ 
  4701 					preDstParStr + "\"," + postNum + "," +
  4702 					QString ("%1,%2").arg(savePos.x()).arg(savePos.y())+ ")";
  4703 
  4704 				saveState (
  4705 					postSelStr,undoCom,
  4706 					preSelStr, redoCom,
  4707 					QString("Relink %1 to %2").arg(getName(bsel)).arg(getName(dst)) );
  4708 			} else
  4709 				if (lmosel->getDepth()==1)
  4710 				{
  4711 					// The select string might be different _after_ moving around.
  4712 					// Therefor reposition and then use string of old selection, too
  4713 					mapCenter->reposition();
  4714 
  4715 					QString ps=qpointfToString ( lmosel->getRelPos() );
  4716 					saveState(
  4717 						lmosel->getSelectString(), "moveRel "+qpointfToString(movingObj_orgRelPos), 
  4718 						preSelStr, "moveRel "+ps, 
  4719 						QString("Move %1 to relative position %2").arg(getName(lmosel)).arg(ps));
  4720 			
  4721 				}
  4722 			// Draw the original link, before selection was moved around
  4723 			mapCenter->reposition();
  4724 		}
  4725 		xelection.update();
  4726 		// Finally resize scene, if needed
  4727 		scene()->update();
  4728 		movingObj=NULL;		
  4729 
  4730 		// Just make sure, that actions are still ok,e.g. the move branch up/down buttons...
  4731 		updateActions();
  4732 	} else 
  4733 		// maybe we moved View: set old cursor
  4734 		setCursor (Qt::ArrowCursor);
  4735     
  4736 }
  4737 
  4738 void MapEditor::mouseDoubleClickEvent(QMouseEvent* e)
  4739 {
  4740 	if (isSelectBlocked() ) 
  4741 	{
  4742 		e->ignore();
  4743 		return;
  4744 	}
  4745 
  4746 	if (e->button() == Qt::LeftButton )
  4747 	{
  4748 		QPointF p = mapToScene(e->pos());
  4749 		LinkableMapObj *lmo=mapCenter->findMapObj(p, NULL);
  4750 		if (lmo) {	// MapObj was found
  4751 			// First select the MapObj than edit heading
  4752 			xelection.select(lmo);
  4753 			mainWindow->editHeading();
  4754 		}
  4755 	}
  4756 }
  4757 
  4758 void MapEditor::resizeEvent (QResizeEvent* e)
  4759 {
  4760 	QGraphicsView::resizeEvent( e );
  4761 }
  4762 
  4763 void MapEditor::dragEnterEvent(QDragEnterEvent *event)
  4764 {
  4765 	//for (unsigned int i=0;event->format(i);i++) // Debug mime type
  4766 	//	cerr << event->format(i) << endl;
  4767 
  4768 	if (event->mimeData()->hasImage())
  4769 		event->acceptProposedAction();
  4770 	else	
  4771 		if (event->mimeData()->hasUrls())
  4772 			event->acceptProposedAction();
  4773 }
  4774 
  4775 void MapEditor::dragMoveEvent(QDragMoveEvent *)
  4776 {
  4777 }
  4778 
  4779 void MapEditor::dragLeaveEvent(QDragLeaveEvent *event)
  4780 {
  4781 	event->accept();
  4782 }
  4783 
  4784 void MapEditor::dropEvent(QDropEvent *event)
  4785 {
  4786 	BranchObj *sel=xelection.getBranch();
  4787 	if (sel)
  4788 	{
  4789 		if (debug)
  4790 			foreach (QString format,event->mimeData()->formats()) 
  4791 				cout << "MapEditor: Dropped format: "<<format.ascii()<<endl;
  4792 
  4793 
  4794 		QList <QUrl> uris;
  4795 		if (event->mimeData()->hasImage()) 
  4796 		{
  4797 			 QVariant imageData = event->mimeData()->imageData();
  4798 			 addFloatImageInt (qvariant_cast<QPixmap>(imageData));
  4799 		} else
  4800 		if (event->mimeData()->hasUrls())
  4801 			uris=event->mimeData()->urls();
  4802 
  4803 		if (uris.count()>0)
  4804 		{
  4805 			QStringList files;
  4806 			QString s;
  4807 			QString heading;
  4808 			BranchObj *bo;
  4809 			for (int i=0; i<uris.count();i++)
  4810 			{
  4811 				// Workaround to avoid adding empty branches
  4812 				if (!uris.at(i).toString().isEmpty())
  4813 				{
  4814 					bo=sel->addBranch();
  4815 					if (bo)
  4816 					{
  4817 						s=uris.at(i).toLocalFile();
  4818 						if (!s.isEmpty()) 
  4819 						{
  4820 						   QString file = QDir::convertSeparators(s);
  4821 						   heading = QFileInfo(file).baseName();
  4822 						   files.append(file);
  4823 						   if (file.endsWith(".vym", false))
  4824 							   bo->setVymLink(file);
  4825 						   else
  4826 							   bo->setURL(uris.at(i).toString());
  4827 					   } else 
  4828 					   {
  4829 						   bo->setURL(uris.at(i).toString());
  4830 					   }
  4831 
  4832 					   if (!heading.isEmpty())
  4833 						   bo->setHeading(heading);
  4834 					   else
  4835 						   bo->setHeading(uris.at(i).toString());
  4836 					}
  4837 				}
  4838 			}
  4839 			mapCenter->reposition();
  4840 		}
  4841 	}	
  4842 	event->acceptProposedAction();
  4843 }
  4844 
  4845 void MapEditor::timerEvent(QTimerEvent *event)  //TODO animation
  4846 {
  4847     Q_UNUSED(event);
  4848 
  4849 	cout << "ME::timerEvent\n";
  4850 
  4851 	for (int i=0; i<animObjList.size(); ++i)
  4852 	{
  4853 		animObjList.at(i)->animate();
  4854 		((BranchObj*)animObjList.at(i))->move2RelPos (((BranchObj*)animObjList.at(i))->getRelPos() );
  4855 	}
  4856 	mapCenter->reposition();
  4857 }
  4858 
  4859 
  4860 void MapEditor::sendSelection()
  4861 {
  4862 	if (netstate!=Server) return;
  4863 	sendData (QString("select (\"%1\")").arg(xelection.getSelectString()) );
  4864 }
  4865 
  4866 void MapEditor::newServer()
  4867 {
  4868 	port=54321;
  4869 	sendCounter=0;
  4870     tcpServer = new QTcpServer(this);
  4871     if (!tcpServer->listen(QHostAddress::Any,port)) {
  4872         QMessageBox::critical(this, "vym server",
  4873                               QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
  4874         close();
  4875         return;
  4876     }
  4877 	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
  4878 	netstate=Server;
  4879 	cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
  4880 }
  4881 
  4882 void MapEditor::connectToServer()
  4883 {
  4884 	port=54321;
  4885 	server="salam.suse.de";
  4886 	server="localhost";
  4887 	clientSocket = new QTcpSocket (this);
  4888 	clientSocket->abort();
  4889     clientSocket->connectToHost(server ,port);
  4890 	connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
  4891     connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
  4892             this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
  4893 	netstate=Client;		
  4894 	cout<<"connected to "<<server.ascii()<<" port "<<port<<endl;
  4895 
  4896 	
  4897 }
  4898 
  4899 void MapEditor::newClient()
  4900 {
  4901     QTcpSocket *newClient = tcpServer->nextPendingConnection();
  4902     connect(newClient, SIGNAL(disconnected()),
  4903             newClient, SLOT(deleteLater()));
  4904 
  4905 	cout <<"ME::newClient  at "<<newClient->peerAddress().toString().ascii()<<endl;
  4906 
  4907 	clientList.append (newClient);
  4908 }
  4909 
  4910 
  4911 void MapEditor::sendData(const QString &s)
  4912 {
  4913 	if (clientList.size()==0) return;
  4914 
  4915 	// Create bytearray to send
  4916 	QByteArray block;
  4917     QDataStream out(&block, QIODevice::WriteOnly);
  4918     out.setVersion(QDataStream::Qt_4_0);
  4919 
  4920 	// Reserve some space for blocksize
  4921     out << (quint16)0;
  4922 
  4923 	// Write sendCounter
  4924     out << sendCounter++;
  4925 
  4926 	// Write data
  4927     out << s;
  4928 
  4929 	// Go back and write blocksize so far
  4930     out.device()->seek(0);
  4931     quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
  4932 	out << bs;
  4933 
  4934 	if (debug)
  4935 		cout << "ME::sendData  bs="<<bs<<"  counter="<<sendCounter<<"  s="<<s.ascii()<<endl;
  4936 
  4937 	for (int i=0; i<clientList.size(); ++i)
  4938 	{
  4939 		//cout << "Sending \""<<s.ascii()<<"\" to "<<clientList.at(i)->peerAddress().toString().ascii()<<endl;
  4940 		clientList.at(i)->write (block);
  4941 	}
  4942 }
  4943 
  4944 void MapEditor::readData ()
  4945 {
  4946 	while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
  4947 	{
  4948 		if (debug)
  4949 			cout <<"readData  bytesAvail="<<clientSocket->bytesAvailable();
  4950 		quint16 recCounter;
  4951 		quint16 blockSize;
  4952 
  4953 		QDataStream in(clientSocket);
  4954 		in.setVersion(QDataStream::Qt_4_0);
  4955 
  4956 		in >> blockSize;
  4957 		in >> recCounter;
  4958 		
  4959 		QString t;
  4960 		in >>t;
  4961 		if (debug)
  4962 			cout << "  t="<<t.ascii()<<endl;
  4963 		parseAtom (t);
  4964 	}
  4965 	return;
  4966 }
  4967 
  4968 void MapEditor::displayNetworkError(QAbstractSocket::SocketError socketError)
  4969 {
  4970     switch (socketError) {
  4971     case QAbstractSocket::RemoteHostClosedError:
  4972         break;
  4973     case QAbstractSocket::HostNotFoundError:
  4974         QMessageBox::information(this, __VYM_NAME " Network client",
  4975                                  "The host was not found. Please check the "
  4976                                     "host name and port settings.");
  4977         break;
  4978     case QAbstractSocket::ConnectionRefusedError:
  4979         QMessageBox::information(this, __VYM_NAME " Network client",
  4980                                  "The connection was refused by the peer. "
  4981                                     "Make sure the fortune server is running, "
  4982                                     "and check that the host name and port "
  4983                                     "settings are correct.");
  4984         break;
  4985     default:
  4986         QMessageBox::information(this, __VYM_NAME " Network client",
  4987                                  QString("The following error occurred: %1.")
  4988                                  .arg(clientSocket->errorString()));
  4989     }
  4990 }
  4991 
  4992 void MapEditor::autosave()
  4993 {
  4994 	// Disable autosave, while we have gone back in history
  4995 	int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
  4996 	if (redosAvail>0) return;
  4997 
  4998 
  4999 	if (mapUnsaved &&mapChanged && settings.value ("/mapeditor/autosave/use",true).toBool() )
  5000 		mainWindow->fileSave (this);
  5001 }
  5002 
  5003 
  5004 /*TODO not needed? void MapEditor::contentsDropEvent(QDropEvent *event) 
  5005 {
  5006 
  5007 		} else if (event->provides("application/x-moz-file-promise-url") && 
  5008 			 event->provides("application/x-moz-nativeimage")) 
  5009 		{
  5010 			// Contains url to the img src in unicode16
  5011 			QByteArray d = event->encodedData("application/x-moz-file-promise-url");
  5012 			QString url = QString((const QChar*)d.data(),d.size()/2);
  5013 			fetchImage(url);
  5014 			event->accept();
  5015 			update=true;
  5016 		} else if (event->provides ("text/uri-list"))
  5017 		{	// Uris provided e.g. by konqueror
  5018 			Q3UriDrag::decode (event,uris);
  5019 		} else if (event->provides ("_NETSCAPE_URL"))
  5020 		{	// Uris provided by Mozilla
  5021 		  QStringList l = QStringList::split("\n", event->encodedData("_NETSCAPE_URL"));
  5022 		  uris.append(l[0]);
  5023 		  heading = l[1];
  5024 		} else if (event->provides("text/html")) {
  5025 
  5026 		  // Handels text mime types
  5027 		  // Look like firefox allways handle text as unicode16 (2 bytes per char.)
  5028 		  QByteArray d = event->encodedData("text/html");
  5029 		  QString text;
  5030 		  if (isUnicode16(d)) 
  5031 		    text = QString((const QChar*)d.data(),d.size()/2);
  5032 		  else 
  5033 		    text = QString(d);
  5034 
  5035 		  textEditor->setText(text);
  5036 
  5037 		  event->accept();
  5038 		  update=true;
  5039 		} else if (event->provides("text/plain")) {
  5040 		  QByteArray d = event->encodedData("text/plain");
  5041 		  QString text;
  5042 		  if (isUnicode16(d))
  5043 		    text = QString((const QChar*)d.data(),d.size()/2);
  5044 		  else 
  5045 		    text = QString(d);
  5046 
  5047 		  textEditor->setText(text);
  5048 		  
  5049 		  event->accept();
  5050 		  update= true;
  5051 		}
  5052 
  5053 		*/
  5054 
  5055 
  5056 
  5057 bool isUnicode16(const QByteArray &d) 
  5058 {
  5059   // TODO: make more precise check for unicode 16.
  5060   // Guess unicode16 if any of second bytes are zero
  5061   unsigned int length = max(0,d.size()-2)/2;
  5062   for (unsigned int i = 0; i<length ; i++)
  5063     if (d.at(i*2+1)==0) return true;
  5064   return false;
  5065 }
  5066       
  5067 void MapEditor::addFloatImageInt (const QPixmap &img) 
  5068 {
  5069 	BranchObj *bo=xelection.getBranch();
  5070 	if (bo)
  5071   {
  5072 	FloatImageObj *fio=bo->addFloatImage();
  5073     fio->load(img);
  5074     fio->setOriginalFilename("No original filename (image added by dropevent)");	
  5075 	QString s=bo->getSelectString();
  5076 	saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",fio  );
  5077 	saveState (fio,"delete ()", bo,QString("paste(%1)").arg(curStep),"Pasting dropped image");
  5078     mapCenter->reposition();
  5079     scene()->update();
  5080   }
  5081 }
  5082 
  5083 /*
  5084 
  5085 void MapEditor::imageDataFetched(const QByteArray &a, Q3NetworkOperation * / *nop* /) 
  5086 {
  5087   if (!imageBuffer) imageBuffer = new QBuffer();
  5088   if (!imageBuffer->isOpen()) {
  5089     imageBuffer->open(QIODevice::WriteOnly | QIODevice::Append);
  5090   }
  5091   imageBuffer->at(imageBuffer->at()+imageBuffer->writeBlock(a));
  5092 }
  5093 
  5094 
  5095 void MapEditor::imageDataFinished(Q3NetworkOperation *nop) 
  5096 {
  5097 	if (nop->state()==Q3NetworkProtocol::StDone) {
  5098 		QPixmap img(imageBuffer->buffer());
  5099 		addFloatImageInt (img);
  5100 	}
  5101 
  5102 	if (imageBuffer) {
  5103 		imageBuffer->close();
  5104 		if (imageBuffer) {
  5105 			imageBuffer->close();
  5106 			delete imageBuffer;
  5107 			imageBuffer = 0;
  5108 		}
  5109 	}
  5110 }
  5111 
  5112 void MapEditor::fetchImage(const QString &url) 
  5113 {
  5114   if (urlOperator) {
  5115     urlOperator->stop();
  5116     disconnect(urlOperator);
  5117     delete urlOperator;
  5118   }
  5119   
  5120   urlOperator = new Q3UrlOperator(url);
  5121   connect(urlOperator, SIGNAL(finished(Q3NetworkOperation *)), 
  5122 	  this, SLOT(imageDataFinished(Q3NetworkOperation*)));
  5123 
  5124   connect(urlOperator, SIGNAL(data(const QByteArray &, Q3NetworkOperation *)),
  5125 	  this, SLOT(imageDataFetched(const QByteArray &, Q3NetworkOperation *)));
  5126   urlOperator->get();
  5127 }
  5128 */
  5129