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