1 #include <QApplication>
6 #include "editxlinkdialog.h"
8 #include "exportxhtmldialog.h"
10 #include "geometry.h" // for addBBox
11 #include "mainwindow.h"
12 #include "mapcenterobj.h"
15 #include "selection.h"
18 #include "warningdialog.h"
19 #include "xml-freemind.h"
25 extern Main *mainWindow;
26 extern Settings settings;
27 extern QString tmpVymDir;
29 extern TextEditor *textEditor;
31 extern QString clipboardDir;
32 extern QString clipboardFile;
33 extern bool clipboardEmpty;
35 extern ImageIO imageIO;
37 extern QString vymName;
38 extern QString vymVersion;
39 extern QDir vymBaseDir;
41 extern QDir lastImageDir;
42 extern QDir lastFileDir;
44 extern FlagRowObj *standardFlagsDefault;
46 extern Settings settings;
50 int VymModel::mapNum=0; // make instance
54 // cout << "Const VymModel\n";
61 // cout << "Destr VymModel\n";
62 autosaveTimer->stop();
63 fileChangedTimer->stop();
67 void VymModel::clear()
69 cout << "VymModel::clear rows="<<rowCount(index(rootItem))<<endl;
70 selModel->clearSelection();
73 while (!mapCenters.isEmpty()) // FIXME VM needs to be in treemodel only...
74 delete mapCenters.takeFirst();
76 QModelIndex ri=index(rootItem);
77 removeRows (0, rowCount(ri),ri);
80 void VymModel::init ()
82 // We should have at least one map center to start with
83 // addMapCenter(); FIXME VM create this in MapEditor as long as model is part of that
88 // Also no scene yet (should not be needed anyway) FIXME VM
101 stepsTotal=settings.readNumEntry("/history/stepsTotal",100);
102 undoSet.setEntry ("/history/stepsTotal",QString::number(stepsTotal));
103 mainWindow->updateHistory (undoSet);
106 makeTmpDirectories();
111 fileName=tr("unnamed");
113 blockReposition=false;
114 blockSaveState=false;
116 autosaveTimer=new QTimer (this);
117 connect(autosaveTimer, SIGNAL(timeout()), this, SLOT(autosave()));
119 fileChangedTimer=new QTimer (this);
120 fileChangedTimer->start(3000);
121 connect(fileChangedTimer, SIGNAL(timeout()), this, SLOT(fileChanged()));
132 animationUse=settings.readBoolEntry("/animation/use",false);
133 animationTicks=settings.readNumEntry("/animation/ticks",10);
134 animationInterval=settings.readNumEntry("/animation/interval",50);
136 animationTimer=new QTimer (this);
137 connect(animationTimer, SIGNAL(timeout()), this, SLOT(animate()));
140 defLinkColor=QColor (0,0,255);
141 defXLinkColor=QColor (180,180,180);
142 linkcolorhint=LinkableMapObj::DefaultColor;
143 linkstyle=LinkableMapObj::PolyParabel;
145 defXLinkColor=QColor (230,230,230);
155 // addMapCenter(); FIXME VM create this in MapEditor until BO and MCO are independent of scene
159 void VymModel::makeTmpDirectories()
161 // Create unique temporary directories
162 tmpMapDir = tmpVymDir+QString("/model-%1").arg(mapNum);
163 histPath = tmpMapDir+"/history";
169 MapEditor* VymModel::getMapEditor() // FIXME VM better return favourite editor here
174 bool VymModel::isRepositionBlocked()
176 return blockReposition;
179 void VymModel::updateActions() // FIXME maybe don't update if blockReposition is set
181 // Tell mainwindow to update states of actions
182 mainWindow->updateActions();
187 QString VymModel::saveToDir(const QString &tmpdir, const QString &prefix, bool writeflags, const QPointF &offset, LinkableMapObj *saveSel)
189 // tmpdir temporary directory to which data will be written
190 // prefix mapname, which will be appended to images etc.
191 // writeflags Only write flags for "real" save of map, not undo
192 // offset offset of bbox of whole map in scene.
193 // Needed for XML export
202 case LinkableMapObj::Line:
205 case LinkableMapObj::Parabel:
208 case LinkableMapObj::PolyLine:
212 ls="StylePolyParabel";
216 QString s="<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE vymmap>\n";
218 if (linkcolorhint==LinkableMapObj::HeadingColor)
219 colhint=xml.attribut("linkColorHint","HeadingColor");
221 QString mapAttr=xml.attribut("version",vymVersion);
223 mapAttr+= xml.attribut("author",author) +
224 xml.attribut("comment",comment) +
225 xml.attribut("date",getDate()) +
226 xml.attribut("backgroundColor", mapScene->backgroundBrush().color().name() ) +
227 xml.attribut("selectionColor", mapEditor->getSelectionColor().name() ) +
228 xml.attribut("linkStyle", ls ) +
229 xml.attribut("linkColor", defLinkColor.name() ) +
230 xml.attribut("defXLinkColor", defXLinkColor.name() ) +
231 xml.attribut("defXLinkWidth", QString().setNum(defXLinkWidth,10) ) +
233 s+=xml.beginElement("vymmap",mapAttr);
236 // Find the used flags while traversing the tree
237 standardFlagsDefault->resetUsedCounter();
239 // Reset the counters before saving
240 // TODO constr. of FIO creates lots of objects, better do this in some other way...
241 FloatImageObj (mapScene).resetSaveCounter();
243 // Build xml recursivly
244 if (!saveSel || typeid (*saveSel) == typeid (MapCenterObj))
245 // Save complete map, if saveSel not set
246 s+=saveToDir(tmpdir,prefix,writeflags,offset);
249 if ( typeid(*saveSel) == typeid(BranchObj) )
251 s+=((BranchObj*)(saveSel))->saveToDir(tmpdir,prefix,offset);
252 else if ( typeid(*saveSel) == typeid(FloatImageObj) )
254 s+=((FloatImageObj*)(saveSel))->saveToDir(tmpdir,prefix);
257 // Save local settings
258 s+=settings.getDataXML (destPath);
261 if (!selection.isEmpty() && !saveSel )
262 s+=xml.valueElement("select",selection.getSelectString());
265 s+=xml.endElement("vymmap");
268 standardFlagsDefault->saveToDir (tmpdir+"/flags/","",writeflags);
272 void VymModel::setFilePath(QString fpath, QString destname)
274 if (fpath.isEmpty() || fpath=="")
281 filePath=fpath; // becomes absolute path
282 fileName=fpath; // gets stripped of path
283 destPath=destname; // needed for vymlinks and during load to reset fileChangedTime
285 // If fpath is not an absolute path, complete it
286 filePath=QDir(fpath).absPath();
287 fileDir=filePath.left (1+filePath.findRev ("/"));
289 // Set short name, too. Search from behind:
290 int i=fileName.findRev("/");
291 if (i>=0) fileName=fileName.remove (0,i+1);
293 // Forget the .vym (or .xml) for name of map
294 mapName=fileName.left(fileName.findRev(".",-1,true) );
298 void VymModel::setFilePath(QString fpath)
300 setFilePath (fpath,fpath);
303 QString VymModel::getFilePath()
308 QString VymModel::getFileName()
313 QString VymModel::getMapName()
318 QString VymModel::getDestPath()
323 ErrorCode VymModel::load (QString fname, const LoadMode &lmode, const FileType &ftype)
325 ErrorCode err=success;
327 parseBaseHandler *handler;
331 case VymMap: handler=new parseVYMHandler; break;
332 case FreemindMap : handler=new parseFreemindHandler; break;
334 QMessageBox::critical( 0, tr( "Critical Parse Error" ),
335 "Unknown FileType in VymModel::load()");
339 bool zipped_org=zipped;
343 selModel->clearSelection();
344 // FIXME VM not needed??? model->setMapEditor(this);
345 // (map state is set later at end of load...)
348 BranchObj *bo=getSelectedBranch();
349 if (!bo) return aborted;
350 if (lmode==ImportAdd)
351 saveStateChangingPart(
354 QString("addMapInsert (%1)").arg(fname),
355 QString("Add map %1 to %2").arg(fname).arg(getObjectName(bo)));
357 saveStateChangingPart(
360 QString("addMapReplace(%1)").arg(fname),
361 QString("Add map %1 to %2").arg(fname).arg(getObjectName(bo)));
365 // Create temporary directory for packing
367 QString tmpZipDir=makeTmpDir (ok,"vym-pack");
370 QMessageBox::critical( 0, tr( "Critical Load Error" ),
371 tr("Couldn't create temporary directory before load\n"));
376 err=unzipDir (tmpZipDir,fname);
386 // Look for mapname.xml
387 xmlfile= fname.left(fname.findRev(".",-1,true));
388 xmlfile=xmlfile.section( '/', -1 );
389 QFile mfile( tmpZipDir + "/" + xmlfile + ".xml");
390 if (!mfile.exists() )
392 // mapname.xml does not exist, well,
393 // maybe someone renamed the mapname.vym file...
394 // Try to find any .xml in the toplevel
395 // directory of the .vym file
396 QStringList flist=QDir (tmpZipDir).entryList("*.xml");
397 if (flist.count()==1)
399 // Only one entry, take this one
400 xmlfile=tmpZipDir + "/"+flist.first();
403 for ( QStringList::Iterator it = flist.begin(); it != flist.end(); ++it )
404 *it=tmpZipDir + "/" + *it;
405 // TODO Multiple entries, load all (but only the first one into this ME)
406 //mainWindow->fileLoadFromTmp (flist);
407 //returnCode=1; // Silently forget this attempt to load
408 qWarning ("MainWindow::load (fn) multimap found...");
411 if (flist.isEmpty() )
413 QMessageBox::critical( 0, tr( "Critical Load Error" ),
414 tr("Couldn't find a map (*.xml) in .vym archive.\n"));
417 } //file doesn't exist
419 xmlfile=mfile.name();
422 QFile file( xmlfile);
424 // I am paranoid: file should exist anyway
425 // according to check in mainwindow.
428 QMessageBox::critical( 0, tr( "Critical Parse Error" ),
429 tr(QString("Couldn't open map %1").arg(file.name())));
433 bool blockSaveStateOrg=blockSaveState;
434 blockReposition=true;
436 QXmlInputSource source( file);
437 QXmlSimpleReader reader;
438 reader.setContentHandler( handler );
439 reader.setErrorHandler( handler );
440 handler->setModel ( this);
443 // We need to set the tmpDir in order to load files with rel. path
448 tmpdir=fname.left(fname.findRev("/",-1));
449 handler->setTmpDir (tmpdir);
450 handler->setInputFile (file.name());
451 handler->setLoadMode (lmode);
452 bool ok = reader.parse( source );
453 blockReposition=false;
454 blockSaveState=blockSaveStateOrg;
458 reposition(); // FIXME VM reposition the view instead...
465 autosaveTimer->stop();
468 // Reset timestamp to check for later updates of file
469 fileChangedTime=QFileInfo (destPath).lastModified();
472 QMessageBox::critical( 0, tr( "Critical Parse Error" ),
473 tr( handler->errorProtocol() ) );
475 // Still return "success": the map maybe at least
476 // partially read by the parser
481 removeDir (QDir(tmpZipDir));
483 // Restore original zip state
490 ErrorCode VymModel::save (const SaveMode &savemode)
494 QString safeFilePath;
496 ErrorCode err=success;
500 mapFileName=mapName+".xml";
502 // use name given by user, even if he chooses .doc
503 mapFileName=fileName;
505 // Look, if we should zip the data:
508 QMessageBox mb( vymName,
509 tr("The map %1\ndid not use the compressed "
510 "vym file format.\nWriting it uncompressed will also write images \n"
511 "and flags and thus may overwrite files in the "
512 "given directory\n\nDo you want to write the map").arg(filePath),
513 QMessageBox::Warning,
514 QMessageBox::Yes | QMessageBox::Default,
516 QMessageBox::Cancel | QMessageBox::Escape);
517 mb.setButtonText( QMessageBox::Yes, tr("compressed (vym default)") );
518 mb.setButtonText( QMessageBox::No, tr("uncompressed") );
519 mb.setButtonText( QMessageBox::Cancel, tr("Cancel"));
522 case QMessageBox::Yes:
523 // save compressed (default file format)
526 case QMessageBox::No:
530 case QMessageBox::Cancel:
537 // First backup existing file, we
538 // don't want to add to old zip archives
542 if ( settings.value ("/mapeditor/writeBackupFile").toBool())
544 QString backupFileName(destPath + "~");
545 QFile backupFile(backupFileName);
546 if (backupFile.exists() && !backupFile.remove())
548 QMessageBox::warning(0, tr("Save Error"),
549 tr("%1\ncould not be removed before saving").arg(backupFileName));
551 else if (!f.rename(backupFileName))
553 QMessageBox::warning(0, tr("Save Error"),
554 tr("%1\ncould not be renamed before saving").arg(destPath));
561 // Create temporary directory for packing
563 tmpZipDir=makeTmpDir (ok,"vym-zip");
566 QMessageBox::critical( 0, tr( "Critical Load Error" ),
567 tr("Couldn't create temporary directory before save\n"));
571 safeFilePath=filePath;
572 setFilePath (tmpZipDir+"/"+ mapName+ ".xml", safeFilePath);
575 // Create mapName and fileDir
576 makeSubDirs (fileDir);
579 if (savemode==CompleteMap || selection.isEmpty())
582 saveFile=saveToDir (fileDir,mapName+"-",true,QPointF(),NULL);
585 autosaveTimer->stop();
590 if (selectionType()==TreeItem::Image)
593 saveFile=saveToDir (fileDir,mapName+"-",true,QPointF(),getSelectedBranch());
594 // TODO take care of multiselections
597 if (!saveStringToDisk(fileDir+mapFileName,saveFile))
600 qWarning ("ME::saveStringToDisk failed!");
606 if (err==success) err=zipDir (tmpZipDir,destPath);
609 removeDir (QDir(tmpZipDir));
611 // Restore original filepath outside of tmp zip dir
612 setFilePath (safeFilePath);
616 fileChangedTime=QFileInfo (destPath).lastModified();
620 void VymModel::addMapReplaceInt(const QString &undoSel, const QString &path)
622 QString pathDir=path.left(path.findRev("/"));
628 // We need to parse saved XML data
629 parseVYMHandler handler;
630 QXmlInputSource source( file);
631 QXmlSimpleReader reader;
632 reader.setContentHandler( &handler );
633 reader.setErrorHandler( &handler );
634 handler.setModel ( this);
635 handler.setTmpDir ( pathDir ); // needed to load files with rel. path
636 if (undoSel.isEmpty())
640 handler.setLoadMode (NewMap);
644 handler.setLoadMode (ImportReplace);
646 blockReposition=true;
647 bool ok = reader.parse( source );
648 blockReposition=false;
651 // This should never ever happen
652 QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
653 handler.errorProtocol());
656 QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
659 void VymModel::addMapInsertInt (const QString &path, int pos)
661 BranchObj *sel=getSelectedBranch();
664 QString pathDir=path.left(path.findRev("/"));
670 // We need to parse saved XML data
671 parseVYMHandler handler;
672 QXmlInputSource source( file);
673 QXmlSimpleReader reader;
674 reader.setContentHandler( &handler );
675 reader.setErrorHandler( &handler );
676 handler.setModel (this);
677 handler.setTmpDir ( pathDir ); // needed to load files with rel. path
678 handler.setLoadMode (ImportAdd);
679 blockReposition=true;
680 bool ok = reader.parse( source );
681 blockReposition=false;
684 // This should never ever happen
685 QMessageBox::critical( 0, tr( "Critical Parse Error while reading %1").arg(path),
686 handler.errorProtocol());
688 if (sel->getDepth()>0)
689 sel->getLastBranch()->linkTo (sel,pos);
691 QMessageBox::critical( 0, tr( "Critical Error" ), tr("Could not read %1").arg(path));
695 FloatImageObj* VymModel::loadFloatImageInt (QString fn)
697 BranchObj *bo=getSelectedBranch();
702 fio=bo->getLastFloatImage();
705 // FIXME VM needed? scene()->update();
711 void VymModel::loadFloatImage ()
713 BranchObj *bo=getSelectedBranch();
717 Q3FileDialog *fd=new Q3FileDialog( NULL);
718 fd->setMode (Q3FileDialog::ExistingFiles);
719 fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
720 ImagePreview *p =new ImagePreview (fd);
721 fd->setContentsPreviewEnabled( TRUE );
722 fd->setContentsPreview( p, p );
723 fd->setPreviewMode( Q3FileDialog::Contents );
724 fd->setCaption(vymName+" - " +tr("Load image"));
725 fd->setDir (lastImageDir);
728 if ( fd->exec() == QDialog::Accepted )
730 // TODO loadFIO in QT4 use: lastImageDir=fd->directory();
731 lastImageDir=QDir (fd->dirPath());
734 for (int j=0; j<fd->selectedFiles().count(); j++)
736 s=fd->selectedFiles().at(j);
737 fio=loadFloatImageInt (s);
740 (LinkableMapObj*)fio,
743 QString ("loadImage (%1)").arg(s ),
744 QString("Add image %1 to %2").arg(s).arg(getObjectName(bo))
747 // TODO loadFIO error handling
748 qWarning ("Failed to load "+s);
756 void VymModel::saveFloatImageInt (FloatImageObj *fio, const QString &type, const QString &fn)
761 void VymModel::saveFloatImage ()
763 FloatImageObj *fio=selection.getFloatImage();
766 QFileDialog *fd=new QFileDialog( NULL);
767 fd->setFilters (imageIO.getFilters());
768 fd->setCaption(vymName+" - " +tr("Save image"));
769 fd->setFileMode( QFileDialog::AnyFile );
770 fd->setDirectory (lastImageDir);
771 // fd->setSelection (fio->getOriginalFilename());
775 if ( fd->exec() == QDialog::Accepted && fd->selectedFiles().count()==1)
777 fn=fd->selectedFiles().at(0);
778 if (QFile (fn).exists() )
780 QMessageBox mb( vymName,
781 tr("The file %1 exists already.\n"
782 "Do you want to overwrite it?").arg(fn),
783 QMessageBox::Warning,
784 QMessageBox::Yes | QMessageBox::Default,
785 QMessageBox::Cancel | QMessageBox::Escape,
786 QMessageBox::NoButton );
788 mb.setButtonText( QMessageBox::Yes, tr("Overwrite") );
789 mb.setButtonText( QMessageBox::No, tr("Cancel"));
792 case QMessageBox::Yes:
795 case QMessageBox::Cancel:
802 saveFloatImageInt (fio,fd->selectedFilter(),fn );
809 void VymModel::importDirInt(BranchObj *dst, QDir d)
811 BranchObj *bo=getSelectedBranch();
814 // Traverse directories
815 d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
816 QFileInfoList list = d.entryInfoList();
819 for (int i = 0; i < list.size(); ++i)
822 if (fi.fileName() != "." && fi.fileName() != ".." )
825 bo=dst->getLastBranch();
826 bo->setHeading (fi.fileName() );
827 bo->setColor (QColor("blue"));
829 if ( !d.cd(fi.fileName()) )
830 QMessageBox::critical (0,tr("Critical Import Error"),tr("Cannot find the directory %1").arg(fi.fileName()));
833 // Recursively add subdirs
840 d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
841 list = d.entryInfoList();
843 for (int i = 0; i < list.size(); ++i)
847 bo=dst->getLastBranch();
848 bo->setHeading (fi.fileName() );
849 bo->setColor (QColor("black"));
850 if (fi.fileName().right(4) == ".vym" )
851 bo->setVymLink (fi.filePath());
856 void VymModel::importDirInt (const QString &s)
858 BranchObj *bo=getSelectedBranch();
861 saveStateChangingPart (bo,bo,QString ("importDir (\"%1\")").arg(s),QString("Import directory structure from %1").arg(s));
868 void VymModel::importDir()
870 BranchObj *bo=getSelectedBranch();
874 filters <<"VYM map (*.vym)";
875 QFileDialog *fd=new QFileDialog( NULL,vymName+ " - " +tr("Choose directory structure to import"));
876 fd->setMode (QFileDialog::DirectoryOnly);
877 fd->setFilters (filters);
878 fd->setCaption(vymName+" - " +tr("Choose directory structure to import"));
882 if ( fd->exec() == QDialog::Accepted )
884 importDirInt (fd->selectedFile() );
886 //FIXME VM needed? scene()->update();
892 void VymModel::autosave()
894 QDateTime now=QDateTime().currentDateTime();
896 // Disable autosave, while we have gone back in history
897 int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
898 if (redosAvail>0) return;
900 // Also disable autosave for new map without filename
901 if (filePath.isEmpty()) return;
904 if (mapUnsaved &&mapChanged && settings.value ("/autosave/use",true).toBool() )
906 if (QFileInfo(filePath).lastModified()<=fileChangedTime)
907 mainWindow->fileSave (this);
910 cout <<" ME::autosave rejected, file on disk is newer than last save.\n";
915 void VymModel::fileChanged()
917 // Check if file on disk has changed meanwhile
918 if (!filePath.isEmpty())
920 QDateTime tmod=QFileInfo (filePath).lastModified();
921 if (tmod>fileChangedTime)
923 // FIXME VM switch to current mapeditor and finish lineedits...
924 QMessageBox mb( vymName,
925 tr("The file of the map on disk has changed:\n\n"
926 " %1\n\nDo you want to reload that map with the new file?").arg(filePath),
927 QMessageBox::Question,
929 QMessageBox::Cancel | QMessageBox::Default,
930 QMessageBox::NoButton );
932 mb.setButtonText( QMessageBox::Yes, tr("Reload"));
933 mb.setButtonText( QMessageBox::No, tr("Ignore"));
936 case QMessageBox::Yes:
938 load (filePath,NewMap,fileType);
939 case QMessageBox::Cancel:
940 fileChangedTime=tmod; // allow autosave to overwrite newer file!
946 bool VymModel::isDefault()
951 void VymModel::makeDefault()
957 bool VymModel::hasChanged()
962 void VymModel::setChanged()
965 autosaveTimer->start(settings.value("/autosave/ms/",300000).toInt());
973 QString VymModel::getObjectName (const LinkableMapObj *lmo)
976 if (!lmo) return QString("Error: NULL has no name!");
978 if ((typeid(*lmo) == typeid(BranchObj) ||
979 typeid(*lmo) == typeid(MapCenterObj)))
982 s=(((BranchObj*)lmo)->getHeading());
983 if (s=="") s="unnamed";
984 return QString("branch (%1)").arg(s);
986 if ((typeid(*lmo) == typeid(FloatImageObj) ))
987 return QString ("floatimage [%1]").arg(((FloatImageObj*)lmo)->getOriginalFilename());
988 return QString("Unknown type has no name!");
991 void VymModel::redo()
993 // Can we undo at all?
994 if (redosAvail<1) return;
996 bool blockSaveStateOrg=blockSaveState;
1001 if (undosAvail<stepsTotal) undosAvail++;
1003 if (curStep>stepsTotal) curStep=1;
1004 QString undoCommand= undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
1005 QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
1006 QString redoCommand= undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
1007 QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
1008 QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
1009 QString version=undoSet.readEntry ("/history/version");
1011 /* TODO Maybe check for version, if we save the history
1012 if (!checkVersion(version))
1013 QMessageBox::warning(0,tr("Warning"),
1014 tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
1017 // Find out current undo directory
1018 QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
1022 cout << "VymModel::redo() begin\n";
1023 cout << " undosAvail="<<undosAvail<<endl;
1024 cout << " redosAvail="<<redosAvail<<endl;
1025 cout << " curStep="<<curStep<<endl;
1026 cout << " ---------------------------"<<endl;
1027 cout << " comment="<<comment.toStdString()<<endl;
1028 cout << " undoCom="<<undoCommand.toStdString()<<endl;
1029 cout << " undoSel="<<undoSelection.toStdString()<<endl;
1030 cout << " redoCom="<<redoCommand.toStdString()<<endl;
1031 cout << " redoSel="<<redoSelection.toStdString()<<endl;
1032 cout << " ---------------------------"<<endl<<endl;
1035 // select object before redo
1036 if (!redoSelection.isEmpty())
1037 select (redoSelection);
1040 parseAtom (redoCommand);
1043 blockSaveState=blockSaveStateOrg;
1045 undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
1046 undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
1047 undoSet.setEntry ("/history/curStep",QString::number(curStep));
1048 undoSet.writeSettings(histPath);
1050 mainWindow->updateHistory (undoSet);
1053 /* TODO remove testing
1054 cout << "ME::redo() end\n";
1055 cout << " undosAvail="<<undosAvail<<endl;
1056 cout << " redosAvail="<<redosAvail<<endl;
1057 cout << " curStep="<<curStep<<endl;
1058 cout << " ---------------------------"<<endl<<endl;
1064 bool VymModel::isRedoAvailable()
1066 if (undoSet.readNumEntry("/history/redosAvail",0)>0)
1072 void VymModel::undo()
1074 // Can we undo at all?
1075 if (undosAvail<1) return;
1077 mainWindow->statusMessage (tr("Autosave disabled during undo."));
1079 bool blockSaveStateOrg=blockSaveState;
1080 blockSaveState=true;
1082 QString undoCommand= undoSet.readEntry (QString("/history/step-%1/undoCommand").arg(curStep));
1083 QString undoSelection=undoSet.readEntry (QString("/history/step-%1/undoSelection").arg(curStep));
1084 QString redoCommand= undoSet.readEntry (QString("/history/step-%1/redoCommand").arg(curStep));
1085 QString redoSelection=undoSet.readEntry (QString("/history/step-%1/redoSelection").arg(curStep));
1086 QString comment=undoSet.readEntry (QString("/history/step-%1/comment").arg(curStep));
1087 QString version=undoSet.readEntry ("/history/version");
1089 /* TODO Maybe check for version, if we save the history
1090 if (!checkVersion(version))
1091 QMessageBox::warning(0,tr("Warning"),
1092 tr("Version %1 of saved undo/redo data\ndoes not match current vym version %2.").arg(version).arg(vymVersion));
1095 // Find out current undo directory
1096 QString bakMapDir(QString(tmpMapDir+"/undo-%1").arg(curStep));
1098 // select object before undo
1099 if (!undoSelection.isEmpty())
1100 select (undoSelection);
1104 cout << "VymModel::undo() begin\n";
1105 cout << " undosAvail="<<undosAvail<<endl;
1106 cout << " redosAvail="<<redosAvail<<endl;
1107 cout << " curStep="<<curStep<<endl;
1108 cout << " ---------------------------"<<endl;
1109 cout << " comment="<<comment.toStdString()<<endl;
1110 cout << " undoCom="<<undoCommand.toStdString()<<endl;
1111 cout << " undoSel="<<undoSelection.toStdString()<<endl;
1112 cout << " redoCom="<<redoCommand.toStdString()<<endl;
1113 cout << " redoSel="<<redoSelection.toStdString()<<endl;
1114 cout << " ---------------------------"<<endl<<endl;
1116 parseAtom (undoCommand);
1121 if (curStep<1) curStep=stepsTotal;
1125 blockSaveState=blockSaveStateOrg;
1126 /* TODO remove testing
1127 cout << "VymModel::undo() end\n";
1128 cout << " undosAvail="<<undosAvail<<endl;
1129 cout << " redosAvail="<<redosAvail<<endl;
1130 cout << " curStep="<<curStep<<endl;
1131 cout << " ---------------------------"<<endl<<endl;
1134 undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
1135 undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
1136 undoSet.setEntry ("/history/curStep",QString::number(curStep));
1137 undoSet.writeSettings(histPath);
1139 mainWindow->updateHistory (undoSet);
1142 ensureSelectionVisible();
1145 bool VymModel::isUndoAvailable()
1147 if (undoSet.readNumEntry("/history/undosAvail",0)>0)
1153 void VymModel::gotoHistoryStep (int i)
1155 // Restore variables
1156 int undosAvail=undoSet.readNumEntry (QString("/history/undosAvail"));
1157 int redosAvail=undoSet.readNumEntry (QString("/history/redosAvail"));
1159 if (i<0) i=undosAvail+redosAvail;
1161 // Clicking above current step makes us undo things
1164 for (int j=0; j<undosAvail-i; j++) undo();
1167 // Clicking below current step makes us redo things
1169 for (int j=undosAvail; j<i; j++)
1171 if (debug) cout << "VymModel::gotoHistoryStep redo "<<j<<"/"<<undosAvail<<" i="<<i<<endl;
1175 // And ignore clicking the current row ;-)
1179 QString VymModel::getHistoryPath()
1181 QString histName(QString("history-%1").arg(curStep));
1182 return (tmpMapDir+"/"+histName);
1185 void VymModel::saveState(const SaveMode &savemode, const QString &undoSelection, const QString &undoCom, const QString &redoSelection, const QString &redoCom, const QString &comment, LinkableMapObj *saveSel)
1187 sendData(redoCom); //FIXME testing
1192 if (blockSaveState) return;
1194 if (debug) cout << "ME::saveState() for "<<qPrintable (mapName)<<endl;
1196 // Find out current undo directory
1197 if (undosAvail<stepsTotal) undosAvail++;
1199 if (curStep>stepsTotal) curStep=1;
1201 QString backupXML="";
1202 QString histDir=getHistoryPath();
1203 QString bakMapPath=histDir+"/map.xml";
1205 // Create histDir if not available
1208 makeSubDirs (histDir);
1210 // Save depending on how much needs to be saved
1212 backupXML=saveToDir (histDir,mapName+"-",false, QPointF (),saveSel);
1214 QString undoCommand="";
1215 if (savemode==UndoCommand)
1217 undoCommand=undoCom;
1219 else if (savemode==PartOfMap )
1221 undoCommand=undoCom;
1222 undoCommand.replace ("PATH",bakMapPath);
1225 if (!backupXML.isEmpty())
1226 // Write XML Data to disk
1227 saveStringToDisk (bakMapPath,backupXML);
1229 // We would have to save all actions in a tree, to keep track of
1230 // possible redos after a action. Possible, but we are too lazy: forget about redos.
1233 // Write the current state to disk
1234 undoSet.setEntry ("/history/undosAvail",QString::number(undosAvail));
1235 undoSet.setEntry ("/history/redosAvail",QString::number(redosAvail));
1236 undoSet.setEntry ("/history/curStep",QString::number(curStep));
1237 undoSet.setEntry (QString("/history/step-%1/undoCommand").arg(curStep),undoCommand);
1238 undoSet.setEntry (QString("/history/step-%1/undoSelection").arg(curStep),undoSelection);
1239 undoSet.setEntry (QString("/history/step-%1/redoCommand").arg(curStep),redoCom);
1240 undoSet.setEntry (QString("/history/step-%1/redoSelection").arg(curStep),redoSelection);
1241 undoSet.setEntry (QString("/history/step-%1/comment").arg(curStep),comment);
1242 undoSet.setEntry (QString("/history/version"),vymVersion);
1243 undoSet.writeSettings(histPath);
1247 // TODO remove after testing
1248 //cout << " into="<< histPath.toStdString()<<endl;
1249 cout << " stepsTotal="<<stepsTotal<<
1250 ", undosAvail="<<undosAvail<<
1251 ", redosAvail="<<redosAvail<<
1252 ", curStep="<<curStep<<endl;
1253 cout << " ---------------------------"<<endl;
1254 cout << " comment="<<comment.toStdString()<<endl;
1255 cout << " undoCom="<<undoCommand.toStdString()<<endl;
1256 cout << " undoSel="<<undoSelection.toStdString()<<endl;
1257 cout << " redoCom="<<redoCom.toStdString()<<endl;
1258 cout << " redoSel="<<redoSelection.toStdString()<<endl;
1259 if (saveSel) cout << " saveSel="<<qPrintable (getSelectString(saveSel))<<endl;
1260 cout << " ---------------------------"<<endl;
1263 mainWindow->updateHistory (undoSet);
1269 void VymModel::saveStateChangingPart(LinkableMapObj *undoSel, LinkableMapObj* redoSel, const QString &rc, const QString &comment)
1271 // save the selected part of the map, Undo will replace part of map
1272 QString undoSelection="";
1274 undoSelection=getSelectString(undoSel);
1276 qWarning ("VymModel::saveStateChangingPart no undoSel given!");
1277 QString redoSelection="";
1279 redoSelection=getSelectString(undoSel);
1281 qWarning ("VymModel::saveStateChangingPart no redoSel given!");
1284 saveState (PartOfMap,
1285 undoSelection, "addMapReplace (\"PATH\")",
1291 void VymModel::saveStateRemovingPart(LinkableMapObj *redoSel, const QString &comment)
1295 qWarning ("VymModel::saveStateRemovingPart no redoSel given!");
1298 QString undoSelection=getSelectString (redoSel->getParObj());
1299 QString redoSelection=getSelectString(redoSel);
1300 if (typeid(*redoSel) == typeid(BranchObj) )
1302 // save the selected branch of the map, Undo will insert part of map
1303 saveState (PartOfMap,
1304 undoSelection, QString("addMapInsert (\"PATH\",%1)").arg(((BranchObj*)redoSel)->getNum()),
1305 redoSelection, "delete ()",
1312 void VymModel::saveState(LinkableMapObj *undoSel, const QString &uc, LinkableMapObj *redoSel, const QString &rc, const QString &comment)
1314 // "Normal" savestate: save commands, selections and comment
1315 // so just save commands for undo and redo
1316 // and use current selection
1318 QString redoSelection="";
1319 if (redoSel) redoSelection=getSelectString(redoSel);
1320 QString undoSelection="";
1321 if (undoSel) undoSelection=getSelectString(undoSel);
1323 saveState (UndoCommand,
1330 void VymModel::saveState(const QString &undoSel, const QString &uc, const QString &redoSel, const QString &rc, const QString &comment)
1332 // "Normal" savestate: save commands, selections and comment
1333 // so just save commands for undo and redo
1334 // and use current selection
1335 saveState (UndoCommand,
1342 void VymModel::saveState(const QString &uc, const QString &rc, const QString &comment)
1344 // "Normal" savestate applied to model (no selection needed):
1345 // save commands and comment
1346 saveState (UndoCommand,
1354 QGraphicsScene* VymModel::getScene ()
1359 BranchObj* VymModel::first()
1361 if (mapCenters.count()>0)
1362 return mapCenters.first();
1367 BranchObj* VymModel::next(BranchObj *bo_start)
1370 BranchObj *bo=bo_start;
1373 // Try to find next branch in current MapCenter
1375 if (rbo) return rbo;
1377 // Try to find MapCenter of bo
1378 while (bo->getDepth()>0) bo=(BranchObj*)bo->getParObj();
1380 // Try to find next MapCenter
1381 int i=mapCenters.indexOf ((MapCenterObj*)bo);
1382 if (i+2 > mapCenters.count() || i<0) return NULL;
1383 if (mapCenters.at(i+1)!=bo_start)
1384 return mapCenters.at(i+1);
1389 LinkableMapObj* VymModel::findMapObj(QPointF p, LinkableMapObj *excludeLMO)
1391 LinkableMapObj *lmo;
1393 for (int i=0;i<mapCenters.count(); i++)
1395 lmo=mapCenters.at(i)->findMapObj (p,excludeLMO);
1396 if (lmo) return lmo;
1401 LinkableMapObj* VymModel::findObjBySelect(const QString &s)
1403 LinkableMapObj *lmo;
1409 part=s.section(",",0,0);
1411 num=part.right(part.length() - 3);
1412 if (typ=="mc" && num.toInt()>=0 && num.toInt() <mapCenters.count() )
1413 return mapCenters.at(num.toInt() );
1416 for (int i=0; i<mapCenters.count(); i++)
1418 lmo=mapCenters.at(i)->findObjBySelect(s);
1419 if (lmo) return lmo;
1424 LinkableMapObj* VymModel::findID (const QString &s)
1426 LinkableMapObj *lmo;
1427 for (int i=0; i<mapCenters.count(); i++)
1429 lmo=mapCenters.at(i)->findID (s);
1430 if (lmo) return lmo;
1435 QString VymModel::saveToDir (const QString &tmpdir,const QString &prefix, int verbose, const QPointF &offset)
1439 for (int i=0; i<mapCenters.count(); i++)
1440 s+=mapCenters.at(i)->saveToDir (tmpdir,prefix,verbose,offset);
1444 //////////////////////////////////////////////
1446 //////////////////////////////////////////////
1447 void VymModel::setVersion (const QString &s)
1452 void VymModel::setAuthor (const QString &s)
1455 QString ("setMapAuthor (\"%1\")").arg(author),
1456 QString ("setMapAuthor (\"%1\")").arg(s),
1457 QString ("Set author of map to \"%1\"").arg(s)
1463 QString VymModel::getAuthor()
1468 void VymModel::setComment (const QString &s)
1471 QString ("setMapComment (\"%1\")").arg(comment),
1472 QString ("setMapComment (\"%1\")").arg(s),
1473 QString ("Set comment of map")
1479 QString VymModel::getComment ()
1484 QString VymModel::getDate ()
1486 return QDate::currentDate().toString ("yyyy-MM-dd");
1489 void VymModel::setHeading(const QString &s)
1491 BranchObj *sel=getSelectedBranch();
1496 "setHeading (\""+sel->getHeading()+"\")",
1498 "setHeading (\""+s+"\")",
1499 QString("Set heading of %1 to \"%2\"").arg(getObjectName(sel)).arg(s) );
1500 sel->setHeading(s );
1501 /* FIXME testing only
1503 TreeItem *ti=getSelectedTreeItem();
1507 //FIXME VM ix is wrong ModelIndex below, ix2 is (hopefully) correct:
1508 //QModelIndex ix=index( ti->row(), ti->column(), index (0,0,QModelIndex()) );
1509 //FIXME VM testing only cout <<"VM::setHeading s="<<s.toStdString()<<" ti="<<ti<<" r,c=("<<ti->row()<<","<<ti->column()<<")"<<endl;
1510 QModelIndex ix2=index (ti);
1511 emit (dataChanged ( ix2,ix2));
1515 cout << "Warning: VM::setHeading ti==NULL\n";
1518 //cout <<" (r,c)=("<<ix2.row()<<","<<ix2.column()<<")"<<endl;
1522 ensureSelectionVisible();
1526 BranchObj* VymModel::findText (QString s, bool cs)
1528 QTextDocument::FindFlags flags=0;
1529 if (cs) flags=QTextDocument::FindCaseSensitively;
1532 { // Nothing found or new find process
1534 // nothing found, start again
1538 bool searching=true;
1539 bool foundNote=false;
1540 while (searching && !EOFind)
1544 // Searching in Note
1545 if (itFind->getNote().contains(s,cs))
1547 if (getSelectedBranch()!=itFind)
1550 ensureSelectionVisible();
1552 if (textEditor->findText(s,flags))
1558 // Searching in Heading
1559 if (searching && itFind->getHeading().contains (s,cs) )
1562 ensureSelectionVisible();
1568 itFind=next(itFind);
1569 if (!itFind) EOFind=true;
1571 //cout <<"still searching... "<<qPrintable( itFind->getHeading())<<endl;
1574 return getSelectedBranch();
1579 void VymModel::findReset()
1580 { // Necessary if text to find changes during a find process
1587 void VymModel::setScene (QGraphicsScene *s)
1589 cout << "VM::setscene scene="<<s<<endl;
1590 mapScene=s; // FIXME VM should not be necessary anymore, move all occurences to MapEditor
1591 //init(); // Here we have a mapScene set,
1592 // which is (still) needed to create MapCenters
1595 void VymModel::setURL(const QString &url)
1597 BranchObj *bo=getSelectedBranch();
1600 QString oldurl=bo->getURL();
1604 QString ("setURL (\"%1\")").arg(oldurl),
1606 QString ("setURL (\"%1\")").arg(url),
1607 QString ("set URL of %1 to %2").arg(getObjectName(bo)).arg(url)
1612 ensureSelectionVisible();
1616 QString VymModel::getURL()
1618 BranchObj *bo=getSelectedBranch();
1620 return bo->getURL();
1625 QStringList VymModel::getURLs()
1628 BranchObj *bo=getSelectedBranch();
1634 if (!bo->getURL().isEmpty()) urls.append( bo->getURL());
1641 void VymModel::linkFloatImageTo(const QString &dstString)
1643 FloatImageObj *fio=selection.getFloatImage();
1646 BranchObj *dst=(BranchObj*)findObjBySelect(dstString);
1647 if (dst && (typeid(*dst)==typeid (BranchObj) ||
1648 typeid(*dst)==typeid (MapCenterObj)))
1650 LinkableMapObj *dstPar=dst->getParObj();
1651 QString parString=getSelectString(dstPar);
1652 QString fioPreSelectString=getSelectString(fio);
1653 QString fioPreParentSelectString=getSelectString (fio->getParObj());
1654 ((BranchObj*)dst)->addFloatImage (fio);
1655 selection.unselect();
1656 ((BranchObj*)(fio->getParObj()))->removeFloatImage (fio);
1657 fio=((BranchObj*)dst)->getLastFloatImage();
1660 selection.select(fio);
1662 getSelectString(fio),
1663 QString("linkTo (\"%1\")").arg(fioPreParentSelectString),
1665 QString ("linkTo (\"%1\")").arg(dstString),
1666 QString ("Link floatimage to %1").arg(getObjectName(dst)));
1672 void VymModel::setFrameType(const FrameObj::FrameType &t)
1674 BranchObj *bo=getSelectedBranch();
1677 QString s=bo->getFrameTypeName();
1678 bo->setFrameType (t);
1679 saveState (bo, QString("setFrameType (\"%1\")").arg(s),
1680 bo, QString ("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),QString ("set type of frame to %1").arg(s));
1686 void VymModel::setFrameType(const QString &s)
1688 BranchObj *bo=getSelectedBranch();
1691 saveState (bo, QString("setFrameType (\"%1\")").arg(bo->getFrameTypeName()),
1692 bo, QString ("setFrameType (\"%1\")").arg(s),QString ("set type of frame to %1").arg(s));
1693 bo->setFrameType (s);
1699 void VymModel::setFramePenColor(const QColor &c)
1701 BranchObj *bo=getSelectedBranch();
1704 saveState (bo, QString("setFramePenColor (\"%1\")").arg(bo->getFramePenColor().name() ),
1705 bo, QString ("setFramePenColor (\"%1\")").arg(c.name() ),QString ("set pen color of frame to %1").arg(c.name() ));
1706 bo->setFramePenColor (c);
1710 void VymModel::setFrameBrushColor(const QColor &c)
1712 BranchObj *bo=getSelectedBranch();
1715 saveState (bo, QString("setFrameBrushColor (\"%1\")").arg(bo->getFrameBrushColor().name() ),
1716 bo, QString ("setFrameBrushColor (\"%1\")").arg(c.name() ),QString ("set brush color of frame to %1").arg(c.name() ));
1717 bo->setFrameBrushColor (c);
1721 void VymModel::setFramePadding (const int &i)
1723 BranchObj *bo=getSelectedBranch();
1726 saveState (bo, QString("setFramePadding (\"%1\")").arg(bo->getFramePadding() ),
1727 bo, QString ("setFramePadding (\"%1\")").arg(i),QString ("set brush color of frame to %1").arg(i));
1728 bo->setFramePadding (i);
1734 void VymModel::setFrameBorderWidth(const int &i)
1736 BranchObj *bo=getSelectedBranch();
1739 saveState (bo, QString("setFrameBorderWidth (\"%1\")").arg(bo->getFrameBorderWidth() ),
1740 bo, QString ("setFrameBorderWidth (\"%1\")").arg(i),QString ("set border width of frame to %1").arg(i));
1741 bo->setFrameBorderWidth (i);
1747 void VymModel::setIncludeImagesVer(bool b)
1749 BranchObj *bo=getSelectedBranch();
1752 QString u= b ? "false" : "true";
1753 QString r=!b ? "false" : "true";
1757 QString("setIncludeImagesVertically (%1)").arg(u),
1759 QString("setIncludeImagesVertically (%1)").arg(r),
1760 QString("Include images vertically in %1").arg(getObjectName(bo))
1762 bo->setIncludeImagesVer(b);
1767 void VymModel::setIncludeImagesHor(bool b)
1769 BranchObj *bo=getSelectedBranch();
1772 QString u= b ? "false" : "true";
1773 QString r=!b ? "false" : "true";
1777 QString("setIncludeImagesHorizontally (%1)").arg(u),
1779 QString("setIncludeImagesHorizontally (%1)").arg(r),
1780 QString("Include images horizontally in %1").arg(getObjectName(bo))
1782 bo->setIncludeImagesHor(b);
1787 void VymModel::setHideLinkUnselected (bool b)
1789 LinkableMapObj *sel=getSelectedLMO();
1791 (selectionType() == TreeItem::Branch ||
1792 selectionType() == TreeItem::MapCenter ||
1793 selectionType() == TreeItem::Image ))
1795 QString u= b ? "false" : "true";
1796 QString r=!b ? "false" : "true";
1800 QString("setHideLinkUnselected (%1)").arg(u),
1802 QString("setHideLinkUnselected (%1)").arg(r),
1803 QString("Hide link of %1 if unselected").arg(getObjectName(sel))
1805 sel->setHideLinkUnselected(b);
1809 void VymModel::setHideExport(bool b)
1811 BranchObj *bo=getSelectedBranch();
1814 bo->setHideInExport (b);
1815 QString u= b ? "false" : "true";
1816 QString r=!b ? "false" : "true";
1820 QString ("setHideExport (%1)").arg(u),
1822 QString ("setHideExport (%1)").arg(r),
1823 QString ("Set HideExport flag of %1 to %2").arg(getObjectName(bo)).arg (r)
1828 // FIXME VM needed? scene()->update();
1832 void VymModel::toggleHideExport()
1834 BranchObj *bo=getSelectedBranch();
1836 setHideExport ( !bo->hideInExport() );
1840 void VymModel::copy()
1842 LinkableMapObj *sel=getSelectedLMO();
1844 (selectionType() == TreeItem::Branch ||
1845 selectionType() == TreeItem::MapCenter ||
1846 selectionType() == TreeItem::Image ))
1848 if (redosAvail == 0)
1851 QString s=getSelectString(sel);
1852 saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy selection to clipboard",sel );
1853 curClipboard=curStep;
1856 // Copy also to global clipboard, because we are at last step in history
1857 QString bakMapName(QString("history-%1").arg(curStep));
1858 QString bakMapDir(tmpMapDir +"/"+bakMapName);
1859 copyDir (bakMapDir,clipboardDir );
1861 clipboardEmpty=false;
1867 void VymModel::pasteNoSave(const int &n)
1869 bool old=blockSaveState;
1870 blockSaveState=true;
1871 bool zippedOrg=zipped;
1872 if (redosAvail > 0 || n!=0)
1874 // Use the "historical" buffer
1875 QString bakMapName(QString("history-%1").arg(n));
1876 QString bakMapDir(tmpMapDir +"/"+bakMapName);
1877 load (bakMapDir+"/"+clipboardFile,ImportAdd, VymMap);
1879 // Use the global buffer
1880 load (clipboardDir+"/"+clipboardFile,ImportAdd, VymMap);
1885 void VymModel::paste()
1887 BranchObj *sel=getSelectedBranch();
1890 saveStateChangingPart(
1893 QString ("paste (%1)").arg(curClipboard),
1894 QString("Paste to %1").arg( getObjectName(sel))
1901 void VymModel::cut()
1903 LinkableMapObj *sel=getSelectedLMO();
1904 if ( sel && (selectionType() == TreeItem::Branch ||
1905 selectionType()==TreeItem::MapCenter ||
1906 selectionType()==TreeItem::Image))
1908 /* No savestate! savestate is called in cutNoSave
1909 saveStateChangingPart(
1913 QString("Cut %1").arg(getObjectName(sel ))
1922 void VymModel::moveBranchUp()
1924 BranchObj* bo=getSelectedBranch();
1928 if (!bo->canMoveBranchUp()) return;
1929 par=(BranchObj*)(bo->getParObj());
1930 BranchObj *obo=par->moveBranchUp (bo); // bo will be the one below selection
1931 saveState (getSelectString(bo),"moveBranchDown ()",getSelectString(obo),"moveBranchUp ()",QString("Move up %1").arg(getObjectName(bo)));
1933 //FIXME VM needed? scene()->update();
1935 ensureSelectionVisible();
1939 void VymModel::moveBranchDown()
1941 BranchObj* bo=getSelectedBranch();
1945 if (!bo->canMoveBranchDown()) return;
1946 par=(BranchObj*)(bo->getParObj());
1947 BranchObj *obo=par->moveBranchDown(bo); // bo will be the one above selection
1948 saveState(getSelectString(bo),"moveBranchUp ()",getSelectString(obo),"moveBranchDown ()",QString("Move down %1").arg(getObjectName(bo)));
1950 //FIXME VM needed? scene()->update();
1952 ensureSelectionVisible();
1956 void VymModel::sortChildren()
1958 BranchObj* bo=getSelectedBranch();
1961 if(bo->countBranches()>1)
1963 saveStateChangingPart(bo,bo, "sortChildren ()",QString("Sort children of %1").arg(getObjectName(bo)));
1966 ensureSelectionVisible();
1971 void VymModel::createMapCenter()
1973 MapCenterObj *mco=addMapCenter (QPointF (0,0) );
1977 void VymModel::createBranch()
1979 BranchObj *bo=getSelectedBranch();
1982 BranchObj *newbo=addNewBranchInt (-2); // FIXME VM Old model, merge with below
1985 QList<QVariant> cData;
1986 cData << "VM:createBranch" << "undef"<<"undef";
1987 TreeItem *parti=bo->getTreeItem();
1988 TreeItem *ti=new TreeItem (cData,parti);
1990 ti->setType (TreeItem::Branch);
1991 parti->appendChild (ti);
1995 newbo->setTreeItem (ti);
1996 select (newbo); // FIXME VM really needed here?
2001 MapCenterObj* VymModel::addMapCenter ()
2003 MapCenterObj *mco=addMapCenter (contextPos);
2004 cout <<"VM::addMCO () mapScene="<<mapScene<<endl;
2005 selection.select (mco);
2007 ensureSelectionVisible();
2012 QString ("addMapCenter (%1,%2)").arg (contextPos.x()).arg(contextPos.y()),
2013 QString ("Adding MapCenter to (%1,%2)").arg (contextPos.x()).arg(contextPos.y())
2018 MapCenterObj* VymModel::addMapCenter(QPointF absPos)
2020 MapCenterObj *mapCenter = new MapCenterObj(mapScene,this);
2021 mapCenter->setMapEditor(mapEditor); //FIXME VM needed to get defLinkStyle, mapLinkColorHint ... for later added objects
2022 mapCenter->move (absPos);
2023 mapCenter->setVisibility (true);
2024 mapCenter->setHeading (QApplication::translate("Heading of mapcenter in new map", "New map"));
2025 mapCenters.append(mapCenter);
2028 QList<QVariant> cData;
2029 cData << "VM:addMapCenter" << "undef"<<"undef";
2030 TreeItem *ti=new TreeItem (cData,rootItem);
2031 ti->setLMO (mapCenter);
2032 ti->setType (TreeItem::MapCenter);
2033 mapCenter->setTreeItem (ti);
2034 rootItem->appendChild (ti);
2039 MapCenterObj* VymModel::removeMapCenter(MapCenterObj* mco)
2041 int i=mapCenters.indexOf (mco);
2044 mapCenters.removeAt (i);
2046 if (i>0) return mapCenters.at(i-1); // Return previous MCO
2051 MapCenterObj* VymModel::getLastMapCenter()
2053 if (mapCenters.size()>0)
2054 return mapCenters.last();
2061 BranchObj* VymModel::addNewBranchInt(int num)
2063 // Depending on pos:
2064 // -3 insert in children of parent above selection
2065 // -2 add branch to selection
2066 // -1 insert in children of parent below selection
2067 // 0..n insert in children of parent at pos
2068 BranchObj *newbo=NULL;
2069 BranchObj *bo=getSelectedBranch();
2074 // save scroll state. If scrolled, automatically select
2075 // new branch in order to tmp unscroll parent...
2076 newbo=bo->addBranch();
2081 bo=(BranchObj*)bo->getParObj();
2082 if (bo) newbo=bo->insertBranch(num);
2086 bo=(BranchObj*)bo->getParObj();
2087 if (bo) newbo=bo->insertBranch(num);
2089 if (!newbo) return NULL;
2094 BranchObj* VymModel::addNewBranch(int pos)
2096 // Different meaning than num in addNewBranchInt!
2100 BranchObj *bo = getSelectedBranch();
2101 BranchObj *newbo=NULL;
2105 // FIXME VM do we still need this in model? setCursor (Qt::ArrowCursor);
2107 newbo=addNewBranchInt (pos-2);
2115 QString ("addBranch (%1)").arg(pos),
2116 QString ("Add new branch to %1").arg(getObjectName(bo)));
2120 latestSelectionString=getSelectString(newbo);
2121 // In Network mode, the client needs to know where the new branch is,
2122 // so we have to pass on this information via saveState.
2123 // TODO: Get rid of this positioning workaround
2124 QString ps=qpointfToString (newbo->getAbsPos());
2125 sendData ("selectLatestAdded ()");
2126 sendData (QString("move %1").arg(ps));
2134 BranchObj* VymModel::addNewBranchBefore()
2136 BranchObj *newbo=NULL;
2137 BranchObj *bo = getSelectedBranch();
2138 if (bo && selectionType()==TreeItem::Branch)
2139 // We accept no MapCenterObj here, so we _have_ a parent
2141 QPointF p=bo->getRelPos();
2144 BranchObj *parbo=(BranchObj*)(bo->getParObj());
2146 // add below selection
2147 newbo=parbo->insertBranch(bo->getNum()+1);
2150 newbo->move2RelPos (p);
2152 // Move selection to new branch
2153 bo->linkTo (newbo,-1);
2155 saveState (newbo, "deleteKeepChildren ()", newbo, "addBranchBefore ()",
2156 QString ("Add branch before %1").arg(getObjectName(bo)));
2162 latestSelectionString=selection.getSelectString();
2166 void VymModel::deleteSelection()
2168 BranchObj *bo = getSelectedBranch();
2170 if (bo && selectionType()==TreeItem::MapCenter)
2172 // BranchObj* par=(BranchObj*)(bo->getParObj());
2173 selection.unselect();
2174 /* FIXME VM Note: does saveStateRemovingPart work for MCO? (No parent!)
2175 saveStateRemovingPart (bo, QString ("Delete %1").arg(getObjectName(bo)));
2177 bo=removeMapCenter ((MapCenterObj*)bo);
2180 selection.select (bo);
2181 ensureSelectionVisible();
2187 if (bo && selectionType()==TreeItem::Branch)
2189 QModelIndex ix=getSelectedIndex();
2191 BranchObj* par=(BranchObj*)bo->getParObj();
2193 saveStateRemovingPart (bo, QString ("Delete %1").arg(getObjectName(bo)));
2194 par->removeBranch(bo);
2196 ensureSelectionVisible();
2201 FloatImageObj *fio=selection.getFloatImage();
2204 BranchObj* par=(BranchObj*)fio->getParObj();
2205 saveStateChangingPart(
2209 QString("Delete %1").arg(getObjectName(fio))
2212 par->removeFloatImage(fio);
2216 ensureSelectionVisible();
2221 void VymModel::deleteKeepChildren()
2223 BranchObj *bo=getSelectedBranch();
2227 par=(BranchObj*)(bo->getParObj());
2229 // Don't use this on mapcenter
2232 // Check if we have childs at all to keep
2233 if (bo->countBranches()==0)
2239 QPointF p=bo->getRelPos();
2240 saveStateChangingPart(
2243 "deleteKeepChildren ()",
2244 QString("Remove %1 and keep its children").arg(getObjectName(bo))
2247 QString sel=getSelectString(bo);
2249 par->removeBranchHere(bo);
2252 getSelectedBranch()->move2RelPos (p);
2257 void VymModel::deleteChildren()
2259 BranchObj *bo=getSelectedBranch();
2262 saveStateChangingPart(
2265 "deleteChildren ()",
2266 QString( "Remove children of branch %1").arg(getObjectName(bo))
2268 bo->removeChildren();
2274 bool VymModel::scrollBranch(BranchObj *bo)
2278 if (bo->isScrolled()) return false;
2279 if (bo->countBranches()==0) return false;
2280 if (bo->getDepth()==0) return false;
2286 QString ("%1 ()").arg(u),
2288 QString ("%1 ()").arg(r),
2289 QString ("%1 %2").arg(r).arg(getObjectName(bo))
2293 // FIXME VM needed? scene()->update();
2299 bool VymModel::unscrollBranch(BranchObj *bo)
2303 if (!bo->isScrolled()) return false;
2304 if (bo->countBranches()==0) return false;
2305 if (bo->getDepth()==0) return false;
2311 QString ("%1 ()").arg(u),
2313 QString ("%1 ()").arg(r),
2314 QString ("%1 %2").arg(r).arg(getObjectName(bo))
2318 // FIXME VM needed? scene()->update();
2324 void VymModel::toggleScroll()
2326 BranchObj *bo=getSelectedBranch();
2327 if (selectionType()==TreeItem::Branch )
2329 if (bo->isScrolled())
2330 unscrollBranch (bo);
2336 void VymModel::unscrollChildren()
2338 BranchObj *bo=getSelectedBranch();
2344 if (bo->isScrolled()) unscrollBranch (bo);
2349 void VymModel::addFloatImage (const QPixmap &img)
2351 BranchObj *bo=getSelectedBranch();
2354 FloatImageObj *fio=bo->addFloatImage();
2356 fio->setOriginalFilename("No original filename (image added by dropevent)");
2357 QString s=getSelectString(bo);
2358 saveState (PartOfMap, s, "nop ()", s, "copy ()","Copy dropped image to clipboard",fio );
2359 saveState (fio,"delete ()", bo,QString("paste(%1)").arg(curStep),"Pasting dropped image");
2361 // FIXME VM needed? scene()->update();
2366 void VymModel::colorBranch (QColor c)
2368 BranchObj *bo=getSelectedBranch();
2373 QString ("colorBranch (\"%1\")").arg(bo->getColor().name()),
2375 QString ("colorBranch (\"%1\")").arg(c.name()),
2376 QString("Set color of %1 to %2").arg(getObjectName(bo)).arg(c.name())
2378 bo->setColor(c); // color branch
2382 void VymModel::colorSubtree (QColor c)
2384 BranchObj *bo=getSelectedBranch();
2387 saveStateChangingPart(
2390 QString ("colorSubtree (\"%1\")").arg(c.name()),
2391 QString ("Set color of %1 and children to %2").arg(getObjectName(bo)).arg(c.name())
2393 bo->setColorSubtree (c); // color links, color children
2397 QColor VymModel::getCurrentHeadingColor()
2399 BranchObj *bo=getSelectedBranch();
2400 if (bo) return bo->getColor();
2402 QMessageBox::warning(0,"Warning","Can't get color of heading,\nthere's no branch selected");
2408 void VymModel::editURL()
2410 BranchObj *bo=getSelectedBranch();
2414 QString text = QInputDialog::getText(
2415 "VYM", tr("Enter URL:"), QLineEdit::Normal,
2416 bo->getURL(), &ok, NULL);
2418 // user entered something and pressed OK
2423 void VymModel::editLocalURL()
2425 BranchObj *bo=getSelectedBranch();
2428 QStringList filters;
2429 filters <<"All files (*)";
2430 filters << tr("Text","Filedialog") + " (*.txt)";
2431 filters << tr("Spreadsheet","Filedialog") + " (*.odp,*.sxc)";
2432 filters << tr("Textdocument","Filedialog") +" (*.odw,*.sxw)";
2433 filters << tr("Images","Filedialog") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)";
2434 QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Set URL to a local file"));
2435 fd->setFilters (filters);
2436 fd->setCaption(vymName+" - " +tr("Set URL to a local file"));
2437 fd->setDirectory (lastFileDir);
2438 if (! bo->getVymLink().isEmpty() )
2439 fd->selectFile( bo->getURL() );
2442 if ( fd->exec() == QDialog::Accepted )
2444 lastFileDir=QDir (fd->directory().path());
2445 setURL (fd->selectedFile() );
2451 void VymModel::editHeading2URL()
2453 BranchObj *bo=getSelectedBranch();
2455 setURL (bo->getHeading());
2458 void VymModel::editBugzilla2URL()
2460 BranchObj *bo=getSelectedBranch();
2463 QString url= "https://bugzilla.novell.com/show_bug.cgi?id="+bo->getHeading();
2468 void VymModel::editFATE2URL()
2470 BranchObj *bo=getSelectedBranch();
2473 QString url= "http://keeper.suse.de:8080/webfate/match/id?value=ID"+bo->getHeading();
2476 "setURL (\""+bo->getURL()+"\")",
2478 "setURL (\""+url+"\")",
2479 QString("Use heading of %1 as link to FATE").arg(getObjectName(bo))
2486 void VymModel::editVymLink()
2488 BranchObj *bo=getSelectedBranch();
2491 QStringList filters;
2492 filters <<"VYM map (*.vym)";
2493 QFileDialog *fd=new QFileDialog( NULL,vymName+" - " +tr("Link to another map"));
2494 fd->setFilters (filters);
2495 fd->setCaption(vymName+" - " +tr("Link to another map"));
2496 fd->setDirectory (lastFileDir);
2497 if (! bo->getVymLink().isEmpty() )
2498 fd->selectFile( bo->getVymLink() );
2502 if ( fd->exec() == QDialog::Accepted )
2504 lastFileDir=QDir (fd->directory().path());
2507 "setVymLink (\""+bo->getVymLink()+"\")",
2509 "setVymLink (\""+fd->selectedFile()+"\")",
2510 QString("Set vymlink of %1 to %2").arg(getObjectName(bo)).arg(fd->selectedFile())
2512 setVymLink (fd->selectedFile() ); // FIXME ok?
2517 void VymModel::setVymLink (const QString &s)
2519 // Internal function, no saveState needed
2520 BranchObj *bo=getSelectedBranch();
2527 ensureSelectionVisible();
2531 void VymModel::deleteVymLink()
2533 BranchObj *bo=getSelectedBranch();
2538 "setVymLink (\""+bo->getVymLink()+"\")",
2540 "setVymLink (\"\")",
2541 QString("Unset vymlink of %1").arg(getObjectName(bo))
2543 bo->setVymLink ("" );
2546 // FIXME VM needed? scene()->update();
2550 QString VymModel::getVymLink()
2552 BranchObj *bo=getSelectedBranch();
2554 return bo->getVymLink();
2560 QStringList VymModel::getVymLinks()
2563 BranchObj *bo=getSelectedBranch();
2569 if (!bo->getVymLink().isEmpty()) links.append( bo->getVymLink());
2577 void VymModel::followXLink(int i)
2579 BranchObj *bo=getSelectedBranch();
2582 bo=bo->XLinkTargetAt(i);
2585 selection.select(bo);
2586 ensureSelectionVisible();
2591 void VymModel::editXLink(int i) // FIXME VM missing saveState
2593 BranchObj *bo=getSelectedBranch();
2596 XLinkObj *xlo=bo->XLinkAt(i);
2599 EditXLinkDialog dia;
2601 dia.setSelection(bo);
2602 if (dia.exec() == QDialog::Accepted)
2604 if (dia.useSettingsGlobal() )
2606 setMapDefXLinkColor (xlo->getColor() );
2607 setMapDefXLinkWidth (xlo->getWidth() );
2609 if (dia.deleteXLink())
2610 bo->deleteXLinkAt(i);
2620 //////////////////////////////////////////////
2622 //////////////////////////////////////////////
2624 void VymModel::parseAtom(const QString &atom)
2626 BranchObj *selb=getSelectedBranch();
2632 // Split string s into command and parameters
2633 parser.parseAtom (atom);
2634 QString com=parser.getCommand();
2636 // External commands
2637 /////////////////////////////////////////////////////////////////////
2638 if (com=="addBranch")
2640 if (selection.isEmpty())
2642 parser.setError (Aborted,"Nothing selected");
2645 parser.setError (Aborted,"Type of selection is not a branch");
2650 if (parser.checkParCount(pl))
2652 if (parser.parCount()==0)
2656 n=parser.parInt (ok,0);
2657 if (ok ) addNewBranch (n);
2661 /////////////////////////////////////////////////////////////////////
2662 } else if (com=="addBranchBefore")
2664 if (selection.isEmpty())
2666 parser.setError (Aborted,"Nothing selected");
2669 parser.setError (Aborted,"Type of selection is not a branch");
2672 if (parser.parCount()==0)
2674 addNewBranchBefore ();
2677 /////////////////////////////////////////////////////////////////////
2678 } else if (com==QString("addMapCenter"))
2680 if (parser.checkParCount(2))
2682 x=parser.parDouble (ok,0);
2685 y=parser.parDouble (ok,1);
2686 if (ok) addMapCenter (QPointF(x,y));
2689 /////////////////////////////////////////////////////////////////////
2690 } else if (com==QString("addMapReplace"))
2692 if (selection.isEmpty())
2694 parser.setError (Aborted,"Nothing selected");
2697 parser.setError (Aborted,"Type of selection is not a branch");
2698 } else if (parser.checkParCount(1))
2700 //s=parser.parString (ok,0); // selection
2701 t=parser.parString (ok,0); // path to map
2702 if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
2703 addMapReplaceInt(getSelectString(selb),t);
2705 /////////////////////////////////////////////////////////////////////
2706 } else if (com==QString("addMapInsert"))
2708 if (selection.isEmpty())
2710 parser.setError (Aborted,"Nothing selected");
2713 parser.setError (Aborted,"Type of selection is not a branch");
2716 if (parser.checkParCount(2))
2718 t=parser.parString (ok,0); // path to map
2719 n=parser.parInt(ok,1); // position
2720 if (QDir::isRelativePath(t)) t=(tmpMapDir + "/"+t);
2721 addMapInsertInt(t,n);
2724 /////////////////////////////////////////////////////////////////////
2725 } else if (com=="clearFlags")
2727 if (selection.isEmpty() )
2729 parser.setError (Aborted,"Nothing selected");
2732 parser.setError (Aborted,"Type of selection is not a branch");
2733 } else if (parser.checkParCount(0))
2735 selb->clearStandardFlags();
2736 selb->updateFlagsToolbar();
2738 /////////////////////////////////////////////////////////////////////
2739 } else if (com=="colorBranch")
2741 if (selection.isEmpty())
2743 parser.setError (Aborted,"Nothing selected");
2746 parser.setError (Aborted,"Type of selection is not a branch");
2747 } else if (parser.checkParCount(1))
2749 QColor c=parser.parColor (ok,0);
2750 if (ok) colorBranch (c);
2752 /////////////////////////////////////////////////////////////////////
2753 } else if (com=="colorSubtree")
2755 if (selection.isEmpty())
2757 parser.setError (Aborted,"Nothing selected");
2760 parser.setError (Aborted,"Type of selection is not a branch");
2761 } else if (parser.checkParCount(1))
2763 QColor c=parser.parColor (ok,0);
2764 if (ok) colorSubtree (c);
2766 /////////////////////////////////////////////////////////////////////
2767 } else if (com=="copy")
2769 if (selection.isEmpty())
2771 parser.setError (Aborted,"Nothing selected");
2774 parser.setError (Aborted,"Type of selection is not a branch");
2775 } else if (parser.checkParCount(0))
2777 //FIXME missing action for copy
2779 /////////////////////////////////////////////////////////////////////
2780 } else if (com=="cut")
2782 if (selection.isEmpty())
2784 parser.setError (Aborted,"Nothing selected");
2785 } else if ( selectionType()!=TreeItem::Branch &&
2786 selectionType()!=TreeItem::MapCenter &&
2787 selectionType()!=TreeItem::Image )
2789 parser.setError (Aborted,"Type of selection is not a branch or floatimage");
2790 } else if (parser.checkParCount(0))
2794 /////////////////////////////////////////////////////////////////////
2795 } else if (com=="delete")
2797 if (selection.isEmpty())
2799 parser.setError (Aborted,"Nothing selected");
2801 /*else if (selectionType() != TreeItem::Branch && selectionType() != TreeItem::Image )
2803 parser.setError (Aborted,"Type of selection is wrong.");
2806 else if (parser.checkParCount(0))
2810 /////////////////////////////////////////////////////////////////////
2811 } else if (com=="deleteKeepChildren")
2813 if (selection.isEmpty())
2815 parser.setError (Aborted,"Nothing selected");
2818 parser.setError (Aborted,"Type of selection is not a branch");
2819 } else if (parser.checkParCount(0))
2821 deleteKeepChildren();
2823 /////////////////////////////////////////////////////////////////////
2824 } else if (com=="deleteChildren")
2826 if (selection.isEmpty())
2828 parser.setError (Aborted,"Nothing selected");
2831 parser.setError (Aborted,"Type of selection is not a branch");
2832 } else if (parser.checkParCount(0))
2836 /////////////////////////////////////////////////////////////////////
2837 } else if (com=="exportASCII")
2841 if (parser.parCount()>=1)
2842 // Hey, we even have a filename
2843 fname=parser.parString(ok,0);
2846 parser.setError (Aborted,"Could not read filename");
2849 exportASCII (fname,false);
2851 /////////////////////////////////////////////////////////////////////
2852 } else if (com=="exportImage")
2856 if (parser.parCount()>=2)
2857 // Hey, we even have a filename
2858 fname=parser.parString(ok,0);
2861 parser.setError (Aborted,"Could not read filename");
2864 QString format="PNG";
2865 if (parser.parCount()>=2)
2867 format=parser.parString(ok,1);
2869 exportImage (fname,false,format);
2871 /////////////////////////////////////////////////////////////////////
2872 } else if (com=="exportXHTML")
2876 if (parser.parCount()>=2)
2877 // Hey, we even have a filename
2878 fname=parser.parString(ok,1);
2881 parser.setError (Aborted,"Could not read filename");
2884 exportXHTML (fname,false);
2886 /////////////////////////////////////////////////////////////////////
2887 } else if (com=="exportXML")
2891 if (parser.parCount()>=2)
2892 // Hey, we even have a filename
2893 fname=parser.parString(ok,1);
2896 parser.setError (Aborted,"Could not read filename");
2899 exportXML (fname,false);
2901 /////////////////////////////////////////////////////////////////////
2902 } else if (com=="importDir")
2904 if (selection.isEmpty())
2906 parser.setError (Aborted,"Nothing selected");
2909 parser.setError (Aborted,"Type of selection is not a branch");
2910 } else if (parser.checkParCount(1))
2912 s=parser.parString(ok,0);
2913 if (ok) importDirInt(s);
2915 /////////////////////////////////////////////////////////////////////
2916 } else if (com=="linkTo")
2918 if (selection.isEmpty())
2920 parser.setError (Aborted,"Nothing selected");
2923 if (parser.checkParCount(4))
2925 // 0 selectstring of parent
2926 // 1 num in parent (for branches)
2927 // 2,3 x,y of mainbranch or mapcenter
2928 s=parser.parString(ok,0);
2929 LinkableMapObj *dst=findObjBySelect (s);
2932 if (typeid(*dst) == typeid(BranchObj) )
2934 // Get number in parent
2935 n=parser.parInt (ok,1);
2938 selb->linkTo ((BranchObj*)(dst),n);
2941 } else if (typeid(*dst) == typeid(MapCenterObj) )
2943 selb->linkTo ((BranchObj*)(dst),-1);
2944 // Get coordinates of mainbranch
2945 x=parser.parDouble(ok,2);
2948 y=parser.parDouble(ok,3);
2958 } else if ( selectionType() == TreeItem::Image)
2960 if (parser.checkParCount(1))
2962 // 0 selectstring of parent
2963 s=parser.parString(ok,0);
2964 LinkableMapObj *dst=findObjBySelect (s);
2967 if (typeid(*dst) == typeid(BranchObj) ||
2968 typeid(*dst) == typeid(MapCenterObj))
2969 linkFloatImageTo (getSelectString(dst));
2971 parser.setError (Aborted,"Destination is not a branch");
2974 parser.setError (Aborted,"Type of selection is not a floatimage or branch");
2975 /////////////////////////////////////////////////////////////////////
2976 } else if (com=="loadImage")
2978 if (selection.isEmpty())
2980 parser.setError (Aborted,"Nothing selected");
2983 parser.setError (Aborted,"Type of selection is not a branch");
2984 } else if (parser.checkParCount(1))
2986 s=parser.parString(ok,0);
2987 if (ok) loadFloatImageInt (s);
2989 /////////////////////////////////////////////////////////////////////
2990 } else if (com=="moveBranchUp")
2992 if (selection.isEmpty() )
2994 parser.setError (Aborted,"Nothing selected");
2997 parser.setError (Aborted,"Type of selection is not a branch");
2998 } else if (parser.checkParCount(0))
3002 /////////////////////////////////////////////////////////////////////
3003 } else if (com=="moveBranchDown")
3005 if (selection.isEmpty() )
3007 parser.setError (Aborted,"Nothing selected");
3010 parser.setError (Aborted,"Type of selection is not a branch");
3011 } else if (parser.checkParCount(0))
3015 /////////////////////////////////////////////////////////////////////
3016 } else if (com=="move")
3018 if (selection.isEmpty() )
3020 parser.setError (Aborted,"Nothing selected");
3021 } else if ( selectionType()!=TreeItem::Branch &&
3022 selectionType()!=TreeItem::MapCenter &&
3023 selectionType()!=TreeItem::Image )
3025 parser.setError (Aborted,"Type of selection is not a branch or floatimage");
3026 } else if (parser.checkParCount(2))
3028 x=parser.parDouble (ok,0);
3031 y=parser.parDouble (ok,1);
3035 /////////////////////////////////////////////////////////////////////
3036 } else if (com=="moveRel")
3038 if (selection.isEmpty() )
3040 parser.setError (Aborted,"Nothing selected");
3041 } else if ( selectionType()!=TreeItem::Branch &&
3042 selectionType()!=TreeItem::MapCenter &&
3043 selectionType()!=TreeItem::Image )
3045 parser.setError (Aborted,"Type of selection is not a branch or floatimage");
3046 } else if (parser.checkParCount(2))
3048 x=parser.parDouble (ok,0);
3051 y=parser.parDouble (ok,1);
3052 if (ok) moveRel (x,y);
3055 /////////////////////////////////////////////////////////////////////
3056 } else if (com=="nop")
3058 /////////////////////////////////////////////////////////////////////
3059 } else if (com=="paste")
3061 if (selection.isEmpty() )
3063 parser.setError (Aborted,"Nothing selected");
3066 parser.setError (Aborted,"Type of selection is not a branch");
3067 } else if (parser.checkParCount(1))
3069 n=parser.parInt (ok,0);
3070 if (ok) pasteNoSave(n);
3072 /////////////////////////////////////////////////////////////////////
3073 } else if (com=="qa")
3075 if (selection.isEmpty() )
3077 parser.setError (Aborted,"Nothing selected");
3080 parser.setError (Aborted,"Type of selection is not a branch");
3081 } else if (parser.checkParCount(4))
3084 c=parser.parString (ok,0);
3087 parser.setError (Aborted,"No comment given");
3090 s=parser.parString (ok,1);
3093 parser.setError (Aborted,"First parameter is not a string");
3096 t=parser.parString (ok,2);
3099 parser.setError (Aborted,"Condition is not a string");
3102 u=parser.parString (ok,3);
3105 parser.setError (Aborted,"Third parameter is not a string");
3110 parser.setError (Aborted,"Unknown type: "+s);
3115 parser.setError (Aborted,"Unknown operator: "+t);
3120 parser.setError (Aborted,"Type of selection is not a branch");
3123 if (selb->getHeading() == u)
3125 cout << "PASSED: " << qPrintable (c) << endl;
3128 cout << "FAILED: " << qPrintable (c) << endl;
3138 /////////////////////////////////////////////////////////////////////
3139 } else if (com=="saveImage")
3141 FloatImageObj *fio=selection.getFloatImage();
3144 parser.setError (Aborted,"Type of selection is not an image");
3145 } else if (parser.checkParCount(2))
3147 s=parser.parString(ok,0);
3150 t=parser.parString(ok,1);
3151 if (ok) saveFloatImageInt (fio,t,s);
3154 /////////////////////////////////////////////////////////////////////
3155 } else if (com=="scroll")
3157 if (selection.isEmpty() )
3159 parser.setError (Aborted,"Nothing selected");
3162 parser.setError (Aborted,"Type of selection is not a branch");
3163 } else if (parser.checkParCount(0))
3165 if (!scrollBranch (selb))
3166 parser.setError (Aborted,"Could not scroll branch");
3168 /////////////////////////////////////////////////////////////////////
3169 } else if (com=="select")
3171 if (parser.checkParCount(1))
3173 s=parser.parString(ok,0);
3176 /////////////////////////////////////////////////////////////////////
3177 } else if (com=="selectLastBranch")
3179 if (selection.isEmpty() )
3181 parser.setError (Aborted,"Nothing selected");
3184 parser.setError (Aborted,"Type of selection is not a branch");
3185 } else if (parser.checkParCount(0))
3187 BranchObj *bo=selb->getLastBranch();
3189 parser.setError (Aborted,"Could not select last branch");
3193 /////////////////////////////////////////////////////////////////////
3194 } else if (com=="selectLastImage")
3196 if (selection.isEmpty() )
3198 parser.setError (Aborted,"Nothing selected");
3201 parser.setError (Aborted,"Type of selection is not a branch");
3202 } else if (parser.checkParCount(0))
3204 FloatImageObj *fio=selb->getLastFloatImage();
3206 parser.setError (Aborted,"Could not select last image");
3210 /////////////////////////////////////////////////////////////////////
3211 } else if (com=="selectLatestAdded")
3213 if (latestSelectionString.isEmpty() )
3215 parser.setError (Aborted,"No latest added object");
3218 if (!select (latestSelectionString))
3219 parser.setError (Aborted,"Could not select latest added object "+latestSelectionString);
3221 /////////////////////////////////////////////////////////////////////
3222 } else if (com=="setFrameType")
3224 if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
3226 parser.setError (Aborted,"Type of selection does not allow setting frame type");
3228 else if (parser.checkParCount(1))
3230 s=parser.parString(ok,0);
3231 if (ok) setFrameType (s);
3233 /////////////////////////////////////////////////////////////////////
3234 } else if (com=="setFramePenColor")
3236 if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
3238 parser.setError (Aborted,"Type of selection does not allow setting of pen color");
3240 else if (parser.checkParCount(1))
3242 QColor c=parser.parColor(ok,0);
3243 if (ok) setFramePenColor (c);
3245 /////////////////////////////////////////////////////////////////////
3246 } else if (com=="setFrameBrushColor")
3248 if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
3250 parser.setError (Aborted,"Type of selection does not allow setting brush color");
3252 else if (parser.checkParCount(1))
3254 QColor c=parser.parColor(ok,0);
3255 if (ok) setFrameBrushColor (c);
3257 /////////////////////////////////////////////////////////////////////
3258 } else if (com=="setFramePadding")
3260 if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
3262 parser.setError (Aborted,"Type of selection does not allow setting frame padding");
3264 else if (parser.checkParCount(1))
3266 n=parser.parInt(ok,0);
3267 if (ok) setFramePadding(n);
3269 /////////////////////////////////////////////////////////////////////
3270 } else if (com=="setFrameBorderWidth")
3272 if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
3274 parser.setError (Aborted,"Type of selection does not allow setting frame border width");
3276 else if (parser.checkParCount(1))
3278 n=parser.parInt(ok,0);
3279 if (ok) setFrameBorderWidth (n);
3281 /////////////////////////////////////////////////////////////////////
3282 } else if (com=="setMapAuthor")
3284 if (parser.checkParCount(1))
3286 s=parser.parString(ok,0);
3287 if (ok) setAuthor (s);
3289 /////////////////////////////////////////////////////////////////////
3290 } else if (com=="setMapComment")
3292 if (parser.checkParCount(1))
3294 s=parser.parString(ok,0);
3295 if (ok) setComment(s);
3297 /////////////////////////////////////////////////////////////////////
3298 } else if (com=="setMapBackgroundColor")
3300 if (selection.isEmpty() )
3302 parser.setError (Aborted,"Nothing selected");
3303 } else if (! getSelectedBranch() )
3305 parser.setError (Aborted,"Type of selection is not a branch");
3306 } else if (parser.checkParCount(1))
3308 QColor c=parser.parColor (ok,0);
3309 if (ok) setMapBackgroundColor (c);
3311 /////////////////////////////////////////////////////////////////////
3312 } else if (com=="setMapDefLinkColor")
3314 if (selection.isEmpty() )
3316 parser.setError (Aborted,"Nothing selected");
3319 parser.setError (Aborted,"Type of selection is not a branch");
3320 } else if (parser.checkParCount(1))
3322 QColor c=parser.parColor (ok,0);
3323 if (ok) setMapDefLinkColor (c);
3325 /////////////////////////////////////////////////////////////////////
3326 } else if (com=="setMapLinkStyle")
3328 if (parser.checkParCount(1))
3330 s=parser.parString (ok,0);
3331 if (ok) setMapLinkStyle(s);
3333 /////////////////////////////////////////////////////////////////////
3334 } else if (com=="setHeading")
3336 if (selection.isEmpty() )
3338 parser.setError (Aborted,"Nothing selected");
3341 parser.setError (Aborted,"Type of selection is not a branch");
3342 } else if (parser.checkParCount(1))
3344 s=parser.parString (ok,0);
3348 /////////////////////////////////////////////////////////////////////
3349 } else if (com=="setHideExport")
3351 if (selection.isEmpty() )
3353 parser.setError (Aborted,"Nothing selected");
3354 } else if (selectionType()!=TreeItem::Branch && selectionType() != TreeItem::MapCenter &&selectionType()!=TreeItem::Image)
3356 parser.setError (Aborted,"Type of selection is not a branch or floatimage");
3357 } else if (parser.checkParCount(1))
3359 b=parser.parBool(ok,0);
3360 if (ok) setHideExport (b);
3362 /////////////////////////////////////////////////////////////////////
3363 } else if (com=="setIncludeImagesHorizontally")
3365 if (selection.isEmpty() )
3367 parser.setError (Aborted,"Nothing selected");
3370 parser.setError (Aborted,"Type of selection is not a branch");
3371 } else if (parser.checkParCount(1))
3373 b=parser.parBool(ok,0);
3374 if (ok) setIncludeImagesHor(b);
3376 /////////////////////////////////////////////////////////////////////
3377 } else if (com=="setIncludeImagesVertically")
3379 if (selection.isEmpty() )
3381 parser.setError (Aborted,"Nothing selected");
3384 parser.setError (Aborted,"Type of selection is not a branch");
3385 } else if (parser.checkParCount(1))
3387 b=parser.parBool(ok,0);
3388 if (ok) setIncludeImagesVer(b);
3390 /////////////////////////////////////////////////////////////////////
3391 } else if (com=="setHideLinkUnselected")
3393 if (selection.isEmpty() )
3395 parser.setError (Aborted,"Nothing selected");
3396 } else if ( selectionType()!=TreeItem::Branch && selectionType()!= TreeItem::MapCenter && selectionType()!=TreeItem::Image)
3398 parser.setError (Aborted,"Type of selection does not allow hiding the link");
3399 } else if (parser.checkParCount(1))
3401 b=parser.parBool(ok,0);
3402 if (ok) setHideLinkUnselected(b);
3404 /////////////////////////////////////////////////////////////////////
3405 } else if (com=="setSelectionColor")
3407 if (parser.checkParCount(1))
3409 QColor c=parser.parColor (ok,0);
3410 if (ok) setSelectionColorInt (c);
3412 /////////////////////////////////////////////////////////////////////
3413 } else if (com=="setURL")
3415 if (selection.isEmpty() )
3417 parser.setError (Aborted,"Nothing selected");
3420 parser.setError (Aborted,"Type of selection is not a branch");
3421 } else if (parser.checkParCount(1))
3423 s=parser.parString (ok,0);
3426 /////////////////////////////////////////////////////////////////////
3427 } else if (com=="setVymLink")
3429 if (selection.isEmpty() )
3431 parser.setError (Aborted,"Nothing selected");
3434 parser.setError (Aborted,"Type of selection is not a branch");
3435 } else if (parser.checkParCount(1))
3437 s=parser.parString (ok,0);
3438 if (ok) setVymLink(s);
3441 /////////////////////////////////////////////////////////////////////
3442 else if (com=="setFlag")
3444 if (selection.isEmpty() )
3446 parser.setError (Aborted,"Nothing selected");
3449 parser.setError (Aborted,"Type of selection is not a branch");
3450 } else if (parser.checkParCount(1))
3452 s=parser.parString(ok,0);
3455 selb->activateStandardFlag(s);
3456 selb->updateFlagsToolbar();
3459 /////////////////////////////////////////////////////////////////////
3460 } else if (com=="setFrameType")
3462 if (selection.isEmpty() )
3464 parser.setError (Aborted,"Nothing selected");
3467 parser.setError (Aborted,"Type of selection is not a branch");
3468 } else if (parser.checkParCount(1))
3470 s=parser.parString(ok,0);
3474 /////////////////////////////////////////////////////////////////////
3475 } else if (com=="sortChildren")
3477 if (selection.isEmpty() )
3479 parser.setError (Aborted,"Nothing selected");
3482 parser.setError (Aborted,"Type of selection is not a branch");
3483 } else if (parser.checkParCount(0))
3487 /////////////////////////////////////////////////////////////////////
3488 } else if (com=="toggleFlag")
3490 if (selection.isEmpty() )
3492 parser.setError (Aborted,"Nothing selected");
3495 parser.setError (Aborted,"Type of selection is not a branch");
3496 } else if (parser.checkParCount(1))
3498 s=parser.parString(ok,0);
3501 selb->toggleStandardFlag(s);
3502 selb->updateFlagsToolbar();
3505 /////////////////////////////////////////////////////////////////////
3506 } else if (com=="unscroll")
3508 if (selection.isEmpty() )
3510 parser.setError (Aborted,"Nothing selected");
3513 parser.setError (Aborted,"Type of selection is not a branch");
3514 } else if (parser.checkParCount(0))
3516 if (!unscrollBranch (selb))
3517 parser.setError (Aborted,"Could not unscroll branch");
3519 /////////////////////////////////////////////////////////////////////
3520 } else if (com=="unscrollChildren")
3522 if (selection.isEmpty() )
3524 parser.setError (Aborted,"Nothing selected");
3527 parser.setError (Aborted,"Type of selection is not a branch");
3528 } else if (parser.checkParCount(0))
3530 unscrollChildren ();
3532 /////////////////////////////////////////////////////////////////////
3533 } else if (com=="unsetFlag")
3535 if (selection.isEmpty() )
3537 parser.setError (Aborted,"Nothing selected");
3540 parser.setError (Aborted,"Type of selection is not a branch");
3541 } else if (parser.checkParCount(1))
3543 s=parser.parString(ok,0);
3546 selb->deactivateStandardFlag(s);
3547 selb->updateFlagsToolbar();
3551 parser.setError (Aborted,"Unknown command");
3554 if (parser.errorLevel()==NoError)
3556 // setChanged(); FIXME should not be called e.g. for export?!
3561 // TODO Error handling
3562 qWarning("VymModel::parseAtom: Error!");
3563 qWarning(parser.errorMessage());
3567 void VymModel::runScript (QString script)
3569 parser.setScript (script);
3571 while (parser.next() )
3572 parseAtom(parser.getAtom());
3575 void VymModel::setExportMode (bool b)
3577 // should be called before and after exports
3578 // depending on the settings
3579 if (b && settings.value("/export/useHideExport","true")=="true")
3580 setHideTmpMode (HideExport);
3582 setHideTmpMode (HideNone);
3585 void VymModel::exportImage(QString fname, bool askName, QString format)
3589 fname=getMapName()+".png";
3596 QFileDialog *fd=new QFileDialog (NULL);
3597 fd->setCaption (tr("Export map as image"));
3598 fd->setDirectory (lastImageDir);
3599 fd->setFileMode(QFileDialog::AnyFile);
3600 fd->setFilters (imageIO.getFilters() );
3603 fl=fd->selectedFiles();
3605 format=imageIO.getType(fd->selectedFilter());
3609 setExportMode (true);
3610 QPixmap pix (getPixmap());
3611 pix.save(fname, format);
3612 setExportMode (false);
3616 void VymModel::exportXML(QString dir, bool askForName)
3620 dir=browseDirectory(NULL,tr("Export XML to directory"));
3621 if (dir =="" && !reallyWriteDirectory(dir) )
3625 // Hide stuff during export, if settings want this
3626 setExportMode (true);
3628 // Create subdirectories
3631 // write to directory
3632 QString saveFile=saveToDir (dir,mapName+"-",true,getTotalBBox().topLeft() ,NULL);
3635 file.setName ( dir + "/"+mapName+".xml");
3636 if ( !file.open( QIODevice::WriteOnly ) )
3638 // This should neverever happen
3639 QMessageBox::critical (0,tr("Critical Export Error"),tr("VymModel::exportXML couldn't open %1").arg(file.name()));
3643 // Write it finally, and write in UTF8, no matter what
3644 QTextStream ts( &file );
3645 ts.setEncoding (QTextStream::UnicodeUTF8);
3649 // Now write image, too
3650 exportImage (dir+"/images/"+mapName+".png",false,"PNG");
3652 setExportMode (false);
3655 void VymModel::exportASCII(QString fname,bool askName)
3660 ex.setFile (mapName+".txt");
3666 //ex.addFilter ("TXT (*.txt)");
3667 ex.setDir(lastImageDir);
3668 //ex.setCaption(vymName+ " -" +tr("Export as ASCII")+" "+tr("(still experimental)"));
3673 setExportMode(true);
3675 setExportMode(false);
3679 void VymModel::exportXHTML (const QString &dir, bool askForName)
3681 ExportXHTMLDialog dia(NULL);
3682 dia.setFilePath (filePath );
3683 dia.setMapName (mapName );
3685 if (dir!="") dia.setDir (dir);
3691 if (dia.exec()!=QDialog::Accepted)
3695 QDir d (dia.getDir());
3696 // Check, if warnings should be used before overwriting
3697 // the output directory
3698 if (d.exists() && d.count()>0)
3701 warn.showCancelButton (true);
3702 warn.setText(QString(
3703 "The directory %1 is not empty.\n"
3704 "Do you risk to overwrite some of its contents?").arg(d.path() ));
3705 warn.setCaption("Warning: Directory not empty");
3706 warn.setShowAgainName("mainwindow/overwrite-dir-xhtml");
3708 if (warn.exec()!=QDialog::Accepted) ok=false;
3715 exportXML (dia.getDir(),false );
3716 dia.doExport(mapName );
3717 //if (dia.hasChanged()) setChanged();
3721 void VymModel::exportOOPresentation(const QString &fn, const QString &cf)
3726 if (ex.setConfigFile(cf))
3728 setExportMode (true);
3729 ex.exportPresentation();
3730 setExportMode (false);
3737 //////////////////////////////////////////////
3739 //////////////////////////////////////////////
3741 void VymModel::registerEditor(QWidget *me)
3743 mapEditor=(MapEditor*)me;
3744 for (int i=0; i<mapCenters.count(); i++)
3745 mapCenters.at(i)->setMapEditor(mapEditor);
3748 void VymModel::unregisterEditor(QWidget *)
3753 void VymModel::setContextPos(QPointF p)
3758 void VymModel::unsetContextPos()
3760 contextPos=QPointF();
3763 void VymModel::updateNoteFlag()
3766 BranchObj *bo=getSelectedBranch();
3769 bo->updateNoteFlag();
3770 mainWindow->updateActions();
3774 void VymModel::updateRelPositions()
3776 for (int i=0; i<mapCenters.count(); i++)
3777 mapCenters.at(i)->updateRelPositions();
3780 void VymModel::reposition()
3782 for (int i=0;i<mapCenters.count(); i++)
3783 mapCenters.at(i)->reposition(); // for positioning heading
3786 QPolygonF VymModel::shape(BranchObj *bo)
3788 // Creating (arbitrary) shapes
3791 QRectF rb=bo->getBBox();
3792 if (bo->getDepth()==0)
3794 // Just take BBox of this mapCenter
3795 p<<rb.topLeft()<<rb.topRight()<<rb.bottomRight()<<rb.bottomLeft();
3799 // Take union of BBox and TotalBBox
3801 QRectF ra=bo->getTotalBBox();
3802 if (bo->getOrientation()==LinkableMapObj::LeftOfCenter)
3805 <<QPointF (rb.topLeft().x(), ra.topLeft().y() )
3808 <<QPointF (rb.bottomLeft().x(), ra.bottomLeft().y() ) ;
3810 p <<ra.bottomRight()
3812 <<QPointF (rb.topRight().x(), ra.topRight().y() )
3815 <<QPointF (rb.bottomRight().x(), ra.bottomRight().y() ) ;
3820 void VymModel::moveAway(LinkableMapObj *lmo)
3824 // Move all branches and MapCenters away from lmo
3825 // to avoid collisions
3830 BranchObj *boA=(BranchObj*)lmo;
3832 for (int i=0; i<mapCenters.count(); i++)
3834 boB=mapCenters.at(i);
3837 PolygonCollisionResult r = PolygonCollision(pA, pB, QPoint(0,0));
3840 <<" ("<<qPrintable(boA->getHeading() )<<")"
3841 <<" with ("<< qPrintable (boB->getHeading() )
3844 <<" minT="<<r.minTranslation<<endl<<endl;
3848 QPixmap VymModel::getPixmap()
3850 QRectF mapRect=getTotalBBox();
3851 QPixmap pix((int)mapRect.width()+2,(int)mapRect.height()+1);
3854 pp.setRenderHints(mapEditor->renderHints());
3856 // Don't print the visualisation of selection
3857 selection.unselect();
3859 mapScene->render ( &pp,
3860 QRectF(0,0,mapRect.width()+2,mapRect.height()+2),
3861 QRectF(mapRect.x(),mapRect.y(),mapRect.width(),mapRect.height() ));
3863 // Restore selection
3864 selection.reselect();
3870 void VymModel::setMapLinkStyle (const QString & s)
3875 case LinkableMapObj::Line :
3878 case LinkableMapObj::Parabel:
3879 snow="StyleParabel";
3881 case LinkableMapObj::PolyLine:
3882 snow="StylePolyLine";
3884 case LinkableMapObj::PolyParabel:
3885 snow="StylePolyParabel";
3888 snow="UndefinedStyle";
3893 QString("setMapLinkStyle (\"%1\")").arg(s),
3894 QString("setMapLinkStyle (\"%1\")").arg(snow),
3895 QString("Set map link style (\"%1\")").arg(s)
3899 linkstyle=LinkableMapObj::Line;
3900 else if (s=="StyleParabel")
3901 linkstyle=LinkableMapObj::Parabel;
3902 else if (s=="StylePolyLine")
3903 linkstyle=LinkableMapObj::PolyLine;
3904 else if (s=="StylePolyParabel")
3905 linkstyle=LinkableMapObj::PolyParabel;
3907 linkstyle=LinkableMapObj::UndefinedStyle;
3914 bo->setLinkStyle(bo->getDefLinkStyle());
3920 LinkableMapObj::Style VymModel::getMapLinkStyle ()
3925 void VymModel::setMapDefLinkColor(QColor col)
3927 if ( !col.isValid() ) return;
3929 QString("setMapDefLinkColor (\"%1\")").arg(getMapDefLinkColor().name()),
3930 QString("setMapDefLinkColor (\"%1\")").arg(col.name()),
3931 QString("Set map link color to %1").arg(col.name())
3945 void VymModel::setMapLinkColorHintInt()
3947 // called from setMapLinkColorHint(lch) or at end of parse
3957 void VymModel::setMapLinkColorHint(LinkableMapObj::ColorHint lch)
3960 setMapLinkColorHintInt();
3963 void VymModel::toggleMapLinkColorHint()
3965 if (linkcolorhint==LinkableMapObj::HeadingColor)
3966 linkcolorhint=LinkableMapObj::DefaultColor;
3968 linkcolorhint=LinkableMapObj::HeadingColor;
3978 void VymModel::selectMapBackgroundImage ()
3980 Q3FileDialog *fd=new Q3FileDialog( NULL);
3981 fd->setMode (Q3FileDialog::ExistingFile);
3982 fd->addFilter (QString (tr("Images") + " (*.png *.bmp *.xbm *.jpg *.png *.xpm *.gif *.pnm)"));
3983 ImagePreview *p =new ImagePreview (fd);
3984 fd->setContentsPreviewEnabled( TRUE );
3985 fd->setContentsPreview( p, p );
3986 fd->setPreviewMode( Q3FileDialog::Contents );
3987 fd->setCaption(vymName+" - " +tr("Load background image"));
3988 fd->setDir (lastImageDir);
3991 if ( fd->exec() == QDialog::Accepted )
3993 // TODO selectMapBackgroundImg in QT4 use: lastImageDir=fd->directory();
3994 lastImageDir=QDir (fd->dirPath());
3995 setMapBackgroundImage (fd->selectedFile());
3999 void VymModel::setMapBackgroundImage (const QString &fn) //FIXME missing savestate
4001 QColor oldcol=mapScene->backgroundBrush().color();
4005 QString ("setMapBackgroundImage (%1)").arg(oldcol.name()),
4007 QString ("setMapBackgroundImage (%1)").arg(col.name()),
4008 QString("Set background color of map to %1").arg(col.name()));
4011 brush.setTextureImage (QPixmap (fn));
4012 mapScene->setBackgroundBrush(brush);
4015 void VymModel::selectMapBackgroundColor()
4017 QColor col = QColorDialog::getColor( mapScene->backgroundBrush().color(), NULL);
4018 if ( !col.isValid() ) return;
4019 setMapBackgroundColor( col );
4023 void VymModel::setMapBackgroundColor(QColor col)
4025 QColor oldcol=mapScene->backgroundBrush().color();
4027 QString ("setMapBackgroundColor (\"%1\")").arg(oldcol.name()),
4028 QString ("setMapBackgroundColor (\"%1\")").arg(col.name()),
4029 QString("Set background color of map to %1").arg(col.name()));
4030 mapScene->setBackgroundBrush(col);
4033 QColor VymModel::getMapBackgroundColor()
4035 return mapScene->backgroundBrush().color();
4039 LinkableMapObj::ColorHint VymModel::getMapLinkColorHint()
4041 return linkcolorhint;
4044 QColor VymModel::getMapDefLinkColor()
4046 return defLinkColor;
4049 void VymModel::setMapDefXLinkColor(QColor col)
4054 QColor VymModel::getMapDefXLinkColor()
4056 return defXLinkColor;
4059 void VymModel::setMapDefXLinkWidth (int w)
4064 int VymModel::getMapDefXLinkWidth()
4066 return defXLinkWidth;
4069 void VymModel::move(const double &x, const double &y)
4071 BranchObj *bo = getSelectedBranch();
4073 (selectionType()==TreeItem::Branch ||
4074 selectionType()==TreeItem::MapCenter ||
4075 selectionType()==TreeItem::Image
4078 QPointF ap(bo->getAbsPos());
4082 QString ps=qpointfToString(ap);
4083 QString s=getSelectString();
4086 s, "move "+qpointfToString(to),
4087 QString("Move %1 to %2").arg(getObjectName(bo)).arg(ps));
4095 void VymModel::moveRel (const double &x, const double &y)
4097 BranchObj *bo = getSelectedBranch();
4099 (selectionType()==TreeItem::Branch ||
4100 selectionType()==TreeItem::MapCenter ||
4101 selectionType()==TreeItem::Image
4105 QPointF rp(bo->getRelPos());
4109 QString ps=qpointfToString (bo->getRelPos());
4110 QString s=getSelectString(bo);
4113 s, "moveRel "+qpointfToString(to),
4114 QString("Move %1 to relative position %2").arg(getObjectName(bo)).arg(ps));
4115 ((OrnamentedObj*)bo)->move2RelPos (x,y);
4124 void VymModel::animate()
4126 animationTimer->stop();
4129 while (i<animObjList.size() )
4131 bo=(BranchObj*)animObjList.at(i);
4136 animObjList.removeAt(i);
4143 QItemSelection sel=selModel->selection();
4144 emit (selectionChanged(sel,sel));
4147 if (!animObjList.isEmpty()) animationTimer->start();
4151 void VymModel::startAnimation(BranchObj *bo, const QPointF &start, const QPointF &dest)
4153 if (bo && bo->getDepth()>0)
4156 ap.setStart (start);
4158 ap.setTicks (animationTicks);
4159 ap.setAnimated (true);
4160 bo->setAnimation (ap);
4161 animObjList.append( bo );
4162 animationTimer->setSingleShot (true);
4163 animationTimer->start(animationInterval);
4167 void VymModel::stopAnimation (MapObj *mo)
4169 int i=animObjList.indexOf(mo);
4171 animObjList.removeAt (i);
4174 void VymModel::sendSelection()
4176 if (netstate!=Server) return;
4177 sendData (QString("select (\"%1\")").arg(selection.getSelectString()) );
4180 void VymModel::newServer()
4184 tcpServer = new QTcpServer(this);
4185 if (!tcpServer->listen(QHostAddress::Any,port)) {
4186 QMessageBox::critical(NULL, "vym server",
4187 QString("Unable to start the server: %1.").arg(tcpServer->errorString()));
4188 //FIXME needed? we are no widget any longer... close();
4191 connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
4193 cout<<"Server is running on port "<<tcpServer->serverPort()<<endl;
4196 void VymModel::connectToServer()
4199 server="salam.suse.de";
4201 clientSocket = new QTcpSocket (this);
4202 clientSocket->abort();
4203 clientSocket->connectToHost(server ,port);
4204 connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
4205 connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
4206 this, SLOT(displayNetworkError(QAbstractSocket::SocketError)));
4208 cout<<"connected to "<<qPrintable (server)<<" port "<<port<<endl;
4213 void VymModel::newClient()
4215 QTcpSocket *newClient = tcpServer->nextPendingConnection();
4216 connect(newClient, SIGNAL(disconnected()),
4217 newClient, SLOT(deleteLater()));
4219 cout <<"ME::newClient at "<<qPrintable( newClient->peerAddress().toString() )<<endl;
4221 clientList.append (newClient);
4225 void VymModel::sendData(const QString &s)
4227 if (clientList.size()==0) return;
4229 // Create bytearray to send
4231 QDataStream out(&block, QIODevice::WriteOnly);
4232 out.setVersion(QDataStream::Qt_4_0);
4234 // Reserve some space for blocksize
4237 // Write sendCounter
4238 out << sendCounter++;
4243 // Go back and write blocksize so far
4244 out.device()->seek(0);
4245 quint16 bs=(quint16)(block.size() - 2*sizeof(quint16));
4249 cout << "ME::sendData bs="<<bs<<" counter="<<sendCounter<<" s="<<qPrintable(s)<<endl;
4251 for (int i=0; i<clientList.size(); ++i)
4253 //cout << "Sending \""<<qPrintable (s)<<"\" to "<<qPrintable (clientList.at(i)->peerAddress().toString())<<endl;
4254 clientList.at(i)->write (block);
4258 void VymModel::readData ()
4260 while (clientSocket->bytesAvailable() >=(int)sizeof(quint16) )
4263 cout <<"readData bytesAvail="<<clientSocket->bytesAvailable();
4267 QDataStream in(clientSocket);
4268 in.setVersion(QDataStream::Qt_4_0);
4276 cout << " t="<<qPrintable (t)<<endl;
4282 void VymModel::displayNetworkError(QAbstractSocket::SocketError socketError)
4284 switch (socketError) {
4285 case QAbstractSocket::RemoteHostClosedError:
4287 case QAbstractSocket::HostNotFoundError:
4288 QMessageBox::information(NULL, vymName +" Network client",
4289 "The host was not found. Please check the "
4290 "host name and port settings.");
4292 case QAbstractSocket::ConnectionRefusedError:
4293 QMessageBox::information(NULL, vymName + " Network client",
4294 "The connection was refused by the peer. "
4295 "Make sure the fortune server is running, "
4296 "and check that the host name and port "
4297 "settings are correct.");
4300 QMessageBox::information(NULL, vymName + " Network client",
4301 QString("The following error occurred: %1.")
4302 .arg(clientSocket->errorString()));
4309 void VymModel::selectMapSelectionColor()
4311 QColor col = QColorDialog::getColor( defLinkColor, NULL);
4312 setSelectionColor (col);
4315 void VymModel::setSelectionColorInt (QColor col)
4317 if ( !col.isValid() ) return;
4319 QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
4320 QString("setSelectionColor (%1)").arg(col.name()),
4321 QString("Set color of selection box to %1").arg(col.name())
4324 mapEditor->setSelectionColor (col);
4327 void VymModel::updateSelection()
4329 cout << "VM::updateSelection ()\n";
4330 QItemSelection newsel=selModel->selection();
4331 updateSelection (newsel);
4334 void VymModel::updateSelection(const QItemSelection &oldsel)
4336 QItemSelection newsel=selModel->selection();
4337 cout << "VM::updateSelection new=";
4338 if (!newsel.indexes().isEmpty() )
4339 cout << newsel.indexes().first().row()<<"," << newsel.indexes().first().column();
4341 if (!oldsel.indexes().isEmpty() )
4342 cout << oldsel.indexes().first().row()<<"," << oldsel.indexes().first().column();
4344 //emit (selectionChanged(newsel,oldsel));
4345 ensureSelectionVisible();
4349 void VymModel::setSelectionColor(QColor col)
4351 if ( !col.isValid() ) return;
4353 QString("setSelectionColor (%1)").arg(mapEditor->getSelectionColor().name()),
4354 QString("setSelectionColor (%1)").arg(col.name()),
4355 QString("Set color of selection box to %1").arg(col.name())
4357 setSelectionColorInt (col);
4360 QColor VymModel::getSelectionColor()
4362 return mapEditor->getSelectionColor();
4365 void VymModel::setHideTmpMode (HideTmpMode mode)
4368 for (int i=0;i<mapCenters.count(); i++)
4369 mapCenters.at(i)->setHideTmp (mode);
4371 // FIXME needed? scene()->update();
4375 QRectF VymModel::getTotalBBox()
4378 for (int i=0;i<mapCenters.count(); i++)
4379 r=addBBox (mapCenters.at(i)->getTotalBBox(), r);
4383 //////////////////////////////////////////////
4384 // Selection related
4385 //////////////////////////////////////////////
4387 void VymModel::setSelectionModel (QItemSelectionModel *sm)
4390 cout << "VM::setSelModel selModel="<<selModel<<endl;
4393 QItemSelectionModel* VymModel::getSelectionModel()
4398 void VymModel::setSelectionBlocked (bool b)
4403 selection.unblock();
4406 bool VymModel::isSelectionBlocked()
4408 return selection.isBlocked();
4411 bool VymModel::select ()
4413 QModelIndex index=selModel->selectedIndexes().first(); // TODO no multiselections yet
4415 TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
4416 return select (item->getLMO() );
4419 bool VymModel::select (const QString &s)
4421 LinkableMapObj *lmo=findObjBySelect(s);
4423 // Finally select the found object
4433 bool VymModel::select (LinkableMapObj *lmo)
4435 QItemSelection oldsel=selModel->selection();
4439 TreeItem *ti=lmo->getTreeItem();
4440 QModelIndex ix=index(ti);
4441 selModel->select (ix,QItemSelectionModel::ClearAndSelect );
4442 //updateSelection(oldsel); //FIXME needed?
4448 void VymModel::unselect()
4450 selModel->clearSelection();
4453 void VymModel::reselect()
4455 selection.reselect();
4458 void VymModel::ensureSelectionVisible()
4460 LinkableMapObj *lmo=getSelectedLMO();
4461 if (lmo &&mapEditor) mapEditor->ensureVisible (lmo->getBBox() );
4465 void VymModel::selectInt (LinkableMapObj *lmo)
4467 if (selection.select(lmo))
4469 //selection.update();
4470 sendSelection (); // FIXME VM use signal
4475 void VymModel::selectNextBranchInt()
4477 // Increase number of branch
4478 LinkableMapObj *sel=getSelectedBranch();
4481 QString s=getSelectString();
4487 part=s.section(",",-1);
4489 num=part.right(part.length() - 3);
4491 s=s.left (s.length() -num.length());
4494 num=QString ("%1").arg(num.toUInt()+1);
4498 // Try to select this one
4499 if (select (s)) return;
4501 // We have no direct successor,
4502 // try to increase the parental number in order to
4503 // find a successor with same depth
4505 int d=getSelectedLMO()->getDepth();
4510 while (!found && d>0)
4512 s=s.section (",",0,d-1);
4513 // replace substring of current depth in s with "1"
4514 part=s.section(",",-1);
4516 num=part.right(part.length() - 3);
4520 // increase number of parent
4521 num=QString ("%1").arg(num.toUInt()+1);
4522 s=s.section (",",0,d-2) + ","+ typ+num;
4525 // Special case, look at orientation
4526 if (getSelectedLMO()->getOrientation()==LinkableMapObj::RightOfCenter)
4527 num=QString ("%1").arg(num.toUInt()+1);
4529 num=QString ("%1").arg(num.toUInt()-1);
4534 // pad to oldDepth, select the first branch for each depth
4535 for (i=d;i<oldDepth;i++)
4540 if ( getSelectedBranch()->countBranches()>0)
4548 // try to select the freshly built string
4556 void VymModel::selectPrevBranchInt()
4558 // Decrease number of branch
4559 BranchObj *bo=getSelectedBranch();
4562 QString s=selection.getSelectString();
4568 part=s.section(",",-1);
4570 num=part.right(part.length() - 3);
4572 s=s.left (s.length() -num.length());
4574 int n=num.toInt()-1;
4577 num=QString ("%1").arg(n);
4580 // Try to select this one
4581 if (n>=0 && select (s)) return;
4583 // We have no direct precessor,
4584 // try to decrease the parental number in order to
4585 // find a precessor with same depth
4587 int d=getSelectedLMO()->getDepth();
4592 while (!found && d>0)
4594 s=s.section (",",0,d-1);
4595 // replace substring of current depth in s with "1"
4596 part=s.section(",",-1);
4598 num=part.right(part.length() - 3);
4602 // decrease number of parent
4603 num=QString ("%1").arg(num.toInt()-1);
4604 s=s.section (",",0,d-2) + ","+ typ+num;
4607 // Special case, look at orientation
4608 if (getSelectedLMO()->getOrientation()==LinkableMapObj::RightOfCenter)
4609 num=QString ("%1").arg(num.toInt()-1);
4611 num=QString ("%1").arg(num.toInt()+1);
4616 // pad to oldDepth, select the last branch for each depth
4617 for (i=d;i<oldDepth;i++)
4621 if ( getSelectedBranch()->countBranches()>0)
4622 s+=",bo:"+ QString ("%1").arg( getSelectedBranch()->countBranches()-1 );
4629 // try to select the freshly built string
4637 void VymModel::selectUpperBranch()
4639 if (selection.isBlocked() ) return;
4641 BranchObj *bo=getSelectedBranch();
4642 if (bo && selectionType()==TreeItem::Branch)
4644 if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
4645 selectPrevBranchInt();
4647 if (bo->getDepth()==1)
4648 selectNextBranchInt();
4650 selectPrevBranchInt();
4654 void VymModel::selectLowerBranch()
4656 if (selection.isBlocked() ) return;
4658 BranchObj *bo=getSelectedBranch();
4659 if (bo && selectionType()==TreeItem::Branch)
4661 if (bo->getOrientation()==LinkableMapObj::RightOfCenter)
4662 selectNextBranchInt();
4664 if (bo->getDepth()==1)
4665 selectPrevBranchInt();
4667 selectNextBranchInt();
4672 void VymModel::selectLeftBranch()
4674 if (selection.isBlocked() ) return;
4676 QItemSelection oldsel=selModel->selection();
4679 LinkableMapObj *sel=getSelectedBranch();
4682 if (selectionType()== TreeItem::MapCenter)
4684 QModelIndex ix=getSelectedIndex();
4685 selModel->select (index (rowCount(ix)-1,0,ix),QItemSelectionModel::ClearAndSelect );
4688 par=(BranchObj*)(sel->getParObj());
4689 if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
4692 if (selectionType() == TreeItem::Branch ||
4693 selectionType() == TreeItem::Image)
4695 QModelIndex ix=getSelectedIndex();
4697 selModel->select (ix,QItemSelectionModel::ClearAndSelect );
4702 if (selectionType() == TreeItem::Branch )
4704 selectLastSelectedBranch();
4709 updateSelection (oldsel);
4713 void VymModel::selectRightBranch()
4715 if (selection.isBlocked() ) return;
4717 QItemSelection oldsel=selModel->selection();
4720 LinkableMapObj *sel=getSelectedBranch();
4723 if (selectionType()== TreeItem::MapCenter)
4725 QModelIndex ix=getSelectedIndex();
4726 selModel->select (index (0,0,ix),QItemSelectionModel::ClearAndSelect );
4729 par=(BranchObj*)(sel->getParObj());
4730 if (sel->getOrientation()==LinkableMapObj::RightOfCenter)
4733 if (selectionType() == TreeItem::Branch )
4735 selectLastSelectedBranch();
4741 if (selectionType() == TreeItem::Branch ||
4742 selectionType() == TreeItem::Image)
4744 QModelIndex ix=getSelectedIndex();
4746 selModel->select (ix,QItemSelectionModel::ClearAndSelect );
4750 updateSelection (oldsel);
4754 void VymModel::selectFirstBranch()
4756 BranchObj *bo1=getSelectedBranch();
4761 par=(BranchObj*)(bo1->getParObj());
4763 bo2=par->getFirstBranch();
4765 selection.select(bo2);
4767 ensureSelectionVisible();
4773 void VymModel::selectLastBranch()
4775 BranchObj *bo1=getSelectedBranch();
4780 par=(BranchObj*)(bo1->getParObj());
4782 bo2=par->getLastBranch();
4785 selection.select(bo2);
4787 ensureSelectionVisible();
4793 void VymModel::selectLastSelectedBranch()
4795 QItemSelection oldsel=selModel->selection();
4797 BranchObj *bo1=getSelectedBranch();
4801 cout << "bo1="<<bo1->getHeading().toStdString()<<endl;
4802 bo2=bo1->getLastSelectedBranch();
4805 cout << "bo2="<<bo2->getHeading().toStdString()<<endl;
4811 void VymModel::selectParent()
4813 LinkableMapObj *lmo=getSelectedLMO();
4817 par=(BranchObj*)(lmo->getParObj());
4821 ensureSelectionVisible();
4826 TreeItem::Type VymModel::selectionType()
4828 QModelIndexList list=selModel->selectedIndexes();
4829 if (list.isEmpty()) return TreeItem::Undefined;
4830 TreeItem *ti = static_cast<TreeItem*>(list.first().internalPointer());
4831 return ti->getType();
4835 LinkableMapObj* VymModel::getSelectedLMO()
4837 QModelIndexList list=selModel->selectedIndexes();
4838 if (!list.isEmpty() )
4840 TreeItem *ti = static_cast<TreeItem*>(list.first().internalPointer());
4841 TreeItem::Type type=ti->getType();
4842 if (type ==TreeItem::Branch || type==TreeItem::MapCenter || type==TreeItem::Image)
4844 return ti->getLMO();
4850 BranchObj* VymModel::getSelectedBranch()
4852 QModelIndexList list=selModel->selectedIndexes();
4853 if (!list.isEmpty() )
4855 TreeItem *ti = static_cast<TreeItem*>(list.first().internalPointer());
4856 TreeItem::Type type=ti->getType();
4857 if (type ==TreeItem::Branch || type==TreeItem::MapCenter)
4859 return (BranchObj*)ti->getLMO();
4866 TreeItem* VymModel::getSelectedTreeItem()
4868 // FIXME this may not only be branch, but also float etc...
4869 BranchObj* bo=getSelectedBranch();
4870 if (bo) return bo->getTreeItem(); // FIXME VM get directly from treemodl
4874 QModelIndex VymModel::getSelectedIndex()
4876 QModelIndexList list=selModel->selectedIndexes();
4877 if (list.isEmpty() )
4878 return QModelIndex();
4880 return list.first();
4883 FloatImageObj* VymModel::getSelectedFloatImage()
4885 return selection.getFloatImage();
4888 QString VymModel::getSelectString ()
4890 return selection.getSelectString();
4893 QString VymModel::getSelectString (LinkableMapObj *lmo) // FIXME VM needs to use TreeModel
4897 if (typeid(*lmo)==typeid(BranchObj) ||
4898 typeid(*lmo)==typeid(MapCenterObj) )
4900 LinkableMapObj *par=lmo->getParObj();
4903 if (lmo->getDepth() ==1)
4904 // Mainbranch, return
4905 s= "bo:" + QString("%1").arg(((BranchObj*)lmo)->getNum());
4907 // Branch, call myself recursively
4908 s= getSelectString(par) + ",bo:" + QString("%1").arg(((BranchObj*)lmo)->getNum());
4912 int i=mapCenters.indexOf ((MapCenterObj*)lmo);
4913 if (i>=0) s=QString("mc:%1").arg(i);