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