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