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