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