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