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