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