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