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\n";
189 autosaveTimer->stop();
190 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:\n%1").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 xelection.unselect();
2176 void MapEditor::copy()
2178 LinkableMapObj *sel=xelection.single();
2181 if (redosAvail == 0)
2184 QString s=model->getSelectString(sel);
2185 saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",sel );
2186 curClipboard=curStep;
2189 // Copy also to global clipboard, because we are at last step in history
2190 QString bakMapName(QString("history-%1").arg(curStep));
2191 QString bakMapDir(tmpMapDir +"/"+bakMapName);
2192 copyDir (bakMapDir,clipboardDir );
2194 clipboardEmpty=false;
2199 void MapEditor::redo()
2201 // Can we undo at all?
2202 if (redosAvail<1) return;
2204 bool blockSaveStateOrg=blockSaveState;
2205 blockSaveState=true;
2209 if (undosAvail<stepsTotal) undosAvail++;
2211 if (curStep>stepsTotal) curStep=1;
2212 QString undoCommand= undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
2213 QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
2214 QString redoCommand= undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
2215 QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
2216 QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
2217 QString version=undoSet.readEntry ("/history/version");
2219 /* TODO Maybe check for version, if we save the history
2220 if (!checkVersion(version))
2221 QMessageBox::warning(0,tr("Warning"),
2222 tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
2225 // Find out current undo directory
2226 QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
2230 cout << "ME::redo() begin\n";
2231 cout << " undosAvail="<<undosAvail<<endl;
2232 cout << " redosAvail="<<redosAvail<<endl;
2233 cout << " curStep="<<curStep<<endl;
2234 cout << " ---------------------------"<<endl;
2235 cout << " comment="<<comment.toStdString()<<endl;
2236 cout << " undoCom="<<undoCommand.toStdString()<<endl;
2237 cout << " undoSel="<<undoSelection.toStdString()<<endl;
2238 cout << " redoCom="<<redoCommand.toStdString()<<endl;
2239 cout << " redoSel="<<redoSelection.toStdString()<<endl;
2240 cout << " ---------------------------"<<endl<<endl;
2243 // select object before redo
2244 if (!redoSelection.isEmpty())
2245 select (redoSelection);
2248 parseAtom (redoCommand);
2249 model->reposition();
2251 blockSaveState=blockSaveStateOrg;
2253 undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
2254 undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
2255 undoSet.setEntry ("/history/curStep",QString::number(curStep));
2256 undoSet.writeSettings(histPath);
2258 mainWindow->updateHistory (undoSet);
2261 /* TODO remove testing
2262 cout << "ME::redo() end\n";
2263 cout << " undosAvail="<<undosAvail<<endl;
2264 cout << " redosAvail="<<redosAvail<<endl;
2265 cout << " curStep="<<curStep<<endl;
2266 cout << " ---------------------------"<<endl<<endl;
2272 bool MapEditor::isRedoAvailable()
2274 if (undoSet.readNumEntry("/history/redosAvail",0)>0)
2280 void MapEditor::undo()
2282 // Can we undo at all?
2283 if (undosAvail<1) return;
2285 mainWindow->statusMessage (tr("Autosave disabled during undo."));
2287 bool blockSaveStateOrg=blockSaveState;
2288 blockSaveState=true;
2290 QString undoCommand= undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
2291 QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
2292 QString redoCommand= undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
2293 QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
2294 QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
2295 QString version=undoSet.readEntry ("/history/version");
2297 /* TODO Maybe check for version, if we save the history
2298 if (!checkVersion(version))
2299 QMessageBox::warning(0,tr("Warning"),
2300 tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
2303 // Find out current undo directory
2304 QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
2306 // select object before undo
2307 if (!undoSelection.isEmpty())
2308 select (undoSelection);
2312 cout << "ME::undo() begin\n";
2313 cout << " undosAvail="<<undosAvail<<endl;
2314 cout << " redosAvail="<<redosAvail<<endl;
2315 cout << " curStep="<<curStep<<endl;
2316 cout << " ---------------------------"<<endl;
2317 cout << " comment="<<comment.toStdString()<<endl;
2318 cout << " undoCom="<<undoCommand.toStdString()<<endl;
2319 cout << " undoSel="<<undoSelection.toStdString()<<endl;
2320 cout << " redoCom="<<redoCommand.toStdString()<<endl;
2321 cout << " redoSel="<<redoSelection.toStdString()<<endl;
2322 cout << " ---------------------------"<<endl<<endl;
2324 parseAtom (undoCommand);
2325 model->reposition();
2329 if (curStep<1) curStep=stepsTotal;
2333 blockSaveState=blockSaveStateOrg;
2334 /* TODO remove testing
2335 cout << "ME::undo() end\n";
2336 cout << " undosAvail="<<undosAvail<<endl;
2337 cout << " redosAvail="<<redosAvail<<endl;
2338 cout << " curStep="<<curStep<<endl;
2339 cout << " ---------------------------"<<endl<<endl;
2342 undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
2343 undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
2344 undoSet.setEntry ("/history/curStep",QString::number(curStep));
2345 undoSet.writeSettings(histPath);
2347 mainWindow->updateHistory (undoSet);
2350 ensureSelectionVisible();
2353 bool MapEditor::isUndoAvailable()
2355 if (undoSet.readNumEntry("/history/undosAvail",0)>0)
2361 void MapEditor::gotoHistoryStep (int i)
2363 // Restore variables
2364 int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
2365 int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
2367 if (i<0) i=undosAvail+redosAvail;
2369 // Clicking above current step makes us undo things
2372 for (int j=0; j<undosAvail-i; j++) undo();
2375 // Clicking below current step makes us redo things
2377 for (int j=undosAvail; j<i; j++)
2379 if (debug) cout << "ME::gotoHistoryStep redo "<<j<<"/"<<undosAvail<<" i="<<i<<endl;
2383 // And ignore clicking the current row ;-)
2386 void MapEditor::addMapReplaceInt(const QString &undoSel, const QString &path)
2388 QString pathDir=path.left(path.findRev("/"));
2394 // We need to parse saved XML data
2395 parseVYMHandler handler;
2396 QXmlInputSource source( file);
2397 QXmlSimpleReader reader;
2398 reader.setContentHandler( &handler );
2399 reader.setErrorHandler( &handler );
2400 handler.setModel ( model);
2401 handler.setTmpDir ( pathDir ); // needed to load files with rel. path
2402 if (undoSel.isEmpty())
2406 handler.setLoadMode (NewMap);
2410 handler.setLoadMode (ImportReplace);
2412 blockReposition=true;
2413 bool ok = reader.parse( source );
2414 blockReposition=false;
2417 // This should never ever happen
2418 QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
2419 handler.errorProtocol());
2422 QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
2425 void MapEditor::addMapInsertInt (const QString &path, int pos)
2427 BranchObj *sel=xelection.getBranch();
2430 QString pathDir=path.left(path.findRev("/"));
2436 // We need to parse saved XML data
2437 parseVYMHandler handler;
2438 QXmlInputSource source( file);
2439 QXmlSimpleReader reader;
2440 reader.setContentHandler( &handler );
2441 reader.setErrorHandler( &handler );
2442 handler.setModel (model);
2443 handler.setTmpDir ( pathDir ); // needed to load files with rel. path
2444 handler.setLoadMode (ImportAdd);
2445 blockReposition=true;
2446 bool ok = reader.parse( source );
2447 blockReposition=false;
2450 // This should never ever happen
2451 QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
2452 handler.errorProtocol());
2454 if (sel->getDepth()>0)
2455 sel->getLastBranch()->linkTo (sel,pos);
2457 QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
2461 void MapEditor::pasteNoSave(const int &n)
2463 bool old=blockSaveState;
2464 blockSaveState=true;
2465 bool zippedOrg=zipped;
2466 if (redosAvail > 0 || n!=0)
2468 // Use the "historical" buffer
2469 QString bakMapName(QString("history-%1").arg(n));
2470 QString bakMapDir(tmpMapDir +"/"+bakMapName);
2471 load (bakMapDir+"/"+clipboardFile,ImportAdd, VymMap);
2473 // Use the global buffer
2474 load (clipboardDir+"/"+clipboardFile,ImportAdd, VymMap);
2479 void MapEditor::paste()
2481 BranchObj *sel=xelection.getBranch();
2484 saveStateChangingPart(
2487 QString ("paste (%1)").arg(curClipboard),
2488 QString("Paste to %1").arg( getName(sel))
2491 model->reposition();
2495 void MapEditor::cut()
2497 LinkableMapObj *sel=xelection.single();
2498 if ( sel && (xelection.type() == Selection::Branch ||
2499 xelection.type()==Selection::MapCenter ||
2500 xelection.type()==Selection::FloatImage))
2502 /* No savestate! savestate is called in cutNoSave
2503 saveStateChangingPart(
2507 QString("Cut %1").arg(getName(sel ))
2512 model->reposition();
2516 void MapEditor::move(const double &x, const double &y)
2518 LinkableMapObj *sel=xelection.single();
2521 QPointF ap(sel->getAbsPos());
2525 QString ps=qpointfToString(ap);
2526 QString s=xelection.getSelectString();
2529 s, "move "+qpointfToString(to),
2530 QString("Move %1 to %2").arg(getName(sel)).arg(ps));
2532 model->reposition();
2538 void MapEditor::moveRel (const double &x, const double &y)
2540 LinkableMapObj *sel=xelection.single();
2543 QPointF rp(sel->getRelPos());
2547 QString ps=qpointfToString (sel->getRelPos());
2548 QString s=model->getSelectString(sel);
2551 s, "moveRel "+qpointfToString(to),
2552 QString("Move %1 to relative position %2").arg(getName(sel)).arg(ps));
2553 ((OrnamentedObj*)sel)->move2RelPos (x,y);
2554 model->reposition();
2561 void MapEditor::moveBranchUp()
2563 BranchObj* bo=xelection.getBranch();
2567 if (!bo->canMoveBranchUp()) return;
2568 par=(BranchObj*)(bo->getParObj());
2569 BranchObj *obo=par->moveBranchUp (bo); // bo will be the one below selection
2570 saveState (model->getSelectString(bo),"moveBranchDown ()",model->getSelectString(obo),"moveBranchUp ()",QString("Move up %1").arg(getName(bo)));
2571 model->reposition();
2574 ensureSelectionVisible();
2578 void MapEditor::moveBranchDown()
2580 BranchObj* bo=xelection.getBranch();
2584 if (!bo->canMoveBranchDown()) return;
2585 par=(BranchObj*)(bo->getParObj());
2586 BranchObj *obo=par->moveBranchDown(bo); // bo will be the one above selection
2587 saveState(model->getSelectString(bo),"moveBranchUp ()",model->getSelectString(obo),"moveBranchDown ()",QString("Move down %1").arg(getName(bo)));
2588 model->reposition();
2591 ensureSelectionVisible();
2595 void MapEditor::sortChildren()
2597 BranchObj* bo=xelection.getBranch();
2600 if(bo->countBranches()>1)
2602 saveStateChangingPart(bo,bo, "sortChildren ()",QString("Sort children of %1").arg(getName(bo)));
2604 model->reposition();
2605 ensureSelectionVisible();
2610 void MapEditor::linkTo(const QString &dstString)
2612 FloatImageObj *fio=xelection.getFloatImage();
2615 BranchObj *dst=(BranchObj*)(model->findObjBySelect(dstString));
2616 if (dst && (typeid(*dst)==typeid (BranchObj) ||
2617 typeid(*dst)==typeid (MapCenterObj)))
2619 LinkableMapObj *dstPar=dst->getParObj();
2620 QString parString=model->getSelectString(dstPar);
2621 QString fioPreSelectString=model->getSelectString(fio);
2622 QString fioPreParentSelectString=model->getSelectString (fio->getParObj());
2623 ((BranchObj*)(dst))->addFloatImage (fio);
2624 xelection.unselect();
2625 ((BranchObj*)(fio->getParObj()))->removeFloatImage (fio);
2626 fio=((BranchObj*)(dst))->getLastFloatImage();
2629 xelection.select(fio);
2631 model->getSelectString(fio),
2632 QString("linkTo (\"%1\")").arg(fioPreParentSelectString),
2634 QString ("linkTo (\"%1\")").arg(dstString),
2635 QString ("Link floatimage to %1").arg(getName(dst)));
2640 QString MapEditor::getHeading(bool &ok, QPoint &p)
2642 BranchObj *bo=xelection.getBranch();
2646 p=mapFromScene(bo->getAbsPos());
2647 return bo->getHeading();
2653 void MapEditor::setHeading(const QString &s)
2655 BranchObj *sel=xelection.getBranch();
2660 "setHeading (\""+sel->getHeading()+"\")",
2662 "setHeading (\""+s+"\")",
2663 QString("Set heading of %1 to \"%2\"").arg(getName(sel)).arg(s) );
2664 sel->setHeading(s );
2665 model->reposition();
2667 ensureSelectionVisible();
2671 void MapEditor::setHeadingInt(const QString &s)
2673 BranchObj *bo=xelection.getBranch();
2677 model->reposition();
2679 ensureSelectionVisible();
2683 void MapEditor::setVymLinkInt (const QString &s)
2685 // Internal function, no saveState needed
2686 BranchObj *bo=xelection.getBranch();
2690 model->reposition();
2693 ensureSelectionVisible();
2697 BranchObj* MapEditor::addMapCenter ()
2699 MapCenterObj *mco= model->addMapCenter(contextMenuPos);
2700 xelection.select (mco);
2702 ensureSelectionVisible();
2707 QString ("addMapCenter (%1,%2)").arg (contextMenuPos.x()).arg(contextMenuPos.y()),
2708 QString ("Adding MapCenter to (%1,%2").arg (contextMenuPos.x()).arg(contextMenuPos.y())
2713 BranchObj* MapEditor::addNewBranchInt(int num)
2715 // Depending on pos:
2716 // -3 insert in childs of parent above selection
2717 // -2 add branch to selection
2718 // -1 insert in childs of parent below selection
2719 // 0..n insert in childs of parent at pos
2720 BranchObj *newbo=NULL;
2721 BranchObj *bo=xelection.getBranch();
2726 // save scroll state. If scrolled, automatically select
2727 // new branch in order to tmp unscroll parent...
2728 newbo=bo->addBranch();
2733 bo=(BranchObj*)bo->getParObj();
2734 if (bo) newbo=bo->insertBranch(num);
2738 bo=(BranchObj*)bo->getParObj();
2739 if (bo) newbo=bo->insertBranch(num);
2741 if (!newbo) return NULL;
2746 BranchObj* MapEditor::addNewBranch(int pos)
2748 // Different meaning than num in addNewBranchInt!
2752 BranchObj *bo = xelection.getBranch();
2753 BranchObj *newbo=NULL;
2757 setCursor (Qt::ArrowCursor);
2759 newbo=addNewBranchInt (pos-2);
2767 QString ("addBranch (%1)").arg(pos),
2768 QString ("Add new branch to %1").arg(getName(bo)));
2770 model->reposition();
2772 latestSelection=model->getSelectString(newbo);
2773 // In Network mode, the client needs to know where the new branch is,
2774 // so we have to pass on this information via saveState.
2775 // TODO: Get rid of this positioning workaround
2776 QString ps=qpointfToString (newbo->getAbsPos());
2777 sendData ("selectLatestAdded ()");
2778 sendData (QString("move %1").arg(ps));
2786 BranchObj* MapEditor::addNewBranchBefore()
2788 BranchObj *newbo=NULL;
2789 BranchObj *bo = xelection.getBranch();
2790 if (bo && xelection.type()==Selection::Branch)
2791 // We accept no MapCenterObj here, so we _have_ a parent
2793 QPointF p=bo->getRelPos();
2796 BranchObj *parbo=(BranchObj*)(bo->getParObj());
2798 // add below selection
2799 newbo=parbo->insertBranch(bo->getNum()+1);
2802 newbo->move2RelPos (p);
2804 // Move selection to new branch
2805 bo->linkTo (newbo,-1);
2807 saveState (newbo, "deleteKeepChilds ()", newbo, "addBranchBefore ()",
2808 QString ("Add branch before %1").arg(getName(bo)));
2810 model->reposition();
2814 latestSelection=xelection.getSelectString();
2818 void MapEditor::deleteSelection()
2820 BranchObj *bo = xelection.getBranch();
2821 if (bo && xelection.type()==Selection::MapCenter)
2823 // BranchObj* par=(BranchObj*)(bo->getParObj());
2824 xelection.unselect();
2825 /* FIXME Note: does saveStateRemovingPart work for MCO? (No parent!)
2826 saveStateRemovingPart (bo, QString ("Delete %1").arg(getName(bo)));
2828 bo=model->removeMapCenter ((MapCenterObj*)bo);
2831 xelection.select (bo);
2832 ensureSelectionVisible();
2835 model->reposition();
2838 if (bo && xelection.type()==Selection::Branch)
2840 BranchObj* par=(BranchObj*)bo->getParObj();
2841 xelection.unselect();
2842 saveStateRemovingPart (bo, QString ("Delete %1").arg(getName(bo)));
2843 par->removeBranch(bo);
2844 xelection.select (par);
2845 ensureSelectionVisible();
2846 model->reposition();
2847 // xelection.update();
2851 FloatImageObj *fio=xelection.getFloatImage();
2854 BranchObj* par=(BranchObj*)fio->getParObj();
2855 saveStateChangingPart(
2859 QString("Delete %1").arg(getName(fio))
2861 xelection.unselect();
2862 par->removeFloatImage(fio);
2863 xelection.select (par);
2864 model->reposition();
2866 ensureSelectionVisible();
2871 LinkableMapObj* MapEditor::getSelection()
2873 return xelection.single();
2876 BranchObj* MapEditor::getSelectedBranch()
2878 return xelection.getBranch();
2881 FloatImageObj* MapEditor::getSelectedFloatImage()
2883 return xelection.getFloatImage();
2886 void MapEditor::unselect()
2888 xelection.unselect();
2891 void MapEditor::reselect()
2893 xelection.reselect();
2896 bool MapEditor::select (const QString &s)
2898 if (xelection.select(s))
2901 ensureSelectionVisible();
2908 bool MapEditor::select (LinkableMapObj *lmo)
2910 if (xelection.select(lmo))
2913 ensureSelectionVisible();
2920 QString MapEditor::getSelectString()
2922 return xelection.getSelectString();
2925 void MapEditor::selectInt (LinkableMapObj *lmo)
2927 if (lmo && xelection.single()!= lmo && isSelectBlocked()==false )
2929 xelection.select(lmo);
2935 void MapEditor::selectNextBranchInt()
2937 // Increase number of branch
2938 LinkableMapObj *sel=xelection.single();
2941 QString s=xelection.getSelectString();
2947 part=s.section(",",-1);
2949 num=part.right(part.length() - 3);
2951 s=s.left (s.length() -num.length());
2954 num=QString ("%1").arg(num.toUInt()+1);
2958 // Try to select this one
2959 if (select (s)) return;
2961 // We have no direct successor,
2962 // try to increase the parental number in order to
2963 // find a successor with same depth
2965 int d=xelection.single()->getDepth();
2970 while (!found && d>0)
2972 s=s.section (",",0,d-1);
2973 // replace substring of current depth in s with "1"
2974 part=s.section(",",-1);
2976 num=part.right(part.length() - 3);
2980 // increase number of parent
2981 num=QString ("%1").arg(num.toUInt()+1);
2982 s=s.section (",",0,d-2) + ","+ typ+num;
2985 // Special case, look at orientation
2986 if (xelection.single()->getOrientation()==LinkableMapObj::RightOfCenter)
2987 num=QString ("%1").arg(num.toUInt()+1);
2989 num=QString ("%1").arg(num.toUInt()-1);
2994 // pad to oldDepth, select the first branch for each depth
2995 for (i=d;i<oldDepth;i++)
3000 if ( xelection.getBranch()->countBranches()>0)
3008 // try to select the freshly built string
3016 void MapEditor::selectPrevBranchInt()
3018 // Decrease number of branch
3019 BranchObj *bo=xelection.getBranch();
3022 QString s=xelection.getSelectString();
3028 part=s.section(",",-1);
3030 num=part.right(part.length() - 3);
3032 s=s.left (s.length() -num.length());
3034 int n=num.toInt()-1;
3037 num=QString ("%1").arg(n);
3040 // Try to select this one
3041 if (n>=0 && select (s)) return;
3043 // We have no direct precessor,
3044 // try to decrease the parental number in order to
3045 // find a precessor with same depth
3047 int d=xelection.single()->getDepth();
3052 while (!found && d>0)
3054 s=s.section (",",0,d-1);
3055 // replace substring of current depth in s with "1"
3056 part=s.section(",",-1);
3058 num=part.right(part.length() - 3);
3062 // decrease number of parent
3063 num=QString ("%1").arg(num.toInt()-1);
3064 s=s.section (",",0,d-2) + ","+ typ+num;
3067 // Special case, look at orientation
3068 if (xelection.single()->getOrientation()==LinkableMapObj::RightOfCenter)
3069 num=QString ("%1").arg(num.toInt()-1);
3071 num=QString ("%1").arg(num.toInt()+1);
3076 // pad to oldDepth, select the last branch for each depth
3077 for (i=d;i<oldDepth;i++)
3081 if ( xelection.getBranch()->countBranches()>0)
3082 s+=",bo:"+ QString ("%1").arg( xelection.getBranch()->countBranches()-1 );
3089 // try to select the freshly built string
3097 void MapEditor::selectUpperBranch()
3099 if (isSelectBlocked() ) return;
3101 BranchObj *bo=xelection.getBranch();
3102 if (bo && xelection.type()==Selection::Branch)
3104 if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
3105 selectPrevBranchInt();
3107 if (bo->getDepth()==1)
3108 selectNextBranchInt();
3110 selectPrevBranchInt();
3114 void MapEditor::selectLowerBranch()
3116 if (isSelectBlocked() ) return;
3118 BranchObj *bo=xelection.getBranch();
3119 if (bo && xelection.type()==Selection::Branch)
3121 if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
3122 selectNextBranchInt();
3124 if (bo->getDepth()==1)
3125 selectPrevBranchInt();
3127 selectNextBranchInt();
3132 void MapEditor::selectLeftBranch()
3134 if (isSelectBlocked() ) return;
3138 LinkableMapObj *sel=xelection.single();
3141 if (xelection.type()== Selection::MapCenter)
3143 par=xelection.getBranch();
3144 bo=par->getLastSelectedBranch();
3147 // Workaround for reselecting on left and right side
3148 if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
3149 bo=par->getLastBranch();
3152 bo=par->getLastBranch();
3153 xelection.select(bo);
3155 ensureSelectionVisible();
3161 par=(BranchObj*)(sel->getParObj());
3162 if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
3164 if (xelection.type() == Selection::Branch ||
3165 xelection.type() == Selection::FloatImage)
3167 xelection.select(par);
3169 ensureSelectionVisible();
3174 if (xelection.type() == Selection::Branch )
3176 bo=xelection.getBranch()->getLastSelectedBranch();
3179 xelection.select(bo);
3181 ensureSelectionVisible();
3190 void MapEditor::selectRightBranch()
3192 if (isSelectBlocked() ) return;
3196 LinkableMapObj *sel=xelection.single();
3199 if (xelection.type()==Selection::MapCenter)
3201 par=xelection.getBranch();
3202 bo=par->getLastSelectedBranch();
3205 // Workaround for reselecting on left and right side
3206 if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
3207 bo=par->getFirstBranch();
3210 xelection.select(bo);
3212 ensureSelectionVisible();
3218 par=(BranchObj*)(xelection.single()->getParObj());
3219 if (xelection.single()->getOrientation()==LinkableMapObj::LeftOfCenter)
3221 if (xelection.type() == Selection::Branch ||
3222 xelection.type() == Selection::FloatImage)
3224 xelection.select(par);
3226 ensureSelectionVisible();
3231 if (xelection.type() == Selection::Branch)
3233 bo=xelection.getBranch()->getLastSelectedBranch();
3236 xelection.select(bo);
3238 ensureSelectionVisible();
3247 void MapEditor::selectFirstBranch()
3249 BranchObj *bo1=xelection.getBranch();
3254 par=(BranchObj*)(bo1->getParObj());
3256 bo2=par->getFirstBranch();
3258 xelection.select(bo2);
3260 ensureSelectionVisible();
3266 void MapEditor::selectLastBranch()
3268 BranchObj *bo1=xelection.getBranch();
3273 par=(BranchObj*)(bo1->getParObj());
3275 bo2=par->getLastBranch();
3278 xelection.select(bo2);
3280 ensureSelectionVisible();
3286 void MapEditor::selectMapBackgroundImage ()
3288 Q3FileDialog *fd=new Q3FileDialog( this);
3289 fd->setMode (Q3FileDialog::ExistingFile);
3290 fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
3291 ImagePreview *p =new ImagePreview (fd);
3292 fd->setContentsPreviewEnabled( TRUE );
3293 fd->setContentsPreview( p, p );
3294 fd->setPreviewMode( Q3FileDialog::Contents );
3295 fd->setCaption(vymName+" - " +tr("Load background image"));
3296 fd->setDir (lastImageDir);
3299 if ( fd->exec() == QDialog::Accepted )
3301 // TODO selectMapBackgroundImg in QT4 use: lastImageDir=fd->directory();
3302 lastImageDir=QDir (fd->dirPath());
3303 setMapBackgroundImage (fd->selectedFile());
3307 void MapEditor::setMapBackgroundImage (const QString &fn) //FIXME missing savestate
3309 QColor oldcol=mapScene->backgroundBrush().color();
3313 QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
3315 QString ("setMapBackgroundImage (%1)").arg(col.name()),
3316 QString("Set background color of map to %1").arg(col.name()));
3319 brush.setTextureImage (QPixmap (fn));
3320 mapScene->setBackgroundBrush(brush);
3323 void MapEditor::selectMapBackgroundColor()
3325 QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), this );
3326 if ( !col.isValid() ) return;
3327 setMapBackgroundColor( col );
3331 void MapEditor::setMapBackgroundColor(QColor col)
3333 QColor oldcol=mapScene->backgroundBrush().color();
3335 QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
3336 QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
3337 QString("Set background color of map to %1").arg(col.name()));
3338 mapScene->setBackgroundBrush(col);
3341 QColor MapEditor::getMapBackgroundColor()
3343 return mapScene->backgroundBrush().color();
3346 QColor MapEditor::getCurrentHeadingColor()
3348 BranchObj *bo=xelection.getBranch();
3349 if (bo) return bo->getColor();
3351 QMessageBox::warning(0,tr("Warning"),tr("Can't get color of heading,\nthere's no branch selected"));
3355 void MapEditor::colorBranch (QColor c)
3357 BranchObj *bo=xelection.getBranch();
3362 QString ("colorBranch (\"%1\")").arg(bo->getColor().name()),
3364 QString ("colorBranch (\"%1\")").arg(c.name()),
3365 QString("Set color of %1 to %2").arg(getName(bo)).arg(c.name())
3367 bo->setColor(c); // color branch
3371 void MapEditor::colorSubtree (QColor c)
3373 BranchObj *bo=xelection.getBranch();
3376 saveStateChangingPart(
3379 QString ("colorSubtree (\"%1\")").arg(c.name()),
3380 QString ("Set color of %1 and childs to %2").arg(getName(bo)).arg(c.name())
3382 bo->setColorSubtree (c); // color links, color childs
3387 void MapEditor::toggleStandardFlag(QString f)
3389 BranchObj *bo=xelection.getBranch();
3393 if (bo->isSetStandardFlag(f))
3405 QString("%1 (\"%2\")").arg(u).arg(f),
3407 QString("%1 (\"%2\")").arg(r).arg(f),
3408 QString("Toggling standard flag \"%1\" of %2").arg(f).arg(getName(bo)));
3409 bo->toggleStandardFlag (f,mainWindow->useFlagGroups());
3415 BranchObj* MapEditor::findText (QString s, bool cs)
3417 QTextDocument::FindFlags flags=0;
3418 if (cs) flags=QTextDocument::FindCaseSensitively;
3421 { // Nothing found or new find process
3423 // nothing found, start again
3425 itFind=model->first();
3427 bool searching=true;
3428 bool foundNote=false;
3429 while (searching && !EOFind)
3433 // Searching in Note
3434 if (itFind->getNote().contains(s,cs))
3436 if (xelection.single()!=itFind)
3438 xelection.select(itFind);
3439 ensureSelectionVisible();
3441 if (textEditor->findText(s,flags))
3447 // Searching in Heading
3448 if (searching && itFind->getHeading().contains (s,cs) )
3450 xelection.select(itFind);
3451 ensureSelectionVisible();
3457 itFind=model->next(itFind);
3458 if (!itFind) EOFind=true;
3460 //cout <<"still searching... "<<qPrintable( itFind->getHeading())<<endl;
3463 return xelection.getBranch();
3468 void MapEditor::findReset()
3469 { // Necessary if text to find changes during a find process
3473 void MapEditor::setURL(const QString &url)
3475 BranchObj *bo=xelection.getBranch();
3478 QString oldurl=bo->getURL();
3482 QString ("setURL (\"%1\")").arg(oldurl),
3484 QString ("setURL (\"%1\")").arg(url),
3485 QString ("set URL of %1 to %2").arg(getName(bo)).arg(url)
3488 model->reposition();
3490 ensureSelectionVisible();
3494 void MapEditor::editURL()
3496 BranchObj *bo=xelection.getBranch();
3500 QString text = QInputDialog::getText(
3501 "VYM", tr("Enter URL:"), QLineEdit::Normal,
3502 bo->getURL(), &ok, this );
3504 // user entered something and pressed OK
3509 void MapEditor::editLocalURL()
3511 BranchObj *bo=xelection.getBranch();
3514 QStringList filters;
3515 filters <<"All files (*)";
3516 filters << tr("Text","Filedialog") + " (*.txt)";
3517 filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
3518 filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
3519 filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
3520 QFileDialog *fd=new QFileDialog( this,vymName+" - " +tr("Set URL to a local file"));
3521 fd->setFilters (filters);
3522 fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
3523 fd->setDirectory (lastFileDir);
3524 if (! bo->getVymLink().isEmpty() )
3525 fd->selectFile( bo->getURL() );
3528 if ( fd->exec() == QDialog::Accepted )
3530 lastFileDir=QDir (fd->directory().path());
3531 setURL (fd->selectedFile() );
3536 QString MapEditor::getURL()
3538 BranchObj *bo=xelection.getBranch();
3540 return bo->getURL();
3545 QStringList MapEditor::getURLs()
3548 BranchObj *bo=xelection.getBranch();
3554 if (!bo->getURL().isEmpty()) urls.append( bo->getURL());
3562 void MapEditor::editHeading2URL()
3564 BranchObj *bo=xelection.getBranch();
3566 setURL (bo->getHeading());
3569 void MapEditor::editBugzilla2URL()
3571 BranchObj *bo=xelection.getBranch();
3574 QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
3579 void MapEditor::editFATE2URL()
3581 BranchObj *bo=xelection.getBranch();
3584 QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
3587 "setURL (\""+bo->getURL()+"\")",
3589 "setURL (\""+url+"\")",
3590 QString("Use heading of %1 as link to FATE").arg(getName(bo))
3597 void MapEditor::editVymLink()
3599 BranchObj *bo=xelection.getBranch();
3602 QStringList filters;
3603 filters <<"VYM map (*.vym)";
3604 QFileDialog *fd=new QFileDialog( this,vymName+" - " +tr("Link to another map"));
3605 fd->setFilters (filters);
3606 fd->setCaption(vymName+" - " +tr("Link to another map"));
3607 fd->setDirectory (lastFileDir);
3608 if (! bo->getVymLink().isEmpty() )
3609 fd->selectFile( bo->getVymLink() );
3613 if ( fd->exec() == QDialog::Accepted )
3615 lastFileDir=QDir (fd->directory().path());
3618 "setVymLink (\""+bo->getVymLink()+"\")",
3620 "setVymLink (\""+fd->selectedFile()+"\")",
3621 QString("Set vymlink of %1 to %2").arg(getName(bo)).arg(fd->selectedFile())
3623 setVymLinkInt (fd->selectedFile() );
3628 void MapEditor::deleteVymLink()
3630 BranchObj *bo=xelection.getBranch();
3635 "setVymLink (\""+bo->getVymLink()+"\")",
3637 "setVymLink (\"\")",
3638 QString("Unset vymlink of %1").arg(getName(bo))
3640 bo->setVymLink ("" );
3642 model->reposition();
3647 void MapEditor::setHideExport(bool b)
3649 BranchObj *bo=xelection.getBranch();
3652 bo->setHideInExport (b);
3653 QString u= b ? "false" : "true";
3654 QString r=!b ? "false" : "true";
3658 QString ("setHideExport (%1)").arg(u),
3660 QString ("setHideExport (%1)").arg(r),
3661 QString ("Set HideExport flag of %1 to %2").arg(getName(bo)).arg (r)
3664 model->reposition();
3670 void MapEditor::toggleHideExport()
3672 BranchObj *bo=xelection.getBranch();
3674 setHideExport ( !bo->hideInExport() );
3677 QString MapEditor::getVymLink()
3679 BranchObj *bo=xelection.getBranch();
3681 return bo->getVymLink();
3687 QStringList MapEditor::getVymLinks()
3690 BranchObj *bo=xelection.getBranch();
3696 if (!bo->getVymLink().isEmpty()) links.append( bo->getVymLink());
3704 void MapEditor::deleteKeepChilds()
3706 BranchObj *bo=xelection.getBranch();
3710 par=(BranchObj*)(bo->getParObj());
3712 // Don't use this on mapcenter
3715 // Check if we have childs at all to keep
3716 if (bo->countBranches()==0)
3722 QPointF p=bo->getRelPos();
3723 saveStateChangingPart(
3726 "deleteKeepChilds ()",
3727 QString("Remove %1 and keep its childs").arg(getName(bo))
3730 QString sel=model->getSelectString(bo);
3732 par->removeBranchHere(bo);
3733 model->reposition();
3735 xelection.getBranch()->move2RelPos (p);
3736 model->reposition();
3740 void MapEditor::deleteChilds()
3742 BranchObj *bo=xelection.getBranch();
3745 saveStateChangingPart(
3749 QString( "Remove childs of branch %1").arg(getName(bo))
3752 model->reposition();
3756 void MapEditor::editMapInfo()
3758 ExtraInfoDialog dia;
3759 dia.setMapName (getFileName() );
3760 dia.setAuthor (model->getAuthor() );
3761 dia.setComment(model->getComment() );
3765 stats+=tr("%1 items on map\n","Info about map").arg (mapScene->items().size(),6);
3775 if (!bo->getNote().isEmpty() ) n++;
3776 f+= bo->countFloatImages();
3778 xl+=bo->countXLinks();
3781 stats+=QString ("%1 branches\n").arg (b-1,6);
3782 stats+=QString ("%1 xLinks \n").arg (xl,6);
3783 stats+=QString ("%1 notes\n").arg (n,6);
3784 stats+=QString ("%1 images\n").arg (f,6);
3785 dia.setStats (stats);
3787 // Finally show dialog
3788 if (dia.exec() == QDialog::Accepted)
3790 setMapAuthor (dia.getAuthor() );
3791 setMapComment (dia.getComment() );
3795 void MapEditor::ensureSelectionVisible()
3797 LinkableMapObj *lmo=xelection.single();
3798 if (lmo) ensureVisible (lmo->getBBox() );
3802 void MapEditor::updateSelection()
3804 // Tell selection to update geometries
3808 void MapEditor::updateActions()
3810 // Tell mainwindow to update states of actions
3811 mainWindow->updateActions();
3812 // TODO maybe don't update if blockReposition is set
3815 void MapEditor::updateNoteFlag()
3818 BranchObj *bo=xelection.getBranch();
3821 bo->updateNoteFlag();
3822 mainWindow->updateActions();
3826 void MapEditor::setMapAuthor (const QString &s)
3829 QString ("setMapAuthor (\"%1\")").arg(model->getAuthor()),
3830 QString ("setMapAuthor (\"%1\")").arg(s),
3831 QString ("Set author of map to \"%1\"").arg(s)
3833 model->setAuthor (s);
3836 void MapEditor::setMapComment (const QString &s)
3839 QString ("setMapComment (\"%1\")").arg(model->getComment()),
3840 QString ("setMapComment (\"%1\")").arg(s),
3841 QString ("Set comment of map")
3843 model->setComment (s);
3846 void MapEditor::setMapLinkStyle (const QString & s)
3849 if (linkstyle==LinkableMapObj::Line)
3851 else if (linkstyle==LinkableMapObj::Parabel)
3852 snow="StyleParabel";
3853 else if (linkstyle==LinkableMapObj::PolyLine)
3854 snow="StylePolyLine";
3855 else if (linkstyle==LinkableMapObj::PolyParabel)
3856 snow="StyleParabel";
3859 QString("setMapLinkStyle (\"%1\")").arg(s),
3860 QString("setMapLinkStyle (\"%1\")").arg(snow),
3861 QString("Set map link style (\"%1\")").arg(s)
3865 linkstyle=LinkableMapObj::Line;
3866 else if (s=="StyleParabel")
3867 linkstyle=LinkableMapObj::Parabel;
3868 else if (s=="StylePolyLine")
3869 linkstyle=LinkableMapObj::PolyLine;
3871 linkstyle=LinkableMapObj::PolyParabel;
3878 bo->setLinkStyle(bo->getDefLinkStyle());
3881 model->reposition();
3884 LinkableMapObj::Style MapEditor::getMapLinkStyle ()
3889 void MapEditor::setMapDefLinkColor(QColor c)
3902 void MapEditor::setMapLinkColorHintInt()
3904 // called from setMapLinkColorHint(lch) or at end of parse
3914 void MapEditor::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
3917 setMapLinkColorHintInt();
3920 void MapEditor::toggleMapLinkColorHint()
3922 if (linkcolorhint==LinkableMapObj::HeadingColor)
3923 linkcolorhint=LinkableMapObj::DefaultColor;
3925 linkcolorhint=LinkableMapObj::HeadingColor;
3935 LinkableMapObj::ColorHint MapEditor::getMapLinkColorHint()
3937 return linkcolorhint;
3940 QColor MapEditor::getMapDefLinkColor()
3942 return defLinkColor;
3945 void MapEditor::setMapDefXLinkColor(QColor col)
3950 QColor MapEditor::getMapDefXLinkColor()
3952 return defXLinkColor;
3955 void MapEditor::setMapDefXLinkWidth (int w)
3960 int MapEditor::getMapDefXLinkWidth()
3962 return defXLinkWidth;
3965 void MapEditor::selectMapLinkColor()
3967 QColor col = QColorDialog::getColor( defLinkColor, this );
3968 if ( !col.isValid() ) return;
3970 QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
3971 QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
3972 QString("Set map link color to %1").arg(col.name())
3974 setMapDefLinkColor( col );
3977 void MapEditor::selectMapSelectionColor()
3979 QColor col = QColorDialog::getColor( defLinkColor, this );
3980 setSelectionColor (col);
3983 void MapEditor::setSelectionColorInt (QColor col)
3985 if ( !col.isValid() ) return;
3986 xelection.setColor (col);
3989 void MapEditor::setSelectionColor(QColor col)
3991 if ( !col.isValid() ) return;
3993 QString("setSelectionColor (%1)").arg(xelection.getColor().name()),
3994 QString("setSelectionColor (%1)").arg(col.name()),
3995 QString("Set color of selection box to %1").arg(col.name())
3997 setSelectionColorInt (col);
4000 QColor MapEditor::getSelectionColor()
4002 return xelection.getColor();
4005 bool MapEditor::scrollBranch(BranchObj *bo)
4009 if (bo->isScrolled()) return false;
4010 if (bo->countBranches()==0) return false;
4011 if (bo->getDepth()==0) return false;
4017 QString ("%1 ()").arg(u),
4019 QString ("%1 ()").arg(r),
4020 QString ("%1 %2").arg(r).arg(getName(bo))
4030 bool MapEditor::unscrollBranch(BranchObj *bo)
4034 if (!bo->isScrolled()) return false;
4035 if (bo->countBranches()==0) return false;
4036 if (bo->getDepth()==0) return false;
4042 QString ("%1 ()").arg(u),
4044 QString ("%1 ()").arg(r),
4045 QString ("%1 %2").arg(r).arg(getName(bo))
4055 void MapEditor::toggleScroll()
4057 BranchObj *bo=xelection.getBranch();
4058 if (xelection.type()==Selection::Branch )
4060 if (bo->isScrolled())
4061 unscrollBranch (bo);
4067 void MapEditor::unscrollChilds()
4069 BranchObj *bo=xelection.getBranch();
4075 if (bo->isScrolled()) unscrollBranch (bo);
4081 FloatImageObj* MapEditor::loadFloatImageInt (QString fn)
4083 BranchObj *bo=xelection.getBranch();
4087 bo->addFloatImage();
4088 fio=bo->getLastFloatImage();
4090 model->reposition();
4097 void MapEditor::loadFloatImage ()
4099 BranchObj *bo=xelection.getBranch();
4103 Q3FileDialog *fd=new Q3FileDialog( this);
4104 fd->setMode (Q3FileDialog::ExistingFiles);
4105 fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
4106 ImagePreview *p =new ImagePreview (fd);
4107 fd->setContentsPreviewEnabled( TRUE );
4108 fd->setContentsPreview( p, p );
4109 fd->setPreviewMode( Q3FileDialog::Contents );
4110 fd->setCaption(vymName+" - " +tr("Load image"));
4111 fd->setDir (lastImageDir);
4114 if ( fd->exec() == QDialog::Accepted )
4116 // TODO loadFIO in QT4 use: lastImageDir=fd->directory();
4117 lastImageDir=QDir (fd->dirPath());
4120 for (int j=0; j<fd->selectedFiles().count(); j++)
4122 s=fd->selectedFiles().at(j);
4123 fio=loadFloatImageInt (s);
4126 (LinkableMapObj*)fio,
4129 QString ("loadImage (%1)").arg(s ),
4130 QString("Add image %1 to %2").arg(s).arg(getName(bo))
4133 // TODO loadFIO error handling
4134 qWarning ("Failed to load "+s);
4142 void MapEditor::saveFloatImageInt (FloatImageObj *fio, const QString &type, const QString &fn)
4144 fio->save (fn,type);
4147 void MapEditor::saveFloatImage ()
4149 FloatImageObj *fio=xelection.getFloatImage();
4152 QFileDialog *fd=new QFileDialog( this);
4153 fd->setFilters (imageIO.getFilters());
4154 fd->setCaption(vymName+" - " +tr("Save image"));
4155 fd->setFileMode( QFileDialog::AnyFile );
4156 fd->setDirectory (lastImageDir);
4157 // fd->setSelection (fio->getOriginalFilename());
4161 if ( fd->exec() == QDialog::Accepted && fd->selectedFiles().count()==1)
4163 fn=fd->selectedFiles().at(0);
4164 if (QFile (fn).exists() )
4166 QMessageBox mb( vymName,
4167 tr("The file %1 exists already.\n"
4168 "Do you want to overwrite it?").arg(fn),
4169 QMessageBox::Warning,
4170 QMessageBox::Yes | QMessageBox::Default,
4171 QMessageBox::Cancel | QMessageBox::Escape,
4172 QMessageBox::NoButton );
4174 mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
4175 mb.setButtonText( QMessageBox::No, tr("Cancel"));
4178 case QMessageBox::Yes:
4181 case QMessageBox::Cancel:
4188 saveFloatImageInt (fio,fd->selectedFilter(),fn );
4194 void MapEditor::setFrameType(const FrameObj::FrameType &t)
4196 BranchObj *bo=xelection.getBranch();
4199 QString s=bo->getFrameTypeName();
4200 bo->setFrameType (t);
4201 saveState (bo, QString("setFrameType (\"%1\")").arg(s),
4202 bo, QString ("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),QString ("set type of frame to %1").arg(s));
4203 model->reposition();
4208 void MapEditor::setFrameType(const QString &s)
4210 BranchObj *bo=xelection.getBranch();
4213 saveState (bo, QString("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),
4214 bo, QString ("setFrameType (\"%1\")").arg(s),QString ("set type of frame to %1").arg(s));
4215 bo->setFrameType (s);
4216 model->reposition();
4221 void MapEditor::setFramePenColor(const QColor &c)
4223 BranchObj *bo=xelection.getBranch();
4226 saveState (bo, QString("setFramePenColor (\"%1\")").arg(bo->getFramePenColor().name() ),
4227 bo, QString ("setFramePenColor (\"%1\")").arg(c.name() ),QString ("set pen color of frame to %1").arg(c.name() ));
4228 bo->setFramePenColor (c);
4232 void MapEditor::setFrameBrushColor(const QColor &c)
4234 BranchObj *bo=xelection.getBranch();
4237 saveState (bo, QString("setFrameBrushColor (\"%1\")").arg(bo->getFrameBrushColor().name() ),
4238 bo, QString ("setFrameBrushColor (\"%1\")").arg(c.name() ),QString ("set brush color of frame to %1").arg(c.name() ));
4239 bo->setFrameBrushColor (c);
4243 void MapEditor::setFramePadding (const int &i)
4245 BranchObj *bo=xelection.getBranch();
4248 saveState (bo, QString("setFramePadding (\"%1\")").arg(bo->getFramePadding() ),
4249 bo, QString ("setFramePadding (\"%1\")").arg(i),QString ("set brush color of frame to %1").arg(i));
4250 bo->setFramePadding (i);
4251 model->reposition();
4256 void MapEditor::setFrameBorderWidth(const int &i)
4258 BranchObj *bo=xelection.getBranch();
4261 saveState (bo, QString("setFrameBorderWidth (\"%1\")").arg(bo->getFrameBorderWidth() ),
4262 bo, QString ("setFrameBorderWidth (\"%1\")").arg(i),QString ("set border width of frame to %1").arg(i));
4263 bo->setFrameBorderWidth (i);
4264 model->reposition();
4269 void MapEditor::setIncludeImagesVer(bool b)
4271 BranchObj *bo=xelection.getBranch();
4274 QString u= b ? "false" : "true";
4275 QString r=!b ? "false" : "true";
4279 QString("setIncludeImagesVertically (%1)").arg(u),
4281 QString("setIncludeImagesVertically (%1)").arg(r),
4282 QString("Include images vertically in %1").arg(getName(bo))
4284 bo->setIncludeImagesVer(b);
4285 model->reposition();
4289 void MapEditor::setIncludeImagesHor(bool b)
4291 BranchObj *bo=xelection.getBranch();
4294 QString u= b ? "false" : "true";
4295 QString r=!b ? "false" : "true";
4299 QString("setIncludeImagesHorizontally (%1)").arg(u),
4301 QString("setIncludeImagesHorizontally (%1)").arg(r),
4302 QString("Include images horizontally in %1").arg(getName(bo))
4304 bo->setIncludeImagesHor(b);
4305 model->reposition();
4309 void MapEditor::setHideLinkUnselected (bool b)
4311 LinkableMapObj *sel=xelection.single();
4313 (xelection.type() == Selection::Branch ||
4314 xelection.type() == Selection::MapCenter ||
4315 xelection.type() == Selection::FloatImage ))
4317 QString u= b ? "false" : "true";
4318 QString r=!b ? "false" : "true";
4322 QString("setHideLinkUnselected (%1)").arg(u),
4324 QString("setHideLinkUnselected (%1)").arg(r),
4325 QString("Hide link of %1 if unselected").arg(getName(sel))
4327 sel->setHideLinkUnselected(b);
4331 void MapEditor::importDirInt(BranchObj *dst, QDir d)
4333 BranchObj *bo=xelection.getBranch();
4336 // Traverse directories
4337 d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
4338 QFileInfoList list = d.entryInfoList();
4341 for (int i = 0; i < list.size(); ++i)
4344 if (fi.fileName() != "." && fi.fileName() != ".." )
4347 bo=dst->getLastBranch();
4348 bo->setHeading (fi.fileName() );
4349 bo->setColor (QColor("blue"));
4351 if ( !d.cd(fi.fileName()) )
4352 QMessageBox::critical (0,tr("Critical Import Error"),tr("Cannot find the directory %1").arg(fi.fileName()));
4355 // Recursively add subdirs
4356 importDirInt (bo,d);
4362 d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
4363 list = d.entryInfoList();
4365 for (int i = 0; i < list.size(); ++i)
4369 bo=dst->getLastBranch();
4370 bo->setHeading (fi.fileName() );
4371 bo->setColor (QColor("black"));
4372 if (fi.fileName().right(4) == ".vym" )
4373 bo->setVymLink (fi.filePath());
4378 void MapEditor::importDirInt (const QString &s)
4380 BranchObj *bo=xelection.getBranch();
4383 saveStateChangingPart (bo,bo,QString ("importDir (\"%1\")").arg(s),QString("Import directory structure from %1").arg(s));
4386 importDirInt (bo,d);
4390 void MapEditor::importDir()
4392 BranchObj *bo=xelection.getBranch();
4395 QStringList filters;
4396 filters <<"VYM map (*.vym)";
4397 QFileDialog *fd=new QFileDialog( this,vymName+ " - " +tr("Choose directory structure to import"));
4398 fd->setMode (QFileDialog::DirectoryOnly);
4399 fd->setFilters (filters);
4400 fd->setCaption(vymName+" - " +tr("Choose directory structure to import"));
4404 if ( fd->exec() == QDialog::Accepted )
4406 importDirInt (fd->selectedFile() );
4407 model->reposition();
4413 void MapEditor::followXLink(int i)
4415 BranchObj *bo=xelection.getBranch();
4418 bo=bo->XLinkTargetAt(i);
4421 xelection.select(bo);
4422 ensureSelectionVisible();
4427 void MapEditor::editXLink(int i) // FIXME missing saveState
4429 BranchObj *bo=xelection.getBranch();
4432 XLinkObj *xlo=bo->XLinkAt(i);
4435 EditXLinkDialog dia;
4437 dia.setSelection(bo);
4438 if (dia.exec() == QDialog::Accepted)
4440 if (dia.useSettingsGlobal() )
4442 setMapDefXLinkColor (xlo->getColor() );
4443 setMapDefXLinkWidth (xlo->getWidth() );
4445 if (dia.deleteXLink())
4446 bo->deleteXLinkAt(i);
4452 AttributeTable* MapEditor::attributeTable()
4457 void MapEditor::testFunction1()
4459 BranchObj *bo=xelection.getBranch();
4460 if (bo) model->moveAway (bo);
4462 /* TODO Hide hidden stuff temporary, maybe add this as regular function somewhere
4463 if (hidemode==HideNone)
4465 setHideTmpMode (HideExport);
4466 mapCenter->calcBBoxSizeWithChilds();
4467 QRectF totalBBox=mapCenter->getTotalBBox();
4468 QRectF mapRect=totalBBox;
4469 QCanvasRectangle *frame=NULL;
4471 cout << " map has =("<<totalBBox.x()<<","<<totalBBox.y()<<","<<totalBBox.width()<<","<<totalBBox.height()<<")\n";
4473 mapRect.setRect (totalBBox.x(), totalBBox.y(),
4474 totalBBox.width(), totalBBox.height());
4475 frame=new QCanvasRectangle (mapRect,mapScene);
4476 frame->setBrush (QColor(white));
4477 frame->setPen (QColor(black));
4478 frame->setZValue(0);
4483 setHideTmpMode (HideNone);
4485 cout <<" hidemode="<<hidemode<<endl;
4489 void MapEditor::testFunction2()
4494 if (hidemode==HideExport)
4495 setHideTmpMode (HideNone);
4497 setHideTmpMode (HideExport);
4501 void MapEditor::contextMenuEvent ( QContextMenuEvent * e )
4503 // Lineedits are already closed by preceding
4504 // mouseEvent, we don't need to close here.
4506 QPointF p = mapToScene(e->pos());
4507 LinkableMapObj* lmo=model->findMapObj(p, NULL);
4510 { // MapObj was found
4511 if (xelection.single() != lmo)
4513 // select the MapObj
4514 xelection.select(lmo);
4517 if (xelection.getBranch() )
4519 // Context Menu on branch or mapcenter
4521 branchContextMenu->popup(e->globalPos() );
4524 if (xelection.getFloatImage() )
4526 // Context Menu on floatimage
4528 floatimageContextMenu->popup(e->globalPos() );
4532 { // No MapObj found, we are on the Canvas itself
4533 // Context Menu on scene
4536 canvasContextMenu->popup(e->globalPos() );
4541 void MapEditor::keyPressEvent(QKeyEvent* e)
4543 if (e->modifiers() & Qt::ControlModifier)
4545 switch (mainWindow->getModMode())
4547 case Main::ModModeColor:
4548 setCursor (PickColorCursor);
4550 case Main::ModModeCopy:
4551 setCursor (CopyCursor);
4553 case Main::ModModeXLink:
4554 setCursor (XLinkCursor);
4557 setCursor (Qt::ArrowCursor);
4563 void MapEditor::keyReleaseEvent(QKeyEvent* e)
4565 if (!(e->modifiers() & Qt::ControlModifier))
4566 setCursor (Qt::ArrowCursor);
4569 void MapEditor::mousePressEvent(QMouseEvent* e)
4571 // Ignore right clicks, these will go to context menus
4572 if (e->button() == Qt::RightButton )
4578 //Ignore clicks while editing heading
4579 if (isSelectBlocked() )
4585 QPointF p = mapToScene(e->pos());
4586 LinkableMapObj* lmo=model->findMapObj(p, NULL);
4590 //Take care of system flags _or_ modifier modes
4592 if (lmo && (typeid(*lmo)==typeid(BranchObj) ||
4593 typeid(*lmo)==typeid(MapCenterObj) ))
4595 QString foname=((BranchObj*)lmo)->getSystemFlagName(p);
4596 if (!foname.isEmpty())
4598 // systemFlag clicked
4602 if (e->state() & Qt::ControlModifier)
4603 mainWindow->editOpenURLTab();
4605 mainWindow->editOpenURL();
4607 else if (foname=="vymLink")
4609 mainWindow->editOpenVymLink();
4610 // tabWidget may change, better return now
4611 // before segfaulting...
4612 } else if (foname=="note")
4613 mainWindow->windowToggleNoteEditor();
4614 else if (foname=="hideInExport")
4621 // No system flag clicked, take care of modmodes (CTRL-Click)
4622 if (e->state() & Qt::ControlModifier)
4624 if (mainWindow->getModMode()==Main::ModModeColor)
4627 setCursor (PickColorCursor);
4630 if (mainWindow->getModMode()==Main::ModModeXLink)
4632 BranchObj *bo_begin=NULL;
4634 bo_begin=(BranchObj*)(lmo);
4636 if (xelection.getBranch() )
4637 bo_begin=xelection.getBranch();
4641 linkingObj_src=bo_begin;
4642 tmpXLink=new XLinkObj (mapScene);
4643 tmpXLink->setBegin (bo_begin);
4644 tmpXLink->setEnd (p);
4645 tmpXLink->setColor(defXLinkColor);
4646 tmpXLink->setWidth(defXLinkWidth);
4647 tmpXLink->updateXLink();
4648 tmpXLink->setVisibility (true);
4652 } // End of modmodes
4656 // Select the clicked object
4659 // Left Button Move Branches
4660 if (e->button() == Qt::LeftButton )
4662 //movingObj_start.setX( p.x() - selection->x() );// TODO replaced selection->lmo here
4663 //movingObj_start.setY( p.y() - selection->y() );
4664 movingObj_start.setX( p.x() - lmo->x() );
4665 movingObj_start.setY( p.y() - lmo->y() );
4666 movingObj_orgPos.setX (lmo->x() );
4667 movingObj_orgPos.setY (lmo->y() );
4668 movingObj_orgRelPos=lmo->getRelPos();
4670 // If modMode==copy, then we want to "move" the _new_ object around
4671 // then we need the offset from p to the _old_ selection, because of tmp
4672 if (mainWindow->getModMode()==Main::ModModeCopy &&
4673 e->state() & Qt::ControlModifier)
4675 BranchObj *bo=xelection.getBranch();
4679 bo->addBranch ((BranchObj*)xelection.single());
4681 xelection.select(bo->getLastBranch());
4682 model->reposition();
4686 movingObj=xelection.single();
4688 // Middle Button Toggle Scroll
4689 // (On Mac OS X this won't work, but we still have
4690 // a button in the toolbar)
4691 if (e->button() == Qt::MidButton )
4696 { // No MapObj found, we are on the scene itself
4697 // Left Button move Pos of sceneView
4698 if (e->button() == Qt::LeftButton )
4700 movingObj=NULL; // move Content not Obj
4701 movingObj_start=e->globalPos();
4702 movingCont_start=QPointF (
4703 horizontalScrollBar()->value(),
4704 verticalScrollBar()->value());
4705 movingVec=QPointF(0,0);
4706 setCursor(HandOpenCursor);
4711 void MapEditor::mouseMoveEvent(QMouseEvent* e)
4713 QPointF p = mapToScene(e->pos());
4714 LinkableMapObj *lmosel=xelection.single();
4716 // Move the selected MapObj
4717 if ( lmosel && movingObj)
4719 // reset cursor if we are moving and don't copy
4720 if (mainWindow->getModMode()!=Main::ModModeCopy)
4721 setCursor (Qt::ArrowCursor);
4723 // To avoid jumping of the sceneView, only
4724 // ensureSelectionVisible, if not tmp linked
4725 if (!lmosel->hasParObjTmp())
4726 ensureSelectionVisible ();
4728 // Now move the selection, but add relative position
4729 // (movingObj_start) where selection was chosen with
4730 // mousepointer. (This avoids flickering resp. jumping
4731 // of selection back to absPos)
4733 // Check if we could link
4734 LinkableMapObj* lmo=model->findMapObj(p, lmosel);
4737 FloatObj *fio=xelection.getFloatImage();
4740 fio->move (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4742 fio->updateLink(); //no need for reposition, if we update link here
4745 // Relink float to new mapcenter or branch, if shift is pressed
4746 // Only relink, if selection really has a new parent
4747 if ( (e->modifiers()==Qt::ShiftModifier) && lmo &&
4748 ( (typeid(*lmo)==typeid(BranchObj)) ||
4749 (typeid(*lmo)==typeid(MapCenterObj)) ) &&
4750 ( lmo != fio->getParObj())
4753 if (typeid(*fio) == typeid(FloatImageObj) &&
4754 ( (typeid(*lmo)==typeid(BranchObj) ||
4755 typeid(*lmo)==typeid(MapCenterObj)) ))
4758 // Also save the move which was done so far
4759 QString pold=qpointfToString(movingObj_orgRelPos);
4760 QString pnow=qpointfToString(fio->getRelPos());
4766 QString("Move %1 to relative position %2").arg(getName(fio)).arg(pnow));
4767 fio->getParObj()->requestReposition();
4768 model->reposition();
4770 linkTo (model->getSelectString(lmo));
4772 //movingObj_orgRelPos=lmosel->getRelPos();
4774 model->reposition();
4778 { // selection != a FloatObj
4779 if (lmosel->getDepth()==0)
4782 if (e->buttons()== Qt::LeftButton && e->modifiers()==Qt::ShiftModifier)
4783 ((MapCenterObj*)lmosel)->moveAll(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4785 lmosel->move (p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4786 model->updateRelPositions();
4789 if (lmosel->getDepth()==1)
4792 lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4793 lmosel->setRelPos();
4796 // Move ordinary branch
4797 lmosel->move(p.x() -movingObj_start.x(), p.y()-movingObj_start.y() );
4800 // Maybe we can relink temporary?
4801 if (lmo && (lmo!=lmosel) && xelection.getBranch() &&
4802 (typeid(*lmo)==typeid(BranchObj) ||
4803 typeid(*lmo)==typeid(MapCenterObj)) )
4806 if (e->modifiers()==Qt::ControlModifier)
4808 // Special case: CTRL to link below lmo
4809 lmosel->setParObjTmp (lmo,p,+1);
4811 else if (e->modifiers()==Qt::ShiftModifier)
4812 lmosel->setParObjTmp (lmo,p,-1);
4814 lmosel->setParObjTmp (lmo,p,0);
4817 lmosel->unsetParObjTmp();
4819 // reposition subbranch
4820 lmosel->reposition();
4824 } // no FloatImageObj
4828 } // selection && moving_obj
4830 // Draw a link from one branch to another
4833 tmpXLink->setEnd (p);
4834 tmpXLink->updateXLink();
4838 if (!movingObj && !pickingColor &&!drawingLink && e->buttons() == Qt::LeftButton )
4840 QPointF p=e->globalPos();
4841 movingVec.setX(-p.x() + movingObj_start.x() );
4842 movingVec.setY(-p.y() + movingObj_start.y() );
4843 horizontalScrollBar()->setSliderPosition((int)( movingCont_start.x()+movingVec.x() ));
4844 verticalScrollBar()->setSliderPosition((int)( movingCont_start.y()+movingVec.y() ) );
4849 void MapEditor::mouseReleaseEvent(QMouseEvent* e)
4851 QPointF p = mapToScene(e->pos());
4852 LinkableMapObj *dst;
4853 LinkableMapObj *lmosel=xelection.single();
4854 // Have we been picking color?
4858 setCursor (Qt::ArrowCursor);
4859 // Check if we are over another branch
4860 dst=model->findMapObj(p, NULL);
4863 if (e->state() & Qt::ShiftModifier)
4864 colorBranch (((BranchObj*)dst)->getColor());
4866 colorSubtree (((BranchObj*)dst)->getColor());
4871 // Have we been drawing a link?
4875 // Check if we are over another branch
4876 dst=model->findMapObj(p, NULL);
4879 tmpXLink->setEnd ( ((BranchObj*)(dst)) );
4880 tmpXLink->updateXLink();
4881 tmpXLink->activate(); //FIXME savestate missing
4882 //saveStateComplete(QString("Activate xLink from %1 to %2").arg(getName(tmpXLink->getBegin())).arg(getName(tmpXLink->getEnd())) );
4891 // Have we been moving something?
4892 if ( lmosel && movingObj )
4894 FloatImageObj *fo=xelection.getFloatImage();
4897 // Moved FloatObj. Maybe we need to reposition
4898 QString pold=qpointfToString(movingObj_orgRelPos);
4899 QString pnow=qpointfToString(fo->getRelPos());
4905 QString("Move %1 to relative position %2").arg(getName(fo)).arg(pnow));
4907 fo->getParObj()->requestReposition();
4908 model->reposition();
4911 // Check if we are over another branch, but ignore
4912 // any found LMOs, which are FloatObjs
4913 dst=model->findMapObj(mapToScene(e->pos() ), lmosel);
4915 if (dst && (typeid(*dst)!=typeid(BranchObj) && typeid(*dst)!=typeid(MapCenterObj)))
4918 BranchObj *bo=xelection.getBranch();
4919 if (bo && bo->getDepth()==0)
4921 if (movingObj_orgPos != bo->getAbsPos())
4923 QString pold=qpointfToString(movingObj_orgPos);
4924 QString pnow=qpointfToString(bo->getAbsPos());
4930 QString("Move mapcenter %1 to position %2").arg(getName(bo)).arg(pnow));
4934 if (xelection.type() == Selection::Branch )
4935 { // A branch was moved
4937 // save the position in case we link to mapcenter
4938 QPointF savePos=QPointF (lmosel->getAbsPos() );
4940 // Reset the temporary drawn link to the original one
4941 lmosel->unsetParObjTmp();
4943 // For Redo we may need to save original selection
4944 QString preSelStr=model->getSelectString(lmosel);
4949 // We have a destination, relink to that
4951 BranchObj* bsel=xelection.getBranch();
4952 BranchObj* bdst=(BranchObj*)dst;
4954 QString preParStr=model->getSelectString (bsel->getParObj());
4955 QString preNum=QString::number (bsel->getNum(),10);
4956 QString preDstParStr;
4958 if (e->state() & Qt::ShiftModifier && dst->getParObj())
4960 preDstParStr=model->getSelectString (dst->getParObj());
4961 bsel->linkTo ( (BranchObj*)(bdst->getParObj()), bdst->getNum());
4963 if (e->state() & Qt::ControlModifier && dst->getParObj())
4966 preDstParStr=model->getSelectString (dst->getParObj());
4967 bsel->linkTo ( (BranchObj*)(bdst->getParObj()), bdst->getNum()+1);
4970 preDstParStr=model->getSelectString(dst);
4971 bsel->linkTo (bdst,-1);
4972 if (dst->getDepth()==0) bsel->move (savePos);
4974 QString postSelStr=model->getSelectString(lmosel);
4975 QString postNum=QString::number (bsel->getNum(),10);
4977 QString undoCom="linkTo (\""+
4978 preParStr+ "\"," + preNum +"," +
4979 QString ("%1,%2").arg(movingObj_orgPos.x()).arg(movingObj_orgPos.y())+ ")";
4981 QString redoCom="linkTo (\""+
4982 preDstParStr + "\"," + postNum + "," +
4983 QString ("%1,%2").arg(savePos.x()).arg(savePos.y())+ ")";
4988 QString("Relink %1 to %2").arg(getName(bsel)).arg(getName(dst)) );
4990 model->reposition(); // not necessary if we undo temporary move below
4993 // No destination, undo temporary move
4995 if (lmosel->getDepth()==1)
4997 // The select string might be different _after_ moving around.
4998 // Therefor reposition and then use string of old selection, too
4999 model->reposition();
5001 QPointF rp(lmosel->getRelPos());
5002 if (rp != movingObj_orgRelPos)
5004 QString ps=qpointfToString(rp);
5006 model->getSelectString(lmosel), "moveRel "+qpointfToString(movingObj_orgRelPos),
5007 preSelStr, "moveRel "+ps,
5008 QString("Move %1 to relative position %2").arg(getName(lmosel)).arg(ps));
5012 // Draw the original link, before selection was moved around
5013 if (settings.value("/animation/use",false).toBool() && lmosel->getDepth()>1)
5015 QPointF p=bo->getParObj()->getChildPos();
5016 lmosel->setRelPos(); // calc relPos first
5017 model->startAnimation(
5018 lmosel->getRelPos(),
5019 QPointF (movingObj_orgPos.x() - p.x(), movingObj_orgPos.y() - p.y() )
5022 model->reposition();
5026 // Finally resize scene, if needed
5030 // Just make sure, that actions are still ok,e.g. the move branch up/down buttons...
5033 // maybe we moved View: set old cursor
5034 setCursor (Qt::ArrowCursor);
5038 void MapEditor::mouseDoubleClickEvent(QMouseEvent* e)
5040 if (isSelectBlocked() )
5046 if (e->button() == Qt::LeftButton )
5048 QPointF p = mapToScene(e->pos());
5049 LinkableMapObj *lmo=model->findMapObj(p, NULL);
5050 if (lmo) { // MapObj was found
5051 // First select the MapObj than edit heading
5052 xelection.select(lmo);
5053 mainWindow->editHeading();
5058 void MapEditor::resizeEvent (QResizeEvent* e)
5060 QGraphicsView::resizeEvent( e );
5063 void MapEditor::dragEnterEvent(QDragEnterEvent *event)
5065 //for (unsigned int i=0;event->format(i);i++) // Debug mime type
5066 // cerr << event->format(i) << endl;
5068 if (event->mimeData()->hasImage())
5069 event->acceptProposedAction();
5071 if (event->mimeData()->hasUrls())
5072 event->acceptProposedAction();
5075 void MapEditor::dragMoveEvent(QDragMoveEvent *)
5079 void MapEditor::dragLeaveEvent(QDragLeaveEvent *event)
5084 void MapEditor::dropEvent(QDropEvent *event)
5086 BranchObj *sel=xelection.getBranch();
5090 foreach (QString format,event->mimeData()->formats())
5091 cout << "MapEditor: Dropped format: "<<qPrintable (format)<<endl;
5095 if (event->mimeData()->hasImage())
5097 QVariant imageData = event->mimeData()->imageData();
5098 addFloatImageInt (qvariant_cast<QPixmap>(imageData));
5100 if (event->mimeData()->hasUrls())
5101 uris=event->mimeData()->urls();
5109 for (int i=0; i<uris.count();i++)
5111 // Workaround to avoid adding empty branches
5112 if (!uris.at(i).toString().isEmpty())
5114 bo=sel->addBranch();
5117 s=uris.at(i).toLocalFile();
5120 QString file = QDir::fromNativeSeparators(s);
5121 heading = QFileInfo(file).baseName();
5123 if (file.endsWith(".vym", false))
5124 bo->setVymLink(file);
5126 bo->setURL(uris.at(i).toString());
5129 bo->setURL(uris.at(i).toString());
5132 if (!heading.isEmpty())
5133 bo->setHeading(heading);
5135 bo->setHeading(uris.at(i).toString());
5139 model->reposition();
5142 event->acceptProposedAction();
5146 void MapEditor::sendSelection()
5148 if (netstate!=Server) return;
5149 sendData (QString("select (\"%1\")").arg(xelection.getSelectString()) );
5152 void MapEditor::newServer()
5156 tcpServer = new QTcpServer(this);
5157 if (!tcpServer->listen(QHostAddress::Any,port)) {
5158 QMessageBox::critical(this, "vym server",
5159 QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
5163 connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
5165 cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
5168 void MapEditor::connectToServer()
5171 server="salam.suse.de";
5173 clientSocket = new QTcpSocket (this);
5174 clientSocket->abort();
5175 clientSocket->connectToHost(server ,port);
5176 connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
5177 connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
5178 this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
5180 cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
5185 void MapEditor::newClient()
5187 QTcpSocket *newClient = tcpServer->nextPendingConnection();
5188 connect(newClient, SIGNAL(disconnected()),
5189 newClient, SLOT(deleteLater()));
5191 cout <<"ME::newClient at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
5193 clientList.append (newClient);
5197 void MapEditor::sendData(const QString &s)
5199 if (clientList.size()==0) return;
5201 // Create bytearray to send
5203 QDataStream out(&block, QIODevice::WriteOnly);
5204 out.setVersion(QDataStream::Qt_4_0);
5206 // Reserve some space for blocksize
5209 // Write sendCounter
5210 out << sendCounter++;
5215 // Go back and write blocksize so far
5216 out.device()->seek(0);
5217 quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
5221 cout << "ME::sendData bs="<<bs<<" counter="<<sendCounter<<" s="<<qPrintable(s)<<endl;
5223 for (int i=0; i<clientList.size(); ++i)
5225 //cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
5226 clientList.at(i)->write (block);
5230 void MapEditor::readData ()
5232 while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
5235 cout <<"readData bytesAvail="<<clientSocket->bytesAvailable();
5239 QDataStream in(clientSocket);
5240 in.setVersion(QDataStream::Qt_4_0);
5248 cout << " t="<<qPrintable (t)<<endl;
5254 void MapEditor::displayNetworkError(QAbstractSocket::SocketError socketError)
5256 switch (socketError) {
5257 case QAbstractSocket::RemoteHostClosedError:
5259 case QAbstractSocket::HostNotFoundError:
5260 QMessageBox::information(this, vymName +" Network client",
5261 "The host was not found. Please check the "
5262 "host name and port settings.");
5264 case QAbstractSocket::ConnectionRefusedError:
5265 QMessageBox::information(this, vymName + " Network client",
5266 "The connection was refused by the peer. "
5267 "Make sure the fortune server is running, "
5268 "and check that the host name and port "
5269 "settings are correct.");
5272 QMessageBox::information(this, vymName + " Network client",
5273 QString("The following error occurred: %1.")
5274 .arg(clientSocket->errorString()));
5278 void MapEditor::autosave()
5280 QDateTime now=QDateTime().currentDateTime();
5282 cout << "ME::autosave checking "<<qPrintable(filePath)<<"...\n";
5283 cout << "fsaved: "<<qPrintable (fileChangedTime.toString())<<endl;
5284 cout << " fnow: "<<qPrintable (QFileInfo(filePath).lastModified().toString())<<endl;
5285 cout << " time: "<<qPrintable (now.toString())<<endl;
5286 cout << " zipped="<<zipped<<endl;
5288 // Disable autosave, while we have gone back in history
5289 int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
5290 if (redosAvail>0) return;
5292 // Also disable autosave for new map without filename
5293 if (filePath.isEmpty()) return;
5296 if (mapUnsaved &&mapChanged && settings.value ("/mapeditor/autosave/use",true).toBool() )
5298 if (QFileInfo(filePath).lastModified()<=fileChangedTime)
5299 mainWindow->fileSave (this);
5302 cout <<" ME::autosave rejected, file on disk is newer than last save.\n";
5306 void MapEditor::fileChanged()
5308 // Check if file on disk has changed meanwhile
5309 if (!filePath.isEmpty())
5311 QDateTime tmod=QFileInfo (filePath).lastModified();
5312 if (tmod>fileChangedTime)
5315 /* FIXME debug message, sometimes there's a glitch in the metrics...
5316 cout << "ME::fileChanged()\n"
5317 << " last saved: "<<qPrintable (fileChangedTime.toString())<<endl
5318 << " last modififed: "<<qPrintable (tmod.toString())<<endl;
5320 // FIXME switch to current mapeditor and finish lineedits...
5321 QMessageBox mb( vymName,
5322 tr("The file of the map on disk has changed:\n\n"
5323 " %1\n\nDo you want to reload that map with the new file?").arg(filePath),
5324 QMessageBox::Question,
5326 QMessageBox::Cancel | QMessageBox::Default,
5327 QMessageBox::NoButton );
5329 mb.setButtonText( QMessageBox::Yes, tr("Reload"));
5330 mb.setButtonText( QMessageBox::No, tr("Ignore"));
5333 case QMessageBox::Yes:
5335 load (filePath,NewMap,fileType);
5336 case QMessageBox::Cancel:
5337 fileChangedTime=tmod; // allow autosave to overwrite newer file!
5345 /*TODO not needed? void MapEditor::contentsDropEvent(QDropEvent *event)
5348 } else if (event->provides("application/x-moz-file-promise-url") &&
5349 event->provides("application/x-moz-nativeimage"))
5351 // Contains url to the img src in unicode16
5352 QByteArray d = event->encodedData("application/x-moz-file-promise-url");
5353 QString url = QString((const QChar*)d.data(),d.size()/2);
5357 } else if (event->provides ("text/uri-list"))
5358 { // Uris provided e.g. by konqueror
5359 Q3UriDrag::decode (event,uris);
5360 } else if (event->provides ("_NETSCAPE_URL"))
5361 { // Uris provided by Mozilla
5362 QStringList l = QStringList::split("\n", event->encodedData("_NETSCAPE_URL"));
5365 } else if (event->provides("text/html")) {
5367 // Handels text mime types
5368 // Look like firefox allways handle text as unicode16 (2 bytes per char.)
5369 QByteArray d = event->encodedData("text/html");
5372 text = QString((const QChar*)d.data(),d.size()/2);
5376 textEditor->setText(text);
5380 } else if (event->provides("text/plain")) {
5381 QByteArray d = event->encodedData("text/plain");
5384 text = QString((const QChar*)d.data(),d.size()/2);
5388 textEditor->setText(text);
5398 bool isUnicode16(const QByteArray &d)
5400 // TODO: make more precise check for unicode 16.
5401 // Guess unicode16 if any of second bytes are zero
5402 unsigned int length = max(0,d.size()-2)/2;
5403 for (unsigned int i = 0; i<length ; i++)
5404 if (d.at(i*2+1)==0) return true;
5408 void MapEditor::addFloatImageInt (const QPixmap &img)
5410 BranchObj *bo=xelection.getBranch();
5413 FloatImageObj *fio=bo->addFloatImage();
5415 fio->setOriginalFilename("No original filename (image added by dropevent)");
5416 QString s=model->getSelectString(bo);
5417 saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",fio );
5418 saveState (fio,"delete ()", bo,QString("paste(%1)").arg(curStep),"Pasting dropped image");
5419 model->reposition();
5426 void MapEditor::imageDataFetched(const QByteArray &a, Q3NetworkOperation * / *nop* /)
5428 if (!imageBuffer) imageBuffer = new QBuffer();
5429 if (!imageBuffer->isOpen()) {
5430 imageBuffer->open(QIODevice::WriteOnly | QIODevice::Append);
5432 imageBuffer->at(imageBuffer->at()+imageBuffer->writeBlock(a));
5436 void MapEditor::imageDataFinished(Q3NetworkOperation *nop)
5438 if (nop->state()==Q3NetworkProtocol::StDone) {
5439 QPixmap img(imageBuffer->buffer());
5440 addFloatImageInt (img);
5444 imageBuffer->close();
5446 imageBuffer->close();
5453 void MapEditor::fetchImage(const QString &url)
5456 urlOperator->stop();
5457 disconnect(urlOperator);
5461 urlOperator = new Q3UrlOperator(url);
5462 connect(urlOperator, SIGNAL(finished(Q3NetworkOperation *)),
5463 this, SLOT(imageDataFinished(Q3NetworkOperation*)));
5465 connect(urlOperator, SIGNAL(data(const QByteArray &, Q3NetworkOperation *)),
5466 this, SLOT(imageDataFetched(const QByteArray &, Q3NetworkOperation *)));