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