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