Bugfix: Serious bug related to autosave fixed.
3 #include <q3filedialog.h>
10 #include "editxlinkdialog.h"
12 #include "exportxhtmldialog.h"
13 #include "extrainfodialog.h"
15 #include "linkablemapobj.h"
16 #include "mainwindow.h"
18 #include "texteditor.h"
19 #include "warningdialog.h"
20 #include "xml-freemind.h"
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;
32 extern FlagRowObj *standardFlagsDefault;
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;
44 extern Settings settings;
45 extern ImageIO imageIO;
47 extern QString vymName;
48 extern QString vymVersion;
50 extern QString iconPath;
51 extern QDir vymBaseDir;
52 extern QDir lastImageDir;
53 extern QDir lastFileDir;
55 int MapEditor::mapNum=0; // make instance
57 ///////////////////////////////////////////////////////////////////////
58 ///////////////////////////////////////////////////////////////////////
59 MapEditor::MapEditor( QWidget* parent) :
62 setObjectName ("MapEditor");
64 //cout << "Constructor ME "<<this<<endl;
68 mapScene= new QGraphicsScene(parent);
69 //mapScene= new QGraphicsScene(QRectF(0,0,width(),height()), parent);
70 mapScene->setBackgroundBrush (QBrush(Qt::white, Qt::SolidPattern));
73 model->setScene (mapScene);
74 model->setMapEditor (this);
80 defLinkColor=QColor (0,0,255);
81 defXLinkColor=QColor (180,180,180);
82 linkcolorhint=LinkableMapObj::DefaultColor;
83 linkstyle=LinkableMapObj::PolyParabel;
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 );
91 setFocusPolicy (Qt::StrongFocus);
100 xelection.setModel (model);
101 xelection.unselect();
104 defXLinkColor=QColor (230,230,230);
112 fileName=tr("unnamed");
115 stepsTotal=settings.readNumEntry("/mapeditor/stepsTotal",100);
116 undoSet.setEntry ("/history/stepsTotal",QString::number(stepsTotal));
117 mainWindow->updateHistory (undoSet);
119 // Initialize find routine
126 blockReposition=false;
127 blockSaveState=false;
131 // Create temporary files
138 setAcceptDrops (true);
143 autosaveTimer=new QTimer (this);
144 connect(autosaveTimer, SIGNAL(timeout()), this, SLOT(autosave()));
146 fileChangedTimer=new QTimer (this);
147 fileChangedTimer->start(3000);
148 connect(fileChangedTimer, SIGNAL(timeout()), this, SLOT(fileChanged()));
153 // Attributes //FIXME testing only...
156 attrTable= new AttributeTable();
158 ad=attrTable->addKey (k,StringList);
162 sl <<"val 1"<<"val 2"<< "val 3";
163 ad->setValue (QVariant (sl));
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");
170 ad=attrTable->addKey (k,FreeString);
173 //attrTable->addValue ("Key B","w1");
174 //attrTable->addValue ("Key B","w2");
176 k="C - UniqueString";
177 ad=attrTable->addKey (k,UniqueString);
180 //attrTable->addKey ("Key Prio");
181 //attrTable->addValue ("Key Prio","Prio 1");
182 //attrTable->addValue ("Key Prio","Prio 2");
186 MapEditor::~MapEditor()
188 //cout <<"Destructor MapEditor "<<mapName.toStdString()<<endl;
189 fileChangedTimer->stop();
192 // tmpMapDir is in tmpVymDir, so it gets removed automagically when vym closes
194 //removeDir(QDir(tmpMapDir));
198 VymModel* MapEditor::getModel()
203 QGraphicsScene * MapEditor::getScene()
208 MapEditor::State MapEditor::getState()
213 void MapEditor::setStateEditHeading(bool s)
217 if (state==Idle) state=EditHeading;
223 bool MapEditor::isRepositionBlocked()
225 return blockReposition;
228 void MapEditor::setSaveStateBlocked(bool b)
233 bool MapEditor::isSelectBlocked()
235 if (state==EditHeading)
241 QString MapEditor::getName (const LinkableMapObj *lmo)
244 if (!lmo) return QString("Error: NULL has no name!");
246 if ((typeid(*lmo) == typeid(BranchObj) ||
247 typeid(*lmo) == typeid(MapCenterObj)))
250 s=(((BranchObj*)lmo)->getHeading());
251 if (s=="") s="unnamed";
252 return QString("branch (%1)").arg(s);
254 if ((typeid(*lmo) == typeid(FloatImageObj) ))
255 return QString ("floatimage [%1]").arg(((FloatImageObj*)lmo)->getOriginalFilename());
256 return QString("Unknown type has no name!");
259 void MapEditor::makeTmpDirs()
261 // Create unique temporary directories
262 tmpMapDir = tmpVymDir+QString("/mapeditor-%1").arg(mapNum);
263 histPath = tmpMapDir+"/history";
268 QString MapEditor::saveToDir(const QString &tmpdir, const QString &prefix, bool writeflags, const QPointF &offset, LinkableMapObj *saveSel)
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
280 case LinkableMapObj::Line:
283 case LinkableMapObj::Parabel:
286 case LinkableMapObj::PolyLine:
290 ls="StylePolyParabel";
294 QString s="<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE vymmap>\n";
296 if (linkcolorhint==LinkableMapObj::HeadingColor)
297 colhint=attribut("linkColorHint","HeadingColor");
299 QString mapAttr=attribut("version",vymVersion);
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) ) +
311 s+=beginElement("vymmap",mapAttr);
314 // Find the used flags while traversing the tree
315 standardFlagsDefault->resetUsedCounter();
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();
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);
327 if ( typeid(*saveSel) == typeid(BranchObj) )
329 s+=((BranchObj*)saveSel)->saveToDir(tmpdir,prefix,offset);
332 if ( typeid(*saveSel) == typeid(FloatImageObj) )
334 s+=((FloatImageObj*)saveSel)->saveToDir(tmpdir,prefix);
338 // Save local settings
339 s+=settings.getDataXML (destPath);
342 if (!xelection.isEmpty() && !saveSel )
343 s+=valueElement("select",xelection.getSelectString());
346 s+=endElement("vymmap");
349 standardFlagsDefault->saveToDir (tmpdir+"/flags/","",writeflags);
353 QString MapEditor::getHistoryDir()
355 QString histName(QString("history-%1").arg(curStep));
356 return (tmpMapDir+"/"+histName);
359 void MapEditor::saveState(const SaveMode &savemode, const QString &undoSelection, const QString &undoCom, const QString &redoSelection, const QString &redoCom, const QString &comment, LinkableMapObj *saveSel)
361 sendData(redoCom); //FIXME testing
366 if (blockSaveState) return;
368 if (debug) cout << "ME::saveState() for "<<qPrintable (mapName)<<endl;
370 // Find out current undo directory
371 if (undosAvail<stepsTotal) undosAvail++;
373 if (curStep>stepsTotal) curStep=1;
375 QString backupXML="";
376 QString histDir=getHistoryDir();
377 QString bakMapPath=histDir+"/map.xml";
379 // Create histDir if not available
382 makeSubDirs (histDir);
384 // Save depending on how much needs to be saved
386 backupXML=saveToDir (histDir,mapName+"-",false, QPointF (),saveSel);
388 QString undoCommand="";
389 if (savemode==UndoCommand)
393 else if (savemode==PartOfMap )
396 undoCommand.replace ("PATH",bakMapPath);
399 if (!backupXML.isEmpty())
400 // Write XML Data to disk
401 saveStringToDisk (bakMapPath,backupXML);
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.
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);
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;
437 mainWindow->updateHistory (undoSet);
443 void MapEditor::saveStateChangingPart(LinkableMapObj *undoSel, LinkableMapObj* redoSel, const QString &rc, const QString &comment)
445 // save the selected part of the map, Undo will replace part of map
446 QString undoSelection="";
448 undoSelection=model->getSelectString(undoSel);
450 qWarning ("MapEditor::saveStateChangingPart no undoSel given!");
451 QString redoSelection="";
453 redoSelection=model->getSelectString(undoSel);
455 qWarning ("MapEditor::saveStateChangingPart no redoSel given!");
458 saveState (PartOfMap,
459 undoSelection, "addMapReplace (\"PATH\")",
465 void MapEditor::saveStateRemovingPart(LinkableMapObj *redoSel, const QString &comment)
469 qWarning ("MapEditor::saveStateRemovingPart no redoSel given!");
472 QString undoSelection=model->getSelectString (redoSel->getParObj());
473 QString redoSelection=model->getSelectString(redoSel);
474 if (typeid(*redoSel) == typeid(BranchObj) )
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 ()",
486 void MapEditor::saveState(LinkableMapObj *undoSel, const QString &uc, LinkableMapObj *redoSel, const QString &rc, const QString &comment)
488 // "Normal" savestate: save commands, selections and comment
489 // so just save commands for undo and redo
490 // and use current selection
492 QString redoSelection="";
493 if (redoSel) redoSelection=model->getSelectString(redoSel);
494 QString undoSelection="";
495 if (undoSel) undoSelection=model->getSelectString(undoSel);
497 saveState (UndoCommand,
504 void MapEditor::saveState(const QString &undoSel, const QString &uc, const QString &redoSel, const QString &rc, const QString &comment)
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,
516 void MapEditor::saveState(const QString &uc, const QString &rc, const QString &comment)
518 // "Normal" savestate applied to model (no selection needed):
519 // save commands and comment
520 saveState (UndoCommand,
528 void MapEditor::parseAtom(const QString &atom)
530 BranchObj *selb=xelection.getBranch();
536 // Split string s into command and parameters
537 parser.parseAtom (atom);
538 QString com=parser.getCommand();
541 /////////////////////////////////////////////////////////////////////
542 if (com=="addBranch")
544 if (xelection.isEmpty())
546 parser.setError (Aborted,"Nothing selected");
549 parser.setError (Aborted,"Type of selection is not a branch");
554 if (parser.checkParCount(pl))
556 if (parser.parCount()==0)
560 n=parser.parInt (ok,0);
561 if (ok ) addNewBranch (n);
565 /////////////////////////////////////////////////////////////////////
566 } else if (com=="addBranchBefore")
568 if (xelection.isEmpty())
570 parser.setError (Aborted,"Nothing selected");
573 parser.setError (Aborted,"Type of selection is not a branch");
576 if (parser.parCount()==0)
578 addNewBranchBefore ();
581 /////////////////////////////////////////////////////////////////////
582 } else if (com==QString("addMapCenter"))
584 if (parser.checkParCount(2))
586 x=parser.parDouble (ok,0);
589 y=parser.parDouble (ok,1);
590 if (ok) model->addMapCenter (QPointF(x,y));
593 /////////////////////////////////////////////////////////////////////
594 } else if (com==QString("addMapReplace"))
596 if (xelection.isEmpty())
598 parser.setError (Aborted,"Nothing selected");
601 parser.setError (Aborted,"Type of selection is not a branch");
602 } else if (parser.checkParCount(1))
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);
609 /////////////////////////////////////////////////////////////////////
610 } else if (com==QString("addMapInsert"))
612 if (xelection.isEmpty())
614 parser.setError (Aborted,"Nothing selected");
617 parser.setError (Aborted,"Type of selection is not a branch");
620 if (parser.checkParCount(2))
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);
628 /////////////////////////////////////////////////////////////////////
629 } else if (com=="clearFlags")
631 if (xelection.isEmpty() )
633 parser.setError (Aborted,"Nothing selected");
636 parser.setError (Aborted,"Type of selection is not a branch");
637 } else if (parser.checkParCount(0))
639 selb->clearStandardFlags();
640 selb->updateFlagsToolbar();
642 /////////////////////////////////////////////////////////////////////
643 } else if (com=="colorBranch")
645 if (xelection.isEmpty())
647 parser.setError (Aborted,"Nothing selected");
650 parser.setError (Aborted,"Type of selection is not a branch");
651 } else if (parser.checkParCount(1))
653 QColor c=parser.parColor (ok,0);
654 if (ok) colorBranch (c);
656 /////////////////////////////////////////////////////////////////////
657 } else if (com=="colorSubtree")
659 if (xelection.isEmpty())
661 parser.setError (Aborted,"Nothing selected");
664 parser.setError (Aborted,"Type of selection is not a branch");
665 } else if (parser.checkParCount(1))
667 QColor c=parser.parColor (ok,0);
668 if (ok) colorSubtree (c);
670 /////////////////////////////////////////////////////////////////////
671 } else if (com=="copy")
673 if (xelection.isEmpty())
675 parser.setError (Aborted,"Nothing selected");
678 parser.setError (Aborted,"Type of selection is not a branch");
679 } else if (parser.checkParCount(0))
681 //FIXME missing action for copy
683 /////////////////////////////////////////////////////////////////////
684 } else if (com=="cut")
686 if (xelection.isEmpty())
688 parser.setError (Aborted,"Nothing selected");
689 } else if ( xelection.type()!=Selection::Branch &&
690 xelection.type()!=Selection::MapCenter &&
691 xelection.type()!=Selection::FloatImage )
693 parser.setError (Aborted,"Type of selection is not a branch or floatimage");
694 } else if (parser.checkParCount(0))
698 /////////////////////////////////////////////////////////////////////
699 } else if (com=="delete")
701 if (xelection.isEmpty())
703 parser.setError (Aborted,"Nothing selected");
705 /*else if (xelection.type() != Selection::Branch && xelection.type() != Selection::FloatImage )
707 parser.setError (Aborted,"Type of selection is wrong.");
710 else if (parser.checkParCount(0))
714 /////////////////////////////////////////////////////////////////////
715 } else if (com=="deleteKeepChilds")
717 if (xelection.isEmpty())
719 parser.setError (Aborted,"Nothing selected");
722 parser.setError (Aborted,"Type of selection is not a branch");
723 } else if (parser.checkParCount(0))
727 /////////////////////////////////////////////////////////////////////
728 } else if (com=="deleteChilds")
730 if (xelection.isEmpty())
732 parser.setError (Aborted,"Nothing selected");
735 parser.setError (Aborted,"Type of selection is not a branch");
736 } else if (parser.checkParCount(0))
740 /////////////////////////////////////////////////////////////////////
741 } else if (com=="exportASCII")
745 if (parser.parCount()>=1)
746 // Hey, we even have a filename
747 fname=parser.parString(ok,0);
750 parser.setError (Aborted,"Could not read filename");
753 exportASCII (fname,false);
755 /////////////////////////////////////////////////////////////////////
756 } else if (com=="exportImage")
760 if (parser.parCount()>=2)
761 // Hey, we even have a filename
762 fname=parser.parString(ok,0);
765 parser.setError (Aborted,"Could not read filename");
768 QString format="PNG";
769 if (parser.parCount()>=2)
771 format=parser.parString(ok,1);
773 exportImage (fname,false,format);
775 /////////////////////////////////////////////////////////////////////
776 } else if (com=="exportXHTML")
780 if (parser.parCount()>=2)
781 // Hey, we even have a filename
782 fname=parser.parString(ok,1);
785 parser.setError (Aborted,"Could not read filename");
788 exportXHTML (fname,false);
790 /////////////////////////////////////////////////////////////////////
791 } else if (com=="exportXML")
795 if (parser.parCount()>=2)
796 // Hey, we even have a filename
797 fname=parser.parString(ok,1);
800 parser.setError (Aborted,"Could not read filename");
803 exportXML (fname,false);
805 /////////////////////////////////////////////////////////////////////
806 } else if (com=="importDir")
808 if (xelection.isEmpty())
810 parser.setError (Aborted,"Nothing selected");
813 parser.setError (Aborted,"Type of selection is not a branch");
814 } else if (parser.checkParCount(1))
816 s=parser.parString(ok,0);
817 if (ok) importDirInt(s);
819 /////////////////////////////////////////////////////////////////////
820 } else if (com=="linkTo")
822 if (xelection.isEmpty())
824 parser.setError (Aborted,"Nothing selected");
827 if (parser.checkParCount(4))
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);
836 if (typeid(*dst) == typeid(BranchObj) )
838 // Get number in parent
839 n=parser.parInt (ok,1);
842 selb->linkTo ((BranchObj*)(dst),n);
845 } else if (typeid(*dst) == typeid(MapCenterObj) )
847 selb->linkTo ((BranchObj*)(dst),-1);
848 // Get coordinates of mainbranch
849 x=parser.parDouble(ok,2);
852 y=parser.parDouble(ok,3);
862 } else if ( xelection.type() == Selection::FloatImage)
864 if (parser.checkParCount(1))
866 // 0 selectstring of parent
867 s=parser.parString(ok,0);
868 LinkableMapObj *dst=model->findObjBySelect (s);
871 if (typeid(*dst) == typeid(BranchObj) ||
872 typeid(*dst) == typeid(MapCenterObj))
873 linkTo (model->getSelectString(dst));
875 parser.setError (Aborted,"Destination is not a branch");
878 parser.setError (Aborted,"Type of selection is not a floatimage or branch");
879 /////////////////////////////////////////////////////////////////////
880 } else if (com=="loadImage")
882 if (xelection.isEmpty())
884 parser.setError (Aborted,"Nothing selected");
887 parser.setError (Aborted,"Type of selection is not a branch");
888 } else if (parser.checkParCount(1))
890 s=parser.parString(ok,0);
891 if (ok) loadFloatImageInt (s);
893 /////////////////////////////////////////////////////////////////////
894 } else if (com=="moveBranchUp")
896 if (xelection.isEmpty() )
898 parser.setError (Aborted,"Nothing selected");
901 parser.setError (Aborted,"Type of selection is not a branch");
902 } else if (parser.checkParCount(0))
906 /////////////////////////////////////////////////////////////////////
907 } else if (com=="moveBranchDown")
909 if (xelection.isEmpty() )
911 parser.setError (Aborted,"Nothing selected");
914 parser.setError (Aborted,"Type of selection is not a branch");
915 } else if (parser.checkParCount(0))
919 /////////////////////////////////////////////////////////////////////
920 } else if (com=="move")
922 if (xelection.isEmpty() )
924 parser.setError (Aborted,"Nothing selected");
925 } else if ( xelection.type()!=Selection::Branch &&
926 xelection.type()!=Selection::MapCenter &&
927 xelection.type()!=Selection::FloatImage )
929 parser.setError (Aborted,"Type of selection is not a branch or floatimage");
930 } else if (parser.checkParCount(2))
932 x=parser.parDouble (ok,0);
935 y=parser.parDouble (ok,1);
939 /////////////////////////////////////////////////////////////////////
940 } else if (com=="moveRel")
942 if (xelection.isEmpty() )
944 parser.setError (Aborted,"Nothing selected");
945 } else if ( xelection.type()!=Selection::Branch &&
946 xelection.type()!=Selection::MapCenter &&
947 xelection.type()!=Selection::FloatImage )
949 parser.setError (Aborted,"Type of selection is not a branch or floatimage");
950 } else if (parser.checkParCount(2))
952 x=parser.parDouble (ok,0);
955 y=parser.parDouble (ok,1);
956 if (ok) moveRel (x,y);
959 /////////////////////////////////////////////////////////////////////
960 } else if (com=="nop")
962 /////////////////////////////////////////////////////////////////////
963 } else if (com=="paste")
965 if (xelection.isEmpty() )
967 parser.setError (Aborted,"Nothing selected");
970 parser.setError (Aborted,"Type of selection is not a branch");
971 } else if (parser.checkParCount(1))
973 n=parser.parInt (ok,0);
974 if (ok) pasteNoSave(n);
976 /////////////////////////////////////////////////////////////////////
977 } else if (com=="qa")
979 if (xelection.isEmpty() )
981 parser.setError (Aborted,"Nothing selected");
984 parser.setError (Aborted,"Type of selection is not a branch");
985 } else if (parser.checkParCount(4))
988 c=parser.parString (ok,0);
991 parser.setError (Aborted,"No comment given");
994 s=parser.parString (ok,1);
997 parser.setError (Aborted,"First parameter is not a string");
1000 t=parser.parString (ok,2);
1003 parser.setError (Aborted,"Condition is not a string");
1006 u=parser.parString (ok,3);
1009 parser.setError (Aborted,"Third parameter is not a string");
1014 parser.setError (Aborted,"Unknown type: "+s);
1019 parser.setError (Aborted,"Unknown operator: "+t);
1024 parser.setError (Aborted,"Type of selection is not a branch");
1027 if (selb->getHeading() == u)
1029 cout << "PASSED: " << qPrintable (c) << endl;
1032 cout << "FAILED: " << qPrintable (c) << endl;
1042 /////////////////////////////////////////////////////////////////////
1043 } else if (com=="saveImage")
1045 FloatImageObj *fio=xelection.getFloatImage();
1048 parser.setError (Aborted,"Type of selection is not an image");
1049 } else if (parser.checkParCount(2))
1051 s=parser.parString(ok,0);
1054 t=parser.parString(ok,1);
1055 if (ok) saveFloatImageInt (fio,t,s);
1058 /////////////////////////////////////////////////////////////////////
1059 } else if (com=="scroll")
1061 if (xelection.isEmpty() )
1063 parser.setError (Aborted,"Nothing selected");
1066 parser.setError (Aborted,"Type of selection is not a branch");
1067 } else if (parser.checkParCount(0))
1069 if (!scrollBranch (selb))
1070 parser.setError (Aborted,"Could not scroll branch");
1072 /////////////////////////////////////////////////////////////////////
1073 } else if (com=="select")
1075 if (parser.checkParCount(1))
1077 s=parser.parString(ok,0);
1080 /////////////////////////////////////////////////////////////////////
1081 } else if (com=="selectLastBranch")
1083 if (xelection.isEmpty() )
1085 parser.setError (Aborted,"Nothing selected");
1088 parser.setError (Aborted,"Type of selection is not a branch");
1089 } else if (parser.checkParCount(0))
1091 BranchObj *bo=selb->getLastBranch();
1093 parser.setError (Aborted,"Could not select last branch");
1097 /////////////////////////////////////////////////////////////////////
1098 } else if (com=="selectLastImage")
1100 if (xelection.isEmpty() )
1102 parser.setError (Aborted,"Nothing selected");
1105 parser.setError (Aborted,"Type of selection is not a branch");
1106 } else if (parser.checkParCount(0))
1108 FloatImageObj *fio=selb->getLastFloatImage();
1110 parser.setError (Aborted,"Could not select last image");
1114 /////////////////////////////////////////////////////////////////////
1115 } else if (com=="selectLatestAdded")
1117 if (latestSelection.isEmpty() )
1119 parser.setError (Aborted,"No latest added object");
1122 if (!select (latestSelection))
1123 parser.setError (Aborted,"Could not select latest added object "+latestSelection);
1125 /////////////////////////////////////////////////////////////////////
1126 } else if (com=="setFrameType")
1128 if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
1130 parser.setError (Aborted,"Type of selection does not allow setting frame type");
1132 else if (parser.checkParCount(1))
1134 s=parser.parString(ok,0);
1135 if (ok) setFrameType (s);
1137 /////////////////////////////////////////////////////////////////////
1138 } else if (com=="setFramePenColor")
1140 if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
1142 parser.setError (Aborted,"Type of selection does not allow setting of pen color");
1144 else if (parser.checkParCount(1))
1146 QColor c=parser.parColor(ok,0);
1147 if (ok) setFramePenColor (c);
1149 /////////////////////////////////////////////////////////////////////
1150 } else if (com=="setFrameBrushColor")
1152 if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
1154 parser.setError (Aborted,"Type of selection does not allow setting brush color");
1156 else if (parser.checkParCount(1))
1158 QColor c=parser.parColor(ok,0);
1159 if (ok) setFrameBrushColor (c);
1161 /////////////////////////////////////////////////////////////////////
1162 } else if (com=="setFramePadding")
1164 if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
1166 parser.setError (Aborted,"Type of selection does not allow setting frame padding");
1168 else if (parser.checkParCount(1))
1170 n=parser.parInt(ok,0);
1171 if (ok) setFramePadding(n);
1173 /////////////////////////////////////////////////////////////////////
1174 } else if (com=="setFrameBorderWidth")
1176 if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
1178 parser.setError (Aborted,"Type of selection does not allow setting frame border width");
1180 else if (parser.checkParCount(1))
1182 n=parser.parInt(ok,0);
1183 if (ok) setFrameBorderWidth (n);
1185 /////////////////////////////////////////////////////////////////////
1186 } else if (com=="setMapAuthor")
1188 if (parser.checkParCount(1))
1190 s=parser.parString(ok,0);
1191 if (ok) setMapAuthor (s);
1193 /////////////////////////////////////////////////////////////////////
1194 } else if (com=="setMapComment")
1196 if (parser.checkParCount(1))
1198 s=parser.parString(ok,0);
1199 if (ok) setMapComment(s);
1201 /////////////////////////////////////////////////////////////////////
1202 } else if (com=="setMapBackgroundColor")
1204 if (xelection.isEmpty() )
1206 parser.setError (Aborted,"Nothing selected");
1207 } else if (! xelection.getBranch() )
1209 parser.setError (Aborted,"Type of selection is not a branch");
1210 } else if (parser.checkParCount(1))
1212 QColor c=parser.parColor (ok,0);
1213 if (ok) setMapBackgroundColor (c);
1215 /////////////////////////////////////////////////////////////////////
1216 } else if (com=="setMapDefLinkColor")
1218 if (xelection.isEmpty() )
1220 parser.setError (Aborted,"Nothing selected");
1223 parser.setError (Aborted,"Type of selection is not a branch");
1224 } else if (parser.checkParCount(1))
1226 QColor c=parser.parColor (ok,0);
1227 if (ok) setMapDefLinkColor (c);
1229 /////////////////////////////////////////////////////////////////////
1230 } else if (com=="setMapLinkStyle")
1232 if (parser.checkParCount(1))
1234 s=parser.parString (ok,0);
1235 if (ok) setMapLinkStyle(s);
1237 /////////////////////////////////////////////////////////////////////
1238 } else if (com=="setHeading")
1240 if (xelection.isEmpty() )
1242 parser.setError (Aborted,"Nothing selected");
1245 parser.setError (Aborted,"Type of selection is not a branch");
1246 } else if (parser.checkParCount(1))
1248 s=parser.parString (ok,0);
1252 /////////////////////////////////////////////////////////////////////
1253 } else if (com=="setHideExport")
1255 if (xelection.isEmpty() )
1257 parser.setError (Aborted,"Nothing selected");
1258 } else if (xelection.type()!=Selection::Branch && xelection.type() != Selection::MapCenter &&xelection.type()!=Selection::FloatImage)
1260 parser.setError (Aborted,"Type of selection is not a branch or floatimage");
1261 } else if (parser.checkParCount(1))
1263 b=parser.parBool(ok,0);
1264 if (ok) setHideExport (b);
1266 /////////////////////////////////////////////////////////////////////
1267 } else if (com=="setIncludeImagesHorizontally")
1269 if (xelection.isEmpty() )
1271 parser.setError (Aborted,"Nothing selected");
1274 parser.setError (Aborted,"Type of selection is not a branch");
1275 } else if (parser.checkParCount(1))
1277 b=parser.parBool(ok,0);
1278 if (ok) setIncludeImagesHor(b);
1280 /////////////////////////////////////////////////////////////////////
1281 } else if (com=="setIncludeImagesVertically")
1283 if (xelection.isEmpty() )
1285 parser.setError (Aborted,"Nothing selected");
1288 parser.setError (Aborted,"Type of selection is not a branch");
1289 } else if (parser.checkParCount(1))
1291 b=parser.parBool(ok,0);
1292 if (ok) setIncludeImagesVer(b);
1294 /////////////////////////////////////////////////////////////////////
1295 } else if (com=="setHideLinkUnselected")
1297 if (xelection.isEmpty() )
1299 parser.setError (Aborted,"Nothing selected");
1300 } else if ( xelection.type()!=Selection::Branch && xelection.type()!= Selection::MapCenter && xelection.type()!=Selection::FloatImage)
1302 parser.setError (Aborted,"Type of selection does not allow hiding the link");
1303 } else if (parser.checkParCount(1))
1305 b=parser.parBool(ok,0);
1306 if (ok) setHideLinkUnselected(b);
1308 /////////////////////////////////////////////////////////////////////
1309 } else if (com=="setSelectionColor")
1311 if (parser.checkParCount(1))
1313 QColor c=parser.parColor (ok,0);
1314 if (ok) setSelectionColorInt (c);
1316 /////////////////////////////////////////////////////////////////////
1317 } else if (com=="setURL")
1319 if (xelection.isEmpty() )
1321 parser.setError (Aborted,"Nothing selected");
1324 parser.setError (Aborted,"Type of selection is not a branch");
1325 } else if (parser.checkParCount(1))
1327 s=parser.parString (ok,0);
1330 /////////////////////////////////////////////////////////////////////
1331 } else if (com=="setVymLink")
1333 if (xelection.isEmpty() )
1335 parser.setError (Aborted,"Nothing selected");
1338 parser.setError (Aborted,"Type of selection is not a branch");
1339 } else if (parser.checkParCount(1))
1341 s=parser.parString (ok,0);
1342 if (ok) setVymLinkInt(s);
1345 /////////////////////////////////////////////////////////////////////
1346 else if (com=="setFlag")
1348 if (xelection.isEmpty() )
1350 parser.setError (Aborted,"Nothing selected");
1353 parser.setError (Aborted,"Type of selection is not a branch");
1354 } else if (parser.checkParCount(1))
1356 s=parser.parString(ok,0);
1359 selb->activateStandardFlag(s);
1360 selb->updateFlagsToolbar();
1363 /////////////////////////////////////////////////////////////////////
1364 } else if (com=="setFrameType")
1366 if (xelection.isEmpty() )
1368 parser.setError (Aborted,"Nothing selected");
1371 parser.setError (Aborted,"Type of selection is not a branch");
1372 } else if (parser.checkParCount(1))
1374 s=parser.parString(ok,0);
1378 /////////////////////////////////////////////////////////////////////
1379 } else if (com=="sortChildren")
1381 if (xelection.isEmpty() )
1383 parser.setError (Aborted,"Nothing selected");
1386 parser.setError (Aborted,"Type of selection is not a branch");
1387 } else if (parser.checkParCount(0))
1391 /////////////////////////////////////////////////////////////////////
1392 } else if (com=="toggleFlag")
1394 if (xelection.isEmpty() )
1396 parser.setError (Aborted,"Nothing selected");
1399 parser.setError (Aborted,"Type of selection is not a branch");
1400 } else if (parser.checkParCount(1))
1402 s=parser.parString(ok,0);
1405 selb->toggleStandardFlag(s);
1406 selb->updateFlagsToolbar();
1409 /////////////////////////////////////////////////////////////////////
1410 } else if (com=="unscroll")
1412 if (xelection.isEmpty() )
1414 parser.setError (Aborted,"Nothing selected");
1417 parser.setError (Aborted,"Type of selection is not a branch");
1418 } else if (parser.checkParCount(0))
1420 if (!unscrollBranch (selb))
1421 parser.setError (Aborted,"Could not unscroll branch");
1423 /////////////////////////////////////////////////////////////////////
1424 } else if (com=="unscrollChilds")
1426 if (xelection.isEmpty() )
1428 parser.setError (Aborted,"Nothing selected");
1431 parser.setError (Aborted,"Type of selection is not a branch");
1432 } else if (parser.checkParCount(0))
1436 /////////////////////////////////////////////////////////////////////
1437 } else if (com=="unsetFlag")
1439 if (xelection.isEmpty() )
1441 parser.setError (Aborted,"Nothing selected");
1444 parser.setError (Aborted,"Type of selection is not a branch");
1445 } else if (parser.checkParCount(1))
1447 s=parser.parString(ok,0);
1450 selb->deactivateStandardFlag(s);
1451 selb->updateFlagsToolbar();
1455 parser.setError (Aborted,"Unknown command");
1458 if (parser.errorLevel()==NoError)
1460 // setChanged(); FIXME should not be called e.g. for export?!
1461 model->reposition();
1465 // TODO Error handling
1466 qWarning("MapEditor::parseAtom: Error!");
1467 qWarning(parser.errorMessage());
1471 void MapEditor::runScript (QString script)
1473 parser.setScript (script);
1475 while (parser.next() )
1476 parseAtom(parser.getAtom());
1479 bool MapEditor::isDefault()
1484 bool MapEditor::hasChanged()
1489 void MapEditor::setChanged()
1492 autosaveTimer->start(settings.value("/mapeditor/autosave/ms/",300000).toInt());
1500 void MapEditor::closeMap()
1502 // Unselect before disabling the toolbar actions
1503 if (!xelection.isEmpty() ) xelection.unselect();
1508 // close(); FIXME needed?
1511 void MapEditor::setFilePath(QString fpath, QString destname)
1513 if (fpath.isEmpty() || fpath=="")
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
1524 // If fpath is not an absolute path, complete it
1525 filePath=QDir(fpath).absPath();
1526 fileDir=filePath.left (1+filePath.findRev ("/"));
1528 // Set short name, too. Search from behind:
1529 int i=fileName.findRev("/");
1530 if (i>=0) fileName=fileName.remove (0,i+1);
1532 // Forget the .vym (or .xml) for name of map
1533 mapName=fileName.left(fileName.findRev(".",-1,true) );
1537 void MapEditor::setFilePath(QString fpath)
1539 setFilePath (fpath,fpath);
1542 QString MapEditor::getFilePath()
1547 QString MapEditor::getFileName()
1552 QString MapEditor::getMapName()
1557 QString MapEditor::getDestPath()
1562 ErrorCode MapEditor::load (QString fname, const LoadMode &lmode, const FileType &ftype)
1564 ErrorCode err=success;
1566 parseBaseHandler *handler;
1570 case VymMap: handler=new parseVYMHandler; break;
1571 case FreemindMap : handler=new parseFreemindHandler; break;
1573 QMessageBox::critical( 0, tr( "Critical Parse Error" ),
1574 "Unknown FileType in MapEditor::load()");
1578 // Save original zip state, important for inserting complete maps
1579 bool zipped_org=zipped;
1584 model->setMapEditor(this);
1585 // (map state is set later at end of load...)
1588 BranchObj *bo=xelection.getBranch();
1589 if (!bo) return aborted;
1590 if (lmode==ImportAdd)
1591 saveStateChangingPart(
1594 QString("addMapInsert (%1)").arg(fname),
1595 QString("Add map %1 to %2").arg(fname).arg(getName(bo)));
1597 saveStateChangingPart(
1600 QString("addMapReplace(%1)").arg(fname),
1601 QString("Add map %1 to %2").arg(fname).arg(getName(bo)));
1605 // Create temporary directory for packing
1607 QString tmpZipDir=makeTmpDir (ok,"vym-pack");
1610 QMessageBox::critical( 0, tr( "Critical Load Error" ),
1611 tr("Couldn't create temporary directory before load\n"));
1615 // Try to unzip file
1616 err=unzipDir (tmpZipDir,fname);
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() )
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)
1639 // Only one entry, take this one
1640 xmlfile=tmpZipDir + "/"+flist.first();
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...");
1651 if (flist.isEmpty() )
1653 QMessageBox::critical( 0, tr( "Critical Load Error" ),
1654 tr("Couldn't find a map (*.xml) in .vym archive.\n"));
1657 } //file doesn't exist
1659 xmlfile=mfile.name();
1662 QFile file( xmlfile);
1664 // I am paranoid: file should exist anyway
1665 // according to check in mainwindow.
1666 if (!file.exists() )
1668 QMessageBox::critical( 0, tr( "Critical Parse Error" ),
1669 tr(QString("Couldn't open map %1").arg(file.name())));
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);
1683 // We need to set the tmpDir in order to load files with rel. path
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;
1698 model->reposition(); // FIXME reposition the view instead...
1705 autosaveTimer->stop();
1708 // Reset timestamp to check for later updates of file
1709 fileChangedTime=QFileInfo (destPath).lastModified();
1712 QMessageBox::critical( 0, tr( "Critical Parse Error" ),
1713 tr( handler->errorProtocol() ) );
1715 // Still return "success": the map maybe at least
1716 // partially read by the parser
1721 removeDir (QDir(tmpZipDir));
1723 // Restore original zip state
1731 ErrorCode MapEditor::save (const SaveMode &savemode)
1734 QString mapFileName;
1735 QString safeFilePath;
1737 ErrorCode err=success;
1741 mapFileName=mapName+".xml";
1743 // use name given by user, even if he chooses .doc
1744 mapFileName=fileName;
1746 // Look, if we should zip the data:
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,
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"));
1763 case QMessageBox::Yes:
1764 // save compressed (default file format)
1767 case QMessageBox::No:
1768 // save uncompressed
1771 case QMessageBox::Cancel:
1778 // First backup existing file, we
1779 // don't want to add to old zip archives
1783 if ( settings.value ("/mapeditor/writeBackupFile").toBool())
1785 QString backupFileName(destPath + "~");
1786 QFile backupFile(backupFileName);
1787 if (backupFile.exists() && !backupFile.remove())
1789 QMessageBox::warning(0, tr("Save Error"),
1790 tr("%1\ncould not be removed before saving").arg(backupFileName));
1792 else if (!f.rename(backupFileName))
1794 QMessageBox::warning(0, tr("Save Error"),
1795 tr("%1\ncould not be renamed before saving").arg(destPath));
1802 // Create temporary directory for packing
1804 tmpZipDir=makeTmpDir (ok,"vym-zip");
1807 QMessageBox::critical( 0, tr( "Critical Load Error" ),
1808 tr("Couldn't create temporary directory before save\n"));
1812 // cout <<"ME::save filePath="<<filePath.toStdString()<<endl;
1813 safeFilePath=filePath;
1814 setFilePath (tmpZipDir+"/"+ mapName+ ".xml", safeFilePath);
1817 // Create mapName and fileDir
1818 makeSubDirs (fileDir);
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;
1830 if (savemode==CompleteMap || xelection.isEmpty())
1832 // Save complete map
1833 saveFile=saveToDir (fileDir,mapName+"-",true,QPointF(),NULL);
1836 autosaveTimer->stop();
1841 if (xelection.type()==Selection::FloatImage)
1844 saveFile=saveToDir (fileDir,mapName+"-",true,QPointF(),xelection.getBranch());
1845 // TODO take care of multiselections
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))
1854 QMessageBox::critical (0,"Critical error in MapEditor::save",QString("could not sage %1").arg(fileDir+mapFileName));
1860 if (err==success) err=zipDir (tmpZipDir,destPath);
1863 removeDir (QDir(tmpZipDir));
1865 // Restore original filepath outside of tmp zip dir
1866 setFilePath (safeFilePath);
1870 fileChangedTime=QFileInfo (destPath).lastModified();
1875 void MapEditor::print()
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());
1886 QRectF totalBBox=model->getTotalBBox();
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
1893 if (totalBBox.width()>totalBBox.height())
1894 // recommend landscape
1895 printer->setOrientation (QPrinter::Landscape);
1897 // recommend portrait
1898 printer->setOrientation (QPrinter::Portrait);
1900 if ( printer->setup(this) )
1901 // returns false, if printing is canceled
1903 QPainter pp(printer);
1905 pp.setRenderHint(QPainter::Antialiasing,true);
1907 // Don't print the visualisation of selection
1908 xelection.unselect();
1910 QRectF mapRect=totalBBox;
1911 QGraphicsRectItem *frame=NULL;
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);
1924 double paperAspect = (double)printer->width() / (double)printer->height();
1925 double mapAspect = (double)mapRect.width() / (double)mapRect.height();
1927 if (mapAspect>=paperAspect)
1929 // Fit horizontally to paper width
1930 //pp.setViewport(0,0, printer->width(),(int)(printer->width()/mapAspect) );
1931 viewBottom=(int)(printer->width()/mapAspect);
1934 // Fit vertically to paper height
1935 //pp.setViewport(0,0,(int)(printer->height()*mapAspect),printer->height());
1936 viewBottom=printer->height();
1941 // Print footer below map
1943 font.setPointSize(10);
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));
1951 QRectF (0,0,printer->width(),printer->height()-15),
1952 QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height())
1955 // Viewport has paper dimension
1956 if (frame) delete (frame);
1958 // Restore selection
1959 xelection.reselect();
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());
1968 void MapEditor::setAntiAlias (bool b)
1970 setRenderHint(QPainter::Antialiasing,b);
1973 void MapEditor::setSmoothPixmap(bool b)
1975 setRenderHint(QPainter::SmoothPixmapTransform,b);
1978 QPixmap MapEditor::getPixmap()
1980 QRectF mapRect=model->getTotalBBox();
1981 QPixmap pix((int)mapRect.width()+2,(int)mapRect.height()+1);
1984 pp.setRenderHints(renderHints());
1986 // Don't print the visualisation of selection
1987 xelection.unselect();
1989 mapScene->render ( &pp,
1990 QRectF(0,0,mapRect.width()+1,mapRect.height()+1),
1991 QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
1993 // Restore selection
1994 xelection.reselect();
1999 void MapEditor::setHideTmpMode (HideTmpMode mode)
2002 model->setHideTmp (hidemode);
2003 model->reposition();
2007 HideTmpMode MapEditor::getHideTmpMode()
2012 void MapEditor::setExportMode (bool b)
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);
2019 setHideTmpMode (HideNone);
2022 void MapEditor::exportASCII(QString fname,bool askName)
2025 ex.setModel (model);
2027 ex.setFile (mapName+".txt");
2033 //ex.addFilter ("TXT (*.txt)");
2034 ex.setDir(lastImageDir);
2035 //ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
2040 setExportMode(true);
2042 setExportMode(false);
2046 void MapEditor::exportImage(QString fname, bool askName, QString format)
2050 fname=mapName+".png";
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() );
2064 fl=fd->selectedFiles();
2066 format=imageIO.getType(fd->selectedFilter());
2070 setExportMode (true);
2071 QPixmap pix (getPixmap());
2072 pix.save(fname, format);
2073 setExportMode (false);
2076 void MapEditor::exportOOPresentation(const QString &fn, const QString &cf)
2080 ex.setModel (model);
2081 if (ex.setConfigFile(cf))
2083 setExportMode (true);
2084 ex.exportPresentation();
2085 setExportMode (false);
2089 void MapEditor::exportXHTML (const QString &dir, bool askForName)
2091 ExportXHTMLDialog dia(this);
2092 dia.setFilePath (filePath );
2093 dia.setMapName (mapName );
2095 if (dir!="") dia.setDir (dir);
2101 if (dia.exec()!=QDialog::Accepted)
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)
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");
2118 if (warn.exec()!=QDialog::Accepted) ok=false;
2125 exportXML (dia.getDir(),false );
2126 dia.doExport(mapName );
2127 //if (dia.hasChanged()) setChanged();
2131 void MapEditor::exportXML(QString dir, bool askForName)
2135 dir=browseDirectory(this,tr("Export XML to directory"));
2136 if (dir =="" && !reallyWriteDirectory(dir) )
2140 // Hide stuff during export, if settings want this
2141 setExportMode (true);
2143 // Create subdirectories
2146 // write to directory
2147 QString saveFile=saveToDir (dir,mapName+"-",true,model->getTotalBBox().topLeft() ,NULL);
2150 file.setName ( dir + "/"+mapName+".xml");
2151 if ( !file.open( QIODevice::WriteOnly ) )
2153 // This should neverever happen
2154 QMessageBox::critical (0,tr("Critical Export Error"),tr("MapEditor::exportXML couldn't open %1").arg(file.name()));
2158 // Write it finally, and write in UTF8, no matter what
2159 QTextStream ts( &file );
2160 ts.setEncoding (QTextStream::UnicodeUTF8);
2164 // Now write image, too
2165 exportImage (dir+"/images/"+mapName+".png",false,"PNG");
2167 setExportMode (false);
2170 void MapEditor::clear()
2172 //cout << "ME::clear() "<<mapName.toStdString()<<endl;
2174 autosaveTimer->stop();
2178 void MapEditor::copy()
2180 LinkableMapObj *sel=xelection.single();
2183 if (redosAvail == 0)
2186 QString s=model->getSelectString(sel);
2187 saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",sel );
2188 curClipboard=curStep;
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 );
2196 clipboardEmpty=false;
2201 void MapEditor::redo()
2203 // Can we undo at all?
2204 if (redosAvail<1) return;
2206 bool blockSaveStateOrg=blockSaveState;
2207 blockSaveState=true;
2211 if (undosAvail<stepsTotal) undosAvail++;
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");
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));
2227 // Find out current undo directory
2228 QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
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;
2245 // select object before redo
2246 if (!redoSelection.isEmpty())
2247 select (redoSelection);
2250 parseAtom (redoCommand);
2251 model->reposition();
2253 blockSaveState=blockSaveStateOrg;
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);
2260 mainWindow->updateHistory (undoSet);
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;
2274 bool MapEditor::isRedoAvailable()
2276 if (undoSet.readNumEntry("/history/redosAvail",0)>0)
2282 void MapEditor::undo()
2284 // Can we undo at all?
2285 if (undosAvail<1) return;
2287 mainWindow->statusMessage (tr("Autosave disabled during undo."));
2289 bool blockSaveStateOrg=blockSaveState;
2290 blockSaveState=true;
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");
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));
2305 // Find out current undo directory
2306 QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
2308 // select object before undo
2309 if (!undoSelection.isEmpty())
2310 select (undoSelection);
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;
2326 parseAtom (undoCommand);
2327 model->reposition();
2331 if (curStep<1) curStep=stepsTotal;
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;
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);
2349 mainWindow->updateHistory (undoSet);
2352 ensureSelectionVisible();
2355 bool MapEditor::isUndoAvailable()
2357 if (undoSet.readNumEntry("/history/undosAvail",0)>0)
2363 void MapEditor::gotoHistoryStep (int i)
2365 // Restore variables
2366 int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
2367 int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
2369 if (i<0) i=undosAvail+redosAvail;
2371 // Clicking above current step makes us undo things
2374 for (int j=0; j<undosAvail-i; j++) undo();
2377 // Clicking below current step makes us redo things
2379 for (int j=undosAvail; j<i; j++)
2381 if (debug) cout << "ME::gotoHistoryStep redo "<<j<<"/"<<undosAvail<<" i="<<i<<endl;
2385 // And ignore clicking the current row ;-)
2388 void MapEditor::addMapReplaceInt(const QString &undoSel, const QString &path)
2390 QString pathDir=path.left(path.findRev("/"));
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())
2408 handler.setLoadMode (NewMap);
2412 handler.setLoadMode (ImportReplace);
2414 blockReposition=true;
2415 bool ok = reader.parse( source );
2416 blockReposition=false;
2419 // This should never ever happen
2420 QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
2421 handler.errorProtocol());
2424 QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
2427 void MapEditor::addMapInsertInt (const QString &path, int pos)
2429 BranchObj *sel=xelection.getBranch();
2432 QString pathDir=path.left(path.findRev("/"));
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;
2452 // This should never ever happen
2453 QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
2454 handler.errorProtocol());
2456 if (sel->getDepth()>0)
2457 sel->getLastBranch()->linkTo (sel,pos);
2459 QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
2463 void MapEditor::pasteNoSave(const int &n)
2465 bool old=blockSaveState;
2466 blockSaveState=true;
2467 bool zippedOrg=zipped;
2468 if (redosAvail > 0 || n!=0)
2470 // Use the "historical" buffer
2471 QString bakMapName(QString("history-%1").arg(n));
2472 QString bakMapDir(tmpMapDir +"/"+bakMapName);
2473 load (bakMapDir+"/"+clipboardFile,ImportAdd, VymMap);
2475 // Use the global buffer
2476 load (clipboardDir+"/"+clipboardFile,ImportAdd, VymMap);
2481 void MapEditor::paste()
2483 BranchObj *sel=xelection.getBranch();
2486 saveStateChangingPart(
2489 QString ("paste (%1)").arg(curClipboard),
2490 QString("Paste to %1").arg( getName(sel))
2493 model->reposition();
2497 void MapEditor::cut()
2499 LinkableMapObj *sel=xelection.single();
2500 if ( sel && (xelection.type() == Selection::Branch ||
2501 xelection.type()==Selection::MapCenter ||
2502 xelection.type()==Selection::FloatImage))
2504 /* No savestate! savestate is called in cutNoSave
2505 saveStateChangingPart(
2509 QString("Cut %1").arg(getName(sel ))
2514 model->reposition();
2518 void MapEditor::move(const double &x, const double &y)
2520 LinkableMapObj *sel=xelection.single();
2523 QPointF ap(sel->getAbsPos());
2527 QString ps=qpointfToString(ap);
2528 QString s=xelection.getSelectString();
2531 s, "move "+qpointfToString(to),
2532 QString("Move %1 to %2").arg(getName(sel)).arg(ps));
2534 model->reposition();
2540 void MapEditor::moveRel (const double &x, const double &y)
2542 LinkableMapObj *sel=xelection.single();
2545 QPointF rp(sel->getRelPos());
2549 QString ps=qpointfToString (sel->getRelPos());
2550 QString s=model->getSelectString(sel);
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();
2563 void MapEditor::moveBranchUp()
2565 BranchObj* bo=xelection.getBranch();
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();
2576 ensureSelectionVisible();
2580 void MapEditor::moveBranchDown()
2582 BranchObj* bo=xelection.getBranch();
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();
2593 ensureSelectionVisible();
2597 void MapEditor::sortChildren()
2599 BranchObj* bo=xelection.getBranch();
2602 if(bo->countBranches()>1)
2604 saveStateChangingPart(bo,bo, "sortChildren ()",QString("Sort children of %1").arg(getName(bo)));
2606 model->reposition();
2607 ensureSelectionVisible();
2612 void MapEditor::linkTo(const QString &dstString)
2614 FloatImageObj *fio=xelection.getFloatImage();
2617 BranchObj *dst=(BranchObj*)(model->findObjBySelect(dstString));
2618 if (dst && (typeid(*dst)==typeid (BranchObj) ||
2619 typeid(*dst)==typeid (MapCenterObj)))
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();
2631 xelection.select(fio);
2633 model->getSelectString(fio),
2634 QString("linkTo (\"%1\")").arg(fioPreParentSelectString),
2636 QString ("linkTo (\"%1\")").arg(dstString),
2637 QString ("Link floatimage to %1").arg(getName(dst)));
2642 QString MapEditor::getHeading(bool &ok, QPoint &p)
2644 BranchObj *bo=xelection.getBranch();
2648 p=mapFromScene(bo->getAbsPos());
2649 return bo->getHeading();
2655 void MapEditor::setHeading(const QString &s)
2657 BranchObj *sel=xelection.getBranch();
2662 "setHeading (\""+sel->getHeading()+"\")",
2664 "setHeading (\""+s+"\")",
2665 QString("Set heading of %1 to \"%2\"").arg(getName(sel)).arg(s) );
2666 sel->setHeading(s );
2667 model->reposition();
2669 ensureSelectionVisible();
2673 void MapEditor::setHeadingInt(const QString &s)
2675 BranchObj *bo=xelection.getBranch();
2679 model->reposition();
2681 ensureSelectionVisible();
2685 void MapEditor::setVymLinkInt (const QString &s)
2687 // Internal function, no saveState needed
2688 BranchObj *bo=xelection.getBranch();
2692 model->reposition();
2695 ensureSelectionVisible();
2699 BranchObj* MapEditor::addMapCenter ()
2701 MapCenterObj *mco= model->addMapCenter(contextMenuPos);
2702 xelection.select (mco);
2704 ensureSelectionVisible();
2709 QString ("addMapCenter (%1,%2)").arg (contextMenuPos.x()).arg(contextMenuPos.y()),
2710 QString ("Adding MapCenter to (%1,%2").arg (contextMenuPos.x()).arg(contextMenuPos.y())
2715 BranchObj* MapEditor::addNewBranchInt(int num)
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();
2728 // save scroll state. If scrolled, automatically select
2729 // new branch in order to tmp unscroll parent...
2730 newbo=bo->addBranch();
2735 bo=(BranchObj*)bo->getParObj();
2736 if (bo) newbo=bo->insertBranch(num);
2740 bo=(BranchObj*)bo->getParObj();
2741 if (bo) newbo=bo->insertBranch(num);
2743 if (!newbo) return NULL;
2748 BranchObj* MapEditor::addNewBranch(int pos)
2750 // Different meaning than num in addNewBranchInt!
2754 BranchObj *bo = xelection.getBranch();
2755 BranchObj *newbo=NULL;
2759 setCursor (Qt::ArrowCursor);
2761 newbo=addNewBranchInt (pos-2);
2769 QString ("addBranch (%1)").arg(pos),
2770 QString ("Add new branch to %1").arg(getName(bo)));
2772 model->reposition();
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));
2788 BranchObj* MapEditor::addNewBranchBefore()
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
2795 QPointF p=bo->getRelPos();
2798 BranchObj *parbo=(BranchObj*)(bo->getParObj());
2800 // add below selection
2801 newbo=parbo->insertBranch(bo->getNum()+1);
2804 newbo->move2RelPos (p);
2806 // Move selection to new branch
2807 bo->linkTo (newbo,-1);
2809 saveState (newbo, "deleteKeepChilds ()", newbo, "addBranchBefore ()",
2810 QString ("Add branch before %1").arg(getName(bo)));
2812 model->reposition();
2816 latestSelection=xelection.getSelectString();
2820 void MapEditor::deleteSelection()
2822 BranchObj *bo = xelection.getBranch();
2823 if (bo && xelection.type()==Selection::MapCenter)
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)));
2830 bo=model->removeMapCenter ((MapCenterObj*)bo);
2833 xelection.select (bo);
2834 ensureSelectionVisible();
2837 model->reposition();
2840 if (bo && xelection.type()==Selection::Branch)
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();
2853 FloatImageObj *fio=xelection.getFloatImage();
2856 BranchObj* par=(BranchObj*)fio->getParObj();
2857 saveStateChangingPart(
2861 QString("Delete %1").arg(getName(fio))
2863 xelection.unselect();
2864 par->removeFloatImage(fio);
2865 xelection.select (par);
2866 model->reposition();
2868 ensureSelectionVisible();
2873 LinkableMapObj* MapEditor::getSelection()
2875 return xelection.single();
2878 BranchObj* MapEditor::getSelectedBranch()
2880 return xelection.getBranch();
2883 FloatImageObj* MapEditor::getSelectedFloatImage()
2885 return xelection.getFloatImage();
2888 void MapEditor::unselect()
2890 xelection.unselect();
2893 void MapEditor::reselect()
2895 xelection.reselect();
2898 bool MapEditor::select (const QString &s)
2900 if (xelection.select(s))
2903 ensureSelectionVisible();
2910 bool MapEditor::select (LinkableMapObj *lmo)
2912 if (xelection.select(lmo))
2915 ensureSelectionVisible();
2922 QString MapEditor::getSelectString()
2924 return xelection.getSelectString();
2927 void MapEditor::selectInt (LinkableMapObj *lmo)
2929 if (lmo && xelection.single()!= lmo && isSelectBlocked()==false )
2931 xelection.select(lmo);
2937 void MapEditor::selectNextBranchInt()
2939 // Increase number of branch
2940 LinkableMapObj *sel=xelection.single();
2943 QString s=xelection.getSelectString();
2949 part=s.section(",",-1);
2951 num=part.right(part.length() - 3);
2953 s=s.left (s.length() -num.length());
2956 num=QString ("%1").arg(num.toUInt()+1);
2960 // Try to select this one
2961 if (select (s)) return;
2963 // We have no direct successor,
2964 // try to increase the parental number in order to
2965 // find a successor with same depth
2967 int d=xelection.single()->getDepth();
2972 while (!found && d>0)
2974 s=s.section (",",0,d-1);
2975 // replace substring of current depth in s with "1"
2976 part=s.section(",",-1);
2978 num=part.right(part.length() - 3);
2982 // increase number of parent
2983 num=QString ("%1").arg(num.toUInt()+1);
2984 s=s.section (",",0,d-2) + ","+ typ+num;
2987 // Special case, look at orientation
2988 if (xelection.single()->getOrientation()==LinkableMapObj::RightOfCenter)
2989 num=QString ("%1").arg(num.toUInt()+1);
2991 num=QString ("%1").arg(num.toUInt()-1);
2996 // pad to oldDepth, select the first branch for each depth
2997 for (i=d;i<oldDepth;i++)
3002 if ( xelection.getBranch()->countBranches()>0)
3010 // try to select the freshly built string
3018 void MapEditor::selectPrevBranchInt()
3020 // Decrease number of branch
3021 BranchObj *bo=xelection.getBranch();
3024 QString s=xelection.getSelectString();
3030 part=s.section(",",-1);
3032 num=part.right(part.length() - 3);
3034 s=s.left (s.length() -num.length());
3036 int n=num.toInt()-1;
3039 num=QString ("%1").arg(n);
3042 // Try to select this one
3043 if (n>=0 && select (s)) return;
3045 // We have no direct precessor,
3046 // try to decrease the parental number in order to
3047 // find a precessor with same depth
3049 int d=xelection.single()->getDepth();
3054 while (!found && d>0)
3056 s=s.section (",",0,d-1);
3057 // replace substring of current depth in s with "1"
3058 part=s.section(",",-1);
3060 num=part.right(part.length() - 3);
3064 // decrease number of parent
3065 num=QString ("%1").arg(num.toInt()-1);
3066 s=s.section (",",0,d-2) + ","+ typ+num;
3069 // Special case, look at orientation
3070 if (xelection.single()->getOrientation()==LinkableMapObj::RightOfCenter)
3071 num=QString ("%1").arg(num.toInt()-1);
3073 num=QString ("%1").arg(num.toInt()+1);
3078 // pad to oldDepth, select the last branch for each depth
3079 for (i=d;i<oldDepth;i++)
3083 if ( xelection.getBranch()->countBranches()>0)
3084 s+=",bo:"+ QString ("%1").arg( xelection.getBranch()->countBranches()-1 );
3091 // try to select the freshly built string
3099 void MapEditor::selectUpperBranch()
3101 if (isSelectBlocked() ) return;
3103 BranchObj *bo=xelection.getBranch();
3104 if (bo && xelection.type()==Selection::Branch)
3106 if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
3107 selectPrevBranchInt();
3109 if (bo->getDepth()==1)
3110 selectNextBranchInt();
3112 selectPrevBranchInt();
3116 void MapEditor::selectLowerBranch()
3118 if (isSelectBlocked() ) return;
3120 BranchObj *bo=xelection.getBranch();
3121 if (bo && xelection.type()==Selection::Branch)
3123 if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
3124 selectNextBranchInt();
3126 if (bo->getDepth()==1)
3127 selectPrevBranchInt();
3129 selectNextBranchInt();
3134 void MapEditor::selectLeftBranch()
3136 if (isSelectBlocked() ) return;
3140 LinkableMapObj *sel=xelection.single();
3143 if (xelection.type()== Selection::MapCenter)
3145 par=xelection.getBranch();
3146 bo=par->getLastSelectedBranch();
3149 // Workaround for reselecting on left and right side
3150 if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
3151 bo=par->getLastBranch();
3154 bo=par->getLastBranch();
3155 xelection.select(bo);
3157 ensureSelectionVisible();
3163 par=(BranchObj*)(sel->getParObj());
3164 if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
3166 if (xelection.type() == Selection::Branch ||
3167 xelection.type() == Selection::FloatImage)
3169 xelection.select(par);
3171 ensureSelectionVisible();
3176 if (xelection.type() == Selection::Branch )
3178 bo=xelection.getBranch()->getLastSelectedBranch();
3181 xelection.select(bo);
3183 ensureSelectionVisible();
3192 void MapEditor::selectRightBranch()
3194 if (isSelectBlocked() ) return;
3198 LinkableMapObj *sel=xelection.single();
3201 if (xelection.type()==Selection::MapCenter)
3203 par=xelection.getBranch();
3204 bo=par->getLastSelectedBranch();
3207 // Workaround for reselecting on left and right side
3208 if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
3209 bo=par->getFirstBranch();
3212 xelection.select(bo);
3214 ensureSelectionVisible();
3220 par=(BranchObj*)(xelection.single()->getParObj());
3221 if (xelection.single()->getOrientation()==LinkableMapObj::LeftOfCenter)
3223 if (xelection.type() == Selection::Branch ||
3224 xelection.type() == Selection::FloatImage)
3226 xelection.select(par);
3228 ensureSelectionVisible();
3233 if (xelection.type() == Selection::Branch)
3235 bo=xelection.getBranch()->getLastSelectedBranch();
3238 xelection.select(bo);
3240 ensureSelectionVisible();
3249 void MapEditor::selectFirstBranch()
3251 BranchObj *bo1=xelection.getBranch();
3256 par=(BranchObj*)(bo1->getParObj());
3258 bo2=par->getFirstBranch();
3260 xelection.select(bo2);
3262 ensureSelectionVisible();
3268 void MapEditor::selectLastBranch()
3270 BranchObj *bo1=xelection.getBranch();
3275 par=(BranchObj*)(bo1->getParObj());
3277 bo2=par->getLastBranch();
3280 xelection.select(bo2);
3282 ensureSelectionVisible();
3288 void MapEditor::selectMapBackgroundImage ()
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);
3301 if ( fd->exec() == QDialog::Accepted )
3303 // TODO selectMapBackgroundImg in QT4 use: lastImageDir=fd->directory();
3304 lastImageDir=QDir (fd->dirPath());
3305 setMapBackgroundImage (fd->selectedFile());
3309 void MapEditor::setMapBackgroundImage (const QString &fn) //FIXME missing savestate
3311 QColor oldcol=mapScene->backgroundBrush().color();
3315 QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
3317 QString ("setMapBackgroundImage (%1)").arg(col.name()),
3318 QString("Set background color of map to %1").arg(col.name()));
3321 brush.setTextureImage (QPixmap (fn));
3322 mapScene->setBackgroundBrush(brush);
3325 void MapEditor::selectMapBackgroundColor()
3327 QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), this );
3328 if ( !col.isValid() ) return;
3329 setMapBackgroundColor( col );
3333 void MapEditor::setMapBackgroundColor(QColor col)
3335 QColor oldcol=mapScene->backgroundBrush().color();
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);
3343 QColor MapEditor::getMapBackgroundColor()
3345 return mapScene->backgroundBrush().color();
3348 QColor MapEditor::getCurrentHeadingColor()
3350 BranchObj *bo=xelection.getBranch();
3351 if (bo) return bo->getColor();
3353 QMessageBox::warning(0,tr("Warning"),tr("Can't get color of heading,\nthere's no branch selected"));
3357 void MapEditor::colorBranch (QColor c)
3359 BranchObj *bo=xelection.getBranch();
3364 QString ("colorBranch (\"%1\")").arg(bo->getColor().name()),
3366 QString ("colorBranch (\"%1\")").arg(c.name()),
3367 QString("Set color of %1 to %2").arg(getName(bo)).arg(c.name())
3369 bo->setColor(c); // color branch
3373 void MapEditor::colorSubtree (QColor c)
3375 BranchObj *bo=xelection.getBranch();
3378 saveStateChangingPart(
3381 QString ("colorSubtree (\"%1\")").arg(c.name()),
3382 QString ("Set color of %1 and childs to %2").arg(getName(bo)).arg(c.name())
3384 bo->setColorSubtree (c); // color links, color childs
3389 void MapEditor::toggleStandardFlag(QString f)
3391 BranchObj *bo=xelection.getBranch();
3395 if (bo->isSetStandardFlag(f))
3407 QString("%1 (\"%2\")").arg(u).arg(f),
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());
3417 BranchObj* MapEditor::findText (QString s, bool cs)
3419 QTextDocument::FindFlags flags=0;
3420 if (cs) flags=QTextDocument::FindCaseSensitively;
3423 { // Nothing found or new find process
3425 // nothing found, start again
3427 itFind=model->first();
3429 bool searching=true;
3430 bool foundNote=false;
3431 while (searching && !EOFind)
3435 // Searching in Note
3436 if (itFind->getNote().contains(s,cs))
3438 if (xelection.single()!=itFind)
3440 xelection.select(itFind);
3441 ensureSelectionVisible();
3443 if (textEditor->findText(s,flags))
3449 // Searching in Heading
3450 if (searching && itFind->getHeading().contains (s,cs) )
3452 xelection.select(itFind);
3453 ensureSelectionVisible();
3459 itFind=model->next(itFind);
3460 if (!itFind) EOFind=true;
3462 //cout <<"still searching... "<<qPrintable( itFind->getHeading())<<endl;
3465 return xelection.getBranch();
3470 void MapEditor::findReset()
3471 { // Necessary if text to find changes during a find process
3475 void MapEditor::setURL(const QString &url)
3477 BranchObj *bo=xelection.getBranch();
3480 QString oldurl=bo->getURL();
3484 QString ("setURL (\"%1\")").arg(oldurl),
3486 QString ("setURL (\"%1\")").arg(url),
3487 QString ("set URL of %1 to %2").arg(getName(bo)).arg(url)
3490 model->reposition();
3492 ensureSelectionVisible();
3496 void MapEditor::editURL()
3498 BranchObj *bo=xelection.getBranch();
3502 QString text = QInputDialog::getText(
3503 "VYM", tr("Enter URL:"), QLineEdit::Normal,
3504 bo->getURL(), &ok, this );
3506 // user entered something and pressed OK
3511 void MapEditor::editLocalURL()
3513 BranchObj *bo=xelection.getBranch();
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() );
3530 if ( fd->exec() == QDialog::Accepted )
3532 lastFileDir=QDir (fd->directory().path());
3533 setURL (fd->selectedFile() );
3538 QString MapEditor::getURL()
3540 BranchObj *bo=xelection.getBranch();
3542 return bo->getURL();
3547 QStringList MapEditor::getURLs()
3550 BranchObj *bo=xelection.getBranch();
3556 if (!bo->getURL().isEmpty()) urls.append( bo->getURL());
3564 void MapEditor::editHeading2URL()
3566 BranchObj *bo=xelection.getBranch();
3568 setURL (bo->getHeading());
3571 void MapEditor::editBugzilla2URL()
3573 BranchObj *bo=xelection.getBranch();
3576 QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
3581 void MapEditor::editFATE2URL()
3583 BranchObj *bo=xelection.getBranch();
3586 QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
3589 "setURL (\""+bo->getURL()+"\")",
3591 "setURL (\""+url+"\")",
3592 QString("Use heading of %1 as link to FATE").arg(getName(bo))
3599 void MapEditor::editVymLink()
3601 BranchObj *bo=xelection.getBranch();
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() );
3615 if ( fd->exec() == QDialog::Accepted )
3617 lastFileDir=QDir (fd->directory().path());
3620 "setVymLink (\""+bo->getVymLink()+"\")",
3622 "setVymLink (\""+fd->selectedFile()+"\")",
3623 QString("Set vymlink of %1 to %2").arg(getName(bo)).arg(fd->selectedFile())
3625 setVymLinkInt (fd->selectedFile() );
3630 void MapEditor::deleteVymLink()
3632 BranchObj *bo=xelection.getBranch();
3637 "setVymLink (\""+bo->getVymLink()+"\")",
3639 "setVymLink (\"\")",
3640 QString("Unset vymlink of %1").arg(getName(bo))
3642 bo->setVymLink ("" );
3644 model->reposition();
3649 void MapEditor::setHideExport(bool b)
3651 BranchObj *bo=xelection.getBranch();
3654 bo->setHideInExport (b);
3655 QString u= b ? "false" : "true";
3656 QString r=!b ? "false" : "true";
3660 QString ("setHideExport (%1)").arg(u),
3662 QString ("setHideExport (%1)").arg(r),
3663 QString ("Set HideExport flag of %1 to %2").arg(getName(bo)).arg (r)
3666 model->reposition();
3672 void MapEditor::toggleHideExport()
3674 BranchObj *bo=xelection.getBranch();
3676 setHideExport ( !bo->hideInExport() );
3679 QString MapEditor::getVymLink()
3681 BranchObj *bo=xelection.getBranch();
3683 return bo->getVymLink();
3689 QStringList MapEditor::getVymLinks()
3692 BranchObj *bo=xelection.getBranch();
3698 if (!bo->getVymLink().isEmpty()) links.append( bo->getVymLink());
3706 void MapEditor::deleteKeepChilds()
3708 BranchObj *bo=xelection.getBranch();
3712 par=(BranchObj*)(bo->getParObj());
3714 // Don't use this on mapcenter
3717 // Check if we have childs at all to keep
3718 if (bo->countBranches()==0)
3724 QPointF p=bo->getRelPos();
3725 saveStateChangingPart(
3728 "deleteKeepChilds ()",
3729 QString("Remove %1 and keep its childs").arg(getName(bo))
3732 QString sel=model->getSelectString(bo);
3734 par->removeBranchHere(bo);
3735 model->reposition();
3737 xelection.getBranch()->move2RelPos (p);
3738 model->reposition();
3742 void MapEditor::deleteChilds()
3744 BranchObj *bo=xelection.getBranch();
3747 saveStateChangingPart(
3751 QString( "Remove childs of branch %1").arg(getName(bo))
3754 model->reposition();
3758 void MapEditor::editMapInfo()
3760 ExtraInfoDialog dia;
3761 dia.setMapName (getFileName() );
3762 dia.setAuthor (model->getAuthor() );
3763 dia.setComment(model->getComment() );
3767 stats+=tr("%1 items on map\n","Info about map").arg (mapScene->items().size(),6);
3777 if (!bo->getNote().isEmpty() ) n++;
3778 f+= bo->countFloatImages();
3780 xl+=bo->countXLinks();
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);
3789 // Finally show dialog
3790 if (dia.exec() == QDialog::Accepted)
3792 setMapAuthor (dia.getAuthor() );
3793 setMapComment (dia.getComment() );
3797 void MapEditor::ensureSelectionVisible()
3799 LinkableMapObj *lmo=xelection.single();
3800 if (lmo) ensureVisible (lmo->getBBox() );
3804 void MapEditor::updateSelection()
3806 // Tell selection to update geometries
3810 void MapEditor::updateActions()
3812 // Tell mainwindow to update states of actions
3813 mainWindow->updateActions();
3814 // TODO maybe don't update if blockReposition is set
3817 void MapEditor::updateNoteFlag()
3820 BranchObj *bo=xelection.getBranch();
3823 bo->updateNoteFlag();
3824 mainWindow->updateActions();
3828 void MapEditor::setMapAuthor (const QString &s)
3831 QString ("setMapAuthor (\"%1\")").arg(model->getAuthor()),
3832 QString ("setMapAuthor (\"%1\")").arg(s),
3833 QString ("Set author of map to \"%1\"").arg(s)
3835 model->setAuthor (s);
3838 void MapEditor::setMapComment (const QString &s)
3841 QString ("setMapComment (\"%1\")").arg(model->getComment()),
3842 QString ("setMapComment (\"%1\")").arg(s),
3843 QString ("Set comment of map")
3845 model->setComment (s);
3848 void MapEditor::setMapLinkStyle (const QString & s)
3851 if (linkstyle==LinkableMapObj::Line)
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";
3861 QString("setMapLinkStyle (\"%1\")").arg(s),
3862 QString("setMapLinkStyle (\"%1\")").arg(snow),
3863 QString("Set map link style (\"%1\")").arg(s)
3867 linkstyle=LinkableMapObj::Line;
3868 else if (s=="StyleParabel")
3869 linkstyle=LinkableMapObj::Parabel;
3870 else if (s=="StylePolyLine")
3871 linkstyle=LinkableMapObj::PolyLine;
3873 linkstyle=LinkableMapObj::PolyParabel;
3880 bo->setLinkStyle(bo->getDefLinkStyle());
3883 model->reposition();
3886 LinkableMapObj::Style MapEditor::getMapLinkStyle ()
3891 void MapEditor::setMapDefLinkColor(QColor c)
3904 void MapEditor::setMapLinkColorHintInt()
3906 // called from setMapLinkColorHint(lch) or at end of parse
3916 void MapEditor::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
3919 setMapLinkColorHintInt();
3922 void MapEditor::toggleMapLinkColorHint()
3924 if (linkcolorhint==LinkableMapObj::HeadingColor)
3925 linkcolorhint=LinkableMapObj::DefaultColor;
3927 linkcolorhint=LinkableMapObj::HeadingColor;
3937 LinkableMapObj::ColorHint MapEditor::getMapLinkColorHint()
3939 return linkcolorhint;
3942 QColor MapEditor::getMapDefLinkColor()
3944 return defLinkColor;
3947 void MapEditor::setMapDefXLinkColor(QColor col)
3952 QColor MapEditor::getMapDefXLinkColor()
3954 return defXLinkColor;
3957 void MapEditor::setMapDefXLinkWidth (int w)
3962 int MapEditor::getMapDefXLinkWidth()
3964 return defXLinkWidth;
3967 void MapEditor::selectMapLinkColor()
3969 QColor col = QColorDialog::getColor( defLinkColor, this );
3970 if ( !col.isValid() ) return;
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())
3976 setMapDefLinkColor( col );
3979 void MapEditor::selectMapSelectionColor()
3981 QColor col = QColorDialog::getColor( defLinkColor, this );
3982 setSelectionColor (col);
3985 void MapEditor::setSelectionColorInt (QColor col)
3987 if ( !col.isValid() ) return;
3988 xelection.setColor (col);
3991 void MapEditor::setSelectionColor(QColor col)
3993 if ( !col.isValid() ) return;
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())
3999 setSelectionColorInt (col);
4002 QColor MapEditor::getSelectionColor()
4004 return xelection.getColor();
4007 bool MapEditor::scrollBranch(BranchObj *bo)
4011 if (bo->isScrolled()) return false;
4012 if (bo->countBranches()==0) return false;
4013 if (bo->getDepth()==0) return false;
4019 QString ("%1 ()").arg(u),
4021 QString ("%1 ()").arg(r),
4022 QString ("%1 %2").arg(r).arg(getName(bo))
4032 bool MapEditor::unscrollBranch(BranchObj *bo)
4036 if (!bo->isScrolled()) return false;
4037 if (bo->countBranches()==0) return false;
4038 if (bo->getDepth()==0) return false;
4044 QString ("%1 ()").arg(u),
4046 QString ("%1 ()").arg(r),
4047 QString ("%1 %2").arg(r).arg(getName(bo))
4057 void MapEditor::toggleScroll()
4059 BranchObj *bo=xelection.getBranch();
4060 if (xelection.type()==Selection::Branch )
4062 if (bo->isScrolled())
4063 unscrollBranch (bo);
4069 void MapEditor::unscrollChilds()
4071 BranchObj *bo=xelection.getBranch();
4077 if (bo->isScrolled()) unscrollBranch (bo);
4083 FloatImageObj* MapEditor::loadFloatImageInt (QString fn)
4085 BranchObj *bo=xelection.getBranch();
4089 bo->addFloatImage();
4090 fio=bo->getLastFloatImage();
4092 model->reposition();
4099 void MapEditor::loadFloatImage ()
4101 BranchObj *bo=xelection.getBranch();
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);
4116 if ( fd->exec() == QDialog::Accepted )
4118 // TODO loadFIO in QT4 use: lastImageDir=fd->directory();
4119 lastImageDir=QDir (fd->dirPath());
4122 for (int j=0; j<fd->selectedFiles().count(); j++)
4124 s=fd->selectedFiles().at(j);
4125 fio=loadFloatImageInt (s);
4128 (LinkableMapObj*)fio,
4131 QString ("loadImage (%1)").arg(s ),
4132 QString("Add image %1 to %2").arg(s).arg(getName(bo))
4135 // TODO loadFIO error handling
4136 qWarning ("Failed to load "+s);
4144 void MapEditor::saveFloatImageInt (FloatImageObj *fio, const QString &type, const QString &fn)
4146 fio->save (fn,type);
4149 void MapEditor::saveFloatImage ()
4151 FloatImageObj *fio=xelection.getFloatImage();
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());
4163 if ( fd->exec() == QDialog::Accepted && fd->selectedFiles().count()==1)
4165 fn=fd->selectedFiles().at(0);
4166 if (QFile (fn).exists() )
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 );
4176 mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
4177 mb.setButtonText( QMessageBox::No, tr("Cancel"));
4180 case QMessageBox::Yes:
4183 case QMessageBox::Cancel:
4190 saveFloatImageInt (fio,fd->selectedFilter(),fn );
4196 void MapEditor::setFrameType(const FrameObj::FrameType &t)
4198 BranchObj *bo=xelection.getBranch();
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();
4210 void MapEditor::setFrameType(const QString &s)
4212 BranchObj *bo=xelection.getBranch();
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();
4223 void MapEditor::setFramePenColor(const QColor &c)
4225 BranchObj *bo=xelection.getBranch();
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);
4234 void MapEditor::setFrameBrushColor(const QColor &c)
4236 BranchObj *bo=xelection.getBranch();
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);
4245 void MapEditor::setFramePadding (const int &i)
4247 BranchObj *bo=xelection.getBranch();
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();
4258 void MapEditor::setFrameBorderWidth(const int &i)
4260 BranchObj *bo=xelection.getBranch();
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();
4271 void MapEditor::setIncludeImagesVer(bool b)
4273 BranchObj *bo=xelection.getBranch();
4276 QString u= b ? "false" : "true";
4277 QString r=!b ? "false" : "true";
4281 QString("setIncludeImagesVertically (%1)").arg(u),
4283 QString("setIncludeImagesVertically (%1)").arg(r),
4284 QString("Include images vertically in %1").arg(getName(bo))
4286 bo->setIncludeImagesVer(b);
4287 model->reposition();
4291 void MapEditor::setIncludeImagesHor(bool b)
4293 BranchObj *bo=xelection.getBranch();
4296 QString u= b ? "false" : "true";
4297 QString r=!b ? "false" : "true";
4301 QString("setIncludeImagesHorizontally (%1)").arg(u),
4303 QString("setIncludeImagesHorizontally (%1)").arg(r),
4304 QString("Include images horizontally in %1").arg(getName(bo))
4306 bo->setIncludeImagesHor(b);
4307 model->reposition();
4311 void MapEditor::setHideLinkUnselected (bool b)
4313 LinkableMapObj *sel=xelection.single();
4315 (xelection.type() == Selection::Branch ||
4316 xelection.type() == Selection::MapCenter ||
4317 xelection.type() == Selection::FloatImage ))
4319 QString u= b ? "false" : "true";
4320 QString r=!b ? "false" : "true";
4324 QString("setHideLinkUnselected (%1)").arg(u),
4326 QString("setHideLinkUnselected (%1)").arg(r),
4327 QString("Hide link of %1 if unselected").arg(getName(sel))
4329 sel->setHideLinkUnselected(b);
4333 void MapEditor::importDirInt(BranchObj *dst, QDir d)
4335 BranchObj *bo=xelection.getBranch();
4338 // Traverse directories
4339 d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
4340 QFileInfoList list = d.entryInfoList();
4343 for (int i = 0; i < list.size(); ++i)
4346 if (fi.fileName() != "." && fi.fileName() != ".." )
4349 bo=dst->getLastBranch();
4350 bo->setHeading (fi.fileName() );
4351 bo->setColor (QColor("blue"));
4353 if ( !d.cd(fi.fileName()) )
4354 QMessageBox::critical (0,tr("Critical Import Error"),tr("Cannot find the directory %1").arg(fi.fileName()));
4357 // Recursively add subdirs
4358 importDirInt (bo,d);
4364 d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
4365 list = d.entryInfoList();
4367 for (int i = 0; i < list.size(); ++i)
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());
4380 void MapEditor::importDirInt (const QString &s)
4382 BranchObj *bo=xelection.getBranch();
4385 saveStateChangingPart (bo,bo,QString ("importDir (\"%1\")").arg(s),QString("Import directory structure from %1").arg(s));
4388 importDirInt (bo,d);
4392 void MapEditor::importDir()
4394 BranchObj *bo=xelection.getBranch();
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"));
4406 if ( fd->exec() == QDialog::Accepted )
4408 importDirInt (fd->selectedFile() );
4409 model->reposition();
4415 void MapEditor::followXLink(int i)
4417 BranchObj *bo=xelection.getBranch();
4420 bo=bo->XLinkTargetAt(i);
4423 xelection.select(bo);
4424 ensureSelectionVisible();
4429 void MapEditor::editXLink(int i) // FIXME missing saveState
4431 BranchObj *bo=xelection.getBranch();
4434 XLinkObj *xlo=bo->XLinkAt(i);
4437 EditXLinkDialog dia;
4439 dia.setSelection(bo);
4440 if (dia.exec() == QDialog::Accepted)
4442 if (dia.useSettingsGlobal() )
4444 setMapDefXLinkColor (xlo->getColor() );
4445 setMapDefXLinkWidth (xlo->getWidth() );
4447 if (dia.deleteXLink())
4448 bo->deleteXLinkAt(i);
4454 AttributeTable* MapEditor::attributeTable()
4459 void MapEditor::testFunction1()
4461 BranchObj *bo=xelection.getBranch();
4462 if (bo) model->moveAway (bo);
4464 /* TODO Hide hidden stuff temporary, maybe add this as regular function somewhere
4465 if (hidemode==HideNone)
4467 setHideTmpMode (HideExport);
4468 mapCenter->calcBBoxSizeWithChilds();
4469 QRectF totalBBox=mapCenter->getTotalBBox();
4470 QRectF mapRect=totalBBox;
4471 QCanvasRectangle *frame=NULL;
4473 cout << " map has =("<<totalBBox.x()<<","<<totalBBox.y()<<","<<totalBBox.width()<<","<<totalBBox.height()<<")\n";
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);
4485 setHideTmpMode (HideNone);
4487 cout <<" hidemode="<<hidemode<<endl;
4491 void MapEditor::testFunction2()
4496 if (hidemode==HideExport)
4497 setHideTmpMode (HideNone);
4499 setHideTmpMode (HideExport);
4503 void MapEditor::contextMenuEvent ( QContextMenuEvent * e )
4505 // Lineedits are already closed by preceding
4506 // mouseEvent, we don't need to close here.
4508 QPointF p = mapToScene(e->pos());
4509 LinkableMapObj* lmo=model->findMapObj(p, NULL);
4512 { // MapObj was found
4513 if (xelection.single() != lmo)
4515 // select the MapObj
4516 xelection.select(lmo);
4519 if (xelection.getBranch() )
4521 // Context Menu on branch or mapcenter
4523 branchContextMenu->popup(e->globalPos() );
4526 if (xelection.getFloatImage() )
4528 // Context Menu on floatimage
4530 floatimageContextMenu->popup(e->globalPos() );
4534 { // No MapObj found, we are on the Canvas itself
4535 // Context Menu on scene
4538 canvasContextMenu->popup(e->globalPos() );
4543 void MapEditor::keyPressEvent(QKeyEvent* e)
4545 if (e->modifiers() & Qt::ControlModifier)
4547 switch (mainWindow->getModMode())
4549 case Main::ModModeColor:
4550 setCursor (PickColorCursor);
4552 case Main::ModModeCopy:
4553 setCursor (CopyCursor);
4555 case Main::ModModeXLink:
4556 setCursor (XLinkCursor);
4559 setCursor (Qt::ArrowCursor);
4565 void MapEditor::keyReleaseEvent(QKeyEvent* e)
4567 if (!(e->modifiers() & Qt::ControlModifier))
4568 setCursor (Qt::ArrowCursor);
4571 void MapEditor::mousePressEvent(QMouseEvent* e)
4573 // Ignore right clicks, these will go to context menus
4574 if (e->button() == Qt::RightButton )
4580 //Ignore clicks while editing heading
4581 if (isSelectBlocked() )
4587 QPointF p = mapToScene(e->pos());
4588 LinkableMapObj* lmo=model->findMapObj(p, NULL);
4592 //Take care of system flags _or_ modifier modes
4594 if (lmo && (typeid(*lmo)==typeid(BranchObj) ||
4595 typeid(*lmo)==typeid(MapCenterObj) ))
4597 QString foname=((BranchObj*)lmo)->getSystemFlagName(p);
4598 if (!foname.isEmpty())
4600 // systemFlag clicked
4604 if (e->state() & Qt::ControlModifier)
4605 mainWindow->editOpenURLTab();
4607 mainWindow->editOpenURL();
4609 else if (foname=="vymLink")
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")
4623 // No system flag clicked, take care of modmodes (CTRL-Click)
4624 if (e->state() & Qt::ControlModifier)
4626 if (mainWindow->getModMode()==Main::ModModeColor)
4629 setCursor (PickColorCursor);
4632 if (mainWindow->getModMode()==Main::ModModeXLink)
4634 BranchObj *bo_begin=NULL;
4636 bo_begin=(BranchObj*)(lmo);
4638 if (xelection.getBranch() )
4639 bo_begin=xelection.getBranch();
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);
4654 } // End of modmodes
4658 // Select the clicked object
4661 // Left Button Move Branches
4662 if (e->button() == Qt::LeftButton )
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();
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)
4677 BranchObj *bo=xelection.getBranch();
4681 bo->addBranch ((BranchObj*)xelection.single());
4683 xelection.select(bo->getLastBranch());
4684 model->reposition();
4688 movingObj=xelection.single();
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 )
4698 { // No MapObj found, we are on the scene itself
4699 // Left Button move Pos of sceneView
4700 if (e->button() == Qt::LeftButton )
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);
4713 void MapEditor::mouseMoveEvent(QMouseEvent* e)
4715 QPointF p = mapToScene(e->pos());
4716 LinkableMapObj *lmosel=xelection.single();
4718 // Move the selected MapObj
4719 if ( lmosel && movingObj)
4721 // reset cursor if we are moving and don't copy
4722 if (mainWindow->getModMode()!=Main::ModModeCopy)
4723 setCursor (Qt::ArrowCursor);
4725 // To avoid jumping of the sceneView, only
4726 // ensureSelectionVisible, if not tmp linked
4727 if (!lmosel->hasParObjTmp())
4728 ensureSelectionVisible ();
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)
4735 // Check if we could link
4736 LinkableMapObj* lmo=model->findMapObj(p, lmosel);
4739 FloatObj *fio=xelection.getFloatImage();
4742 fio->move (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4744 fio->updateLink(); //no need for reposition, if we update link here
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())
4755 if (typeid(*fio) == typeid(FloatImageObj) &&
4756 ( (typeid(*lmo)==typeid(BranchObj) ||
4757 typeid(*lmo)==typeid(MapCenterObj)) ))
4760 // Also save the move which was done so far
4761 QString pold=qpointfToString(movingObj_orgRelPos);
4762 QString pnow=qpointfToString(fio->getRelPos());
4768 QString("Move %1 to relative position %2").arg(getName(fio)).arg(pnow));
4769 fio->getParObj()->requestReposition();
4770 model->reposition();
4772 linkTo (model->getSelectString(lmo));
4774 //movingObj_orgRelPos=lmosel->getRelPos();
4776 model->reposition();
4780 { // selection != a FloatObj
4781 if (lmosel->getDepth()==0)
4784 if (e->buttons()== Qt::LeftButton && e->modifiers()==Qt::ShiftModifier)
4785 ((MapCenterObj*)lmosel)->moveAll(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4787 lmosel->move (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4788 model->updateRelPositions();
4791 if (lmosel->getDepth()==1)
4794 lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4795 lmosel->setRelPos();
4798 // Move ordinary branch
4799 lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4802 // Maybe we can relink temporary?
4803 if (lmo && (lmo!=lmosel) && xelection.getBranch() &&
4804 (typeid(*lmo)==typeid(BranchObj) ||
4805 typeid(*lmo)==typeid(MapCenterObj)) )
4808 if (e->modifiers()==Qt::ControlModifier)
4810 // Special case: CTRL to link below lmo
4811 lmosel->setParObjTmp (lmo,p,+1);
4813 else if (e->modifiers()==Qt::ShiftModifier)
4814 lmosel->setParObjTmp (lmo,p,-1);
4816 lmosel->setParObjTmp (lmo,p,0);
4819 lmosel->unsetParObjTmp();
4821 // reposition subbranch
4822 lmosel->reposition();
4826 } // no FloatImageObj
4830 } // selection && moving_obj
4832 // Draw a link from one branch to another
4835 tmpXLink->setEnd (p);
4836 tmpXLink->updateXLink();
4840 if (!movingObj && !pickingColor &&!drawingLink && e->buttons() == Qt::LeftButton )
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() ) );
4851 void MapEditor::mouseReleaseEvent(QMouseEvent* e)
4853 QPointF p = mapToScene(e->pos());
4854 LinkableMapObj *dst;
4855 LinkableMapObj *lmosel=xelection.single();
4856 // Have we been picking color?
4860 setCursor (Qt::ArrowCursor);
4861 // Check if we are over another branch
4862 dst=model->findMapObj(p, NULL);
4865 if (e->state() & Qt::ShiftModifier)
4866 colorBranch (((BranchObj*)dst)->getColor());
4868 colorSubtree (((BranchObj*)dst)->getColor());
4873 // Have we been drawing a link?
4877 // Check if we are over another branch
4878 dst=model->findMapObj(p, NULL);
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())) );
4893 // Have we been moving something?
4894 if ( lmosel && movingObj )
4896 FloatImageObj *fo=xelection.getFloatImage();
4899 // Moved FloatObj. Maybe we need to reposition
4900 QString pold=qpointfToString(movingObj_orgRelPos);
4901 QString pnow=qpointfToString(fo->getRelPos());
4907 QString("Move %1 to relative position %2").arg(getName(fo)).arg(pnow));
4909 fo->getParObj()->requestReposition();
4910 model->reposition();
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);
4917 if (dst && (typeid(*dst)!=typeid(BranchObj) && typeid(*dst)!=typeid(MapCenterObj)))
4920 BranchObj *bo=xelection.getBranch();
4921 if (bo && bo->getDepth()==0)
4923 if (movingObj_orgPos != bo->getAbsPos())
4925 QString pold=qpointfToString(movingObj_orgPos);
4926 QString pnow=qpointfToString(bo->getAbsPos());
4932 QString("Move mapcenter %1 to position %2").arg(getName(bo)).arg(pnow));
4936 if (xelection.type() == Selection::Branch )
4937 { // A branch was moved
4939 // save the position in case we link to mapcenter
4940 QPointF savePos=QPointF (lmosel->getAbsPos() );
4942 // Reset the temporary drawn link to the original one
4943 lmosel->unsetParObjTmp();
4945 // For Redo we may need to save original selection
4946 QString preSelStr=model->getSelectString(lmosel);
4951 // We have a destination, relink to that
4953 BranchObj* bsel=xelection.getBranch();
4954 BranchObj* bdst=(BranchObj*)dst;
4956 QString preParStr=model->getSelectString (bsel->getParObj());
4957 QString preNum=QString::number (bsel->getNum(),10);
4958 QString preDstParStr;
4960 if (e->state() & Qt::ShiftModifier && dst->getParObj())
4962 preDstParStr=model->getSelectString (dst->getParObj());
4963 bsel->linkTo ( (BranchObj*)(bdst->getParObj()), bdst->getNum());
4965 if (e->state() & Qt::ControlModifier && dst->getParObj())
4968 preDstParStr=model->getSelectString (dst->getParObj());
4969 bsel->linkTo ( (BranchObj*)(bdst->getParObj()), bdst->getNum()+1);
4972 preDstParStr=model->getSelectString(dst);
4973 bsel->linkTo (bdst,-1);
4974 if (dst->getDepth()==0) bsel->move (savePos);
4976 QString postSelStr=model->getSelectString(lmosel);
4977 QString postNum=QString::number (bsel->getNum(),10);
4979 QString undoCom="linkTo (\""+
4980 preParStr+ "\"," + preNum +"," +
4981 QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+ ")";
4983 QString redoCom="linkTo (\""+
4984 preDstParStr + "\"," + postNum + "," +
4985 QString ("%1,%2").arg(savePos.x()).arg(savePos.y())+ ")";
4990 QString("Relink %1 to %2").arg(getName(bsel)).arg(getName(dst)) );
4992 model->reposition(); // not necessary if we undo temporary move below
4995 // No destination, undo temporary move
4997 if (lmosel->getDepth()==1)
4999 // The select string might be different _after_ moving around.
5000 // Therefor reposition and then use string of old selection, too
5001 model->reposition();
5003 QPointF rp(lmosel->getRelPos());
5004 if (rp != movingObj_orgRelPos)
5006 QString ps=qpointfToString(rp);
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));
5014 // Draw the original link, before selection was moved around
5015 if (settings.value("/animation/use",false).toBool() && lmosel->getDepth()>1)
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() )
5024 model->reposition();
5028 // Finally resize scene, if needed
5032 // Just make sure, that actions are still ok,e.g. the move branch up/down buttons...
5035 // maybe we moved View: set old cursor
5036 setCursor (Qt::ArrowCursor);
5040 void MapEditor::mouseDoubleClickEvent(QMouseEvent* e)
5042 if (isSelectBlocked() )
5048 if (e->button() == Qt::LeftButton )
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();
5060 void MapEditor::resizeEvent (QResizeEvent* e)
5062 QGraphicsView::resizeEvent( e );
5065 void MapEditor::dragEnterEvent(QDragEnterEvent *event)
5067 //for (unsigned int i=0;event->format(i);i++) // Debug mime type
5068 // cerr << event->format(i) << endl;
5070 if (event->mimeData()->hasImage())
5071 event->acceptProposedAction();
5073 if (event->mimeData()->hasUrls())
5074 event->acceptProposedAction();
5077 void MapEditor::dragMoveEvent(QDragMoveEvent *)
5081 void MapEditor::dragLeaveEvent(QDragLeaveEvent *event)
5086 void MapEditor::dropEvent(QDropEvent *event)
5088 BranchObj *sel=xelection.getBranch();
5092 foreach (QString format,event->mimeData()->formats())
5093 cout << "MapEditor: Dropped format: "<<qPrintable (format)<<endl;
5097 if (event->mimeData()->hasImage())
5099 QVariant imageData = event->mimeData()->imageData();
5100 addFloatImageInt (qvariant_cast<QPixmap>(imageData));
5102 if (event->mimeData()->hasUrls())
5103 uris=event->mimeData()->urls();
5111 for (int i=0; i<uris.count();i++)
5113 // Workaround to avoid adding empty branches
5114 if (!uris.at(i).toString().isEmpty())
5116 bo=sel->addBranch();
5119 s=uris.at(i).toLocalFile();
5122 QString file = QDir::fromNativeSeparators(s);
5123 heading = QFileInfo(file).baseName();
5125 if (file.endsWith(".vym", false))
5126 bo->setVymLink(file);
5128 bo->setURL(uris.at(i).toString());
5131 bo->setURL(uris.at(i).toString());
5134 if (!heading.isEmpty())
5135 bo->setHeading(heading);
5137 bo->setHeading(uris.at(i).toString());
5141 model->reposition();
5144 event->acceptProposedAction();
5148 void MapEditor::sendSelection()
5150 if (netstate!=Server) return;
5151 sendData (QString("select (\"%1\")").arg(xelection.getSelectString()) );
5154 void MapEditor::newServer()
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()));
5165 connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
5167 cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
5170 void MapEditor::connectToServer()
5173 server="salam.suse.de";
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)));
5182 cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
5187 void MapEditor::newClient()
5189 QTcpSocket *newClient = tcpServer->nextPendingConnection();
5190 connect(newClient, SIGNAL(disconnected()),
5191 newClient, SLOT(deleteLater()));
5193 cout <<"ME::newClient at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
5195 clientList.append (newClient);
5199 void MapEditor::sendData(const QString &s)
5201 if (clientList.size()==0) return;
5203 // Create bytearray to send
5205 QDataStream out(&block, QIODevice::WriteOnly);
5206 out.setVersion(QDataStream::Qt_4_0);
5208 // Reserve some space for blocksize
5211 // Write sendCounter
5212 out << sendCounter++;
5217 // Go back and write blocksize so far
5218 out.device()->seek(0);
5219 quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
5223 cout << "ME::sendData bs="<<bs<<" counter="<<sendCounter<<" s="<<qPrintable(s)<<endl;
5225 for (int i=0; i<clientList.size(); ++i)
5227 //cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
5228 clientList.at(i)->write (block);
5232 void MapEditor::readData ()
5234 while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
5237 cout <<"readData bytesAvail="<<clientSocket->bytesAvailable();
5241 QDataStream in(clientSocket);
5242 in.setVersion(QDataStream::Qt_4_0);
5250 cout << " t="<<qPrintable (t)<<endl;
5256 void MapEditor::displayNetworkError(QAbstractSocket::SocketError socketError)
5258 switch (socketError) {
5259 case QAbstractSocket::RemoteHostClosedError:
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.");
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.");
5274 QMessageBox::information(this, vymName + " Network client",
5275 QString("The following error occurred: %1.")
5276 .arg(clientSocket->errorString()));
5280 void MapEditor::autosave()
5282 QDateTime now=QDateTime().currentDateTime();
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;
5290 // Disable autosave, while we have gone back in history
5291 int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
5292 if (redosAvail>0) return;
5294 // Also disable autosave for new map without filename
5295 if (filePath.isEmpty()) return;
5298 if (mapUnsaved &&mapChanged && settings.value ("/mapeditor/autosave/use",true).toBool() )
5300 if (QFileInfo(filePath).lastModified()<=fileChangedTime)
5301 mainWindow->fileSave (this);
5304 cout <<" ME::autosave rejected, file on disk is newer than last save.\n";
5308 void MapEditor::fileChanged()
5310 // Check if file on disk has changed meanwhile
5311 if (!filePath.isEmpty())
5313 QDateTime tmod=QFileInfo (filePath).lastModified();
5314 if (tmod>fileChangedTime)
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;
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,
5328 QMessageBox::Cancel | QMessageBox::Default,
5329 QMessageBox::NoButton );
5331 mb.setButtonText( QMessageBox::Yes, tr("Reload"));
5332 mb.setButtonText( QMessageBox::No, tr("Ignore"));
5335 case QMessageBox::Yes:
5337 load (filePath,NewMap,fileType);
5338 case QMessageBox::Cancel:
5339 fileChangedTime=tmod; // allow autosave to overwrite newer file!
5347 /*TODO not needed? void MapEditor::contentsDropEvent(QDropEvent *event)
5350 } else if (event->provides("application/x-moz-file-promise-url") &&
5351 event->provides("application/x-moz-nativeimage"))
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);
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"));
5367 } else if (event->provides("text/html")) {
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");
5374 text = QString((const QChar*)d.data(),d.size()/2);
5378 textEditor->setText(text);
5382 } else if (event->provides("text/plain")) {
5383 QByteArray d = event->encodedData("text/plain");
5386 text = QString((const QChar*)d.data(),d.size()/2);
5390 textEditor->setText(text);
5400 bool isUnicode16(const QByteArray &d)
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;
5410 void MapEditor::addFloatImageInt (const QPixmap &img)
5412 BranchObj *bo=xelection.getBranch();
5415 FloatImageObj *fio=bo->addFloatImage();
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();
5428 void MapEditor::imageDataFetched(const QByteArray &a, Q3NetworkOperation * / *nop* /)
5430 if (!imageBuffer) imageBuffer = new QBuffer();
5431 if (!imageBuffer->isOpen()) {
5432 imageBuffer->open(QIODevice::WriteOnly | QIODevice::Append);
5434 imageBuffer->at(imageBuffer->at()+imageBuffer->writeBlock(a));
5438 void MapEditor::imageDataFinished(Q3NetworkOperation *nop)
5440 if (nop->state()==Q3NetworkProtocol::StDone) {
5441 QPixmap img(imageBuffer->buffer());
5442 addFloatImageInt (img);
5446 imageBuffer->close();
5448 imageBuffer->close();
5455 void MapEditor::fetchImage(const QString &url)
5458 urlOperator->stop();
5459 disconnect(urlOperator);
5463 urlOperator = new Q3UrlOperator(url);
5464 connect(urlOperator, SIGNAL(finished(Q3NetworkOperation *)),
5465 this, SLOT(imageDataFinished(Q3NetworkOperation*)));
5467 connect(urlOperator, SIGNAL(data(const QByteArray &, Q3NetworkOperation *)),
5468 this, SLOT(imageDataFetched(const QByteArray &, Q3NetworkOperation *)));