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