From a03358fe219b35c495d2f6216287c5b724ad7856 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Sj=C3=B6lund?= Date: Fri, 7 Jan 2011 08:33:22 +0000 Subject: [PATCH] - Replaced tab characters with 2 spaces (mostly in C sources since Eclipse/MDT usually manages to avoid using tabs) $ svn diff Compiler/ | grep ^- | grep -v ^--- | wc -l 4771 $ svn diff c_runtime/ | grep ^- | grep -v ^--- | wc -l 13365 $ svn diff OMNotebook/ | grep ^- | grep -v ^--- | wc -l 17341 $ svn diff OMShell/ | grep ^- | grep -v ^--- | wc -l 582 git-svn-id: https://openmodelica.org/svn/OpenModelica/trunk@7662 f25d12d1-65f4-0310-ae8a-bbce733d8d8e --- OMNotebook/3Dpkg/SimulationData.cpp | 1222 +-- OMNotebook/3Dpkg/SimulationData.h | 170 +- OMNotebook/3Dpkg/VisualizationWidget.cpp | 596 +- OMNotebook/3Dpkg/VisualizationWidget.h | 68 +- .../notebookgrammarTokenTypes.hpp | 352 +- OMNotebook/OMNotebookQT4/application.h | 6 +- OMNotebook/OMNotebookQT4/cell.cpp | 1698 ++-- OMNotebook/OMNotebookQT4/cell.h | 292 +- OMNotebook/OMNotebookQT4/cellapplication.cpp | 1270 +-- OMNotebook/OMNotebookQT4/cellapplication.h | 62 +- .../OMNotebookQT4/cellcommandcenter.cpp | 56 +- OMNotebook/OMNotebookQT4/cellcommands.cpp | 1086 +-- OMNotebook/OMNotebookQT4/cellcommands.h | 250 +- OMNotebook/OMNotebookQT4/cellcursor.cpp | 1074 +-- OMNotebook/OMNotebookQT4/cellcursor.h | 92 +- OMNotebook/OMNotebookQT4/celldocument.cpp | 2648 +++--- OMNotebook/OMNotebookQT4/celldocument.h | 308 +- OMNotebook/OMNotebookQT4/celldocumentview.h | 16 +- OMNotebook/OMNotebookQT4/cellfactory.cpp | 10 +- OMNotebook/OMNotebookQT4/cellfactory.h | 24 +- OMNotebook/OMNotebookQT4/cellgroup.cpp | 874 +- OMNotebook/OMNotebookQT4/cellgroup.h | 74 +- .../OMNotebookQT4/cellparserfactory.cpp | 10 +- OMNotebook/OMNotebookQT4/cellstyle.h | 108 +- .../OMNotebookQT4/chaptercountervisitor.cpp | 316 +- .../OMNotebookQT4/chaptercountervisitor.h | 42 +- OMNotebook/OMNotebookQT4/command.h | 10 +- .../OMNotebookQT4/commandcompletion.cpp | 666 +- OMNotebook/OMNotebookQT4/commandcompletion.h | 44 +- OMNotebook/OMNotebookQT4/commandunit.h | 86 +- OMNotebook/OMNotebookQT4/cursorcommands.h | 328 +- OMNotebook/OMNotebookQT4/cursorposvisitor.h | 124 +- OMNotebook/OMNotebookQT4/document.h | 212 +- OMNotebook/OMNotebookQT4/documentview.h | 10 +- OMNotebook/OMNotebookQT4/evalthread.cpp | 86 +- OMNotebook/OMNotebookQT4/evalthread.h | 12 +- OMNotebook/OMNotebookQT4/factory.h | 6 +- OMNotebook/OMNotebookQT4/graphcell.cpp | 18 +- OMNotebook/OMNotebookQT4/graphcell.h | 358 +- OMNotebook/OMNotebookQT4/graphcelldelegate.h | 8 +- .../OMNotebookQT4/highlighterthread.cpp | 428 +- OMNotebook/OMNotebookQT4/highlighterthread.h | 36 +- OMNotebook/OMNotebookQT4/imagesizedlg.h | 120 +- OMNotebook/OMNotebookQT4/indent.cpp | 796 +- OMNotebook/OMNotebookQT4/indent.h | 66 +- OMNotebook/OMNotebookQT4/inputcell.cpp | 3056 +++---- OMNotebook/OMNotebookQT4/inputcell.h | 262 +- OMNotebook/OMNotebookQT4/inputcelldelegate.h | 8 +- OMNotebook/OMNotebookQT4/notebook.cpp | 7280 ++++++++--------- OMNotebook/OMNotebookQT4/notebook.h | 580 +- OMNotebook/OMNotebookQT4/notebookcommands.h | 4 +- OMNotebook/OMNotebookQT4/notebooksocket.cpp | 536 +- OMNotebook/OMNotebookQT4/notebooksocket.h | 52 +- OMNotebook/OMNotebookQT4/omc_communicator.cpp | 610 +- .../OMNotebookQT4/omcinteractiveenvironment.h | 32 +- .../OMNotebookQT4/openmodelicahighlighter.cpp | 972 +-- .../OMNotebookQT4/openmodelicahighlighter.h | 64 +- OMNotebook/OMNotebookQT4/otherdlg.h | 84 +- OMNotebook/OMNotebookQT4/printervisitor.h | 52 +- OMNotebook/OMNotebookQT4/puretextvisitor.cpp | 264 +- OMNotebook/OMNotebookQT4/puretextvisitor.h | 40 +- OMNotebook/OMNotebookQT4/qcombobox_search.cpp | 74 +- OMNotebook/OMNotebookQT4/qcombobox_search.h | 22 +- OMNotebook/OMNotebookQT4/qtapp.cpp | 24 +- .../OMNotebookQT4/removehighlightervisitor.h | 52 +- OMNotebook/OMNotebookQT4/replaceallvisitor.h | 244 +- OMNotebook/OMNotebookQT4/rule.h | 12 +- OMNotebook/OMNotebookQT4/searchform.cpp | 1122 +-- OMNotebook/OMNotebookQT4/searchform.h | 54 +- .../OMNotebookQT4/serializingvisitor.cpp | 790 +- OMNotebook/OMNotebookQT4/serializingvisitor.h | 48 +- OMNotebook/OMNotebookQT4/stripstring.h | 510 +- OMNotebook/OMNotebookQT4/stylesheet.cpp | 880 +- OMNotebook/OMNotebookQT4/stylesheet.h | 44 +- OMNotebook/OMNotebookQT4/syntaxhighlighter.h | 24 +- OMNotebook/OMNotebookQT4/textcell.cpp | 1662 ++-- OMNotebook/OMNotebookQT4/textcell.h | 186 +- .../OMNotebookQT4/textcursorcommands.cpp | 930 +-- OMNotebook/OMNotebookQT4/textcursorcommands.h | 400 +- OMNotebook/OMNotebookQT4/treeview.cpp | 160 +- .../OMNotebookQT4/updategroupcellvisitor.cpp | 104 +- .../OMNotebookQT4/updategroupcellvisitor.h | 36 +- .../OMNotebookQT4/updatelinkvisitor.cpp | 208 +- OMNotebook/OMNotebookQT4/updatelinkvisitor.h | 42 +- OMNotebook/OMNotebookQT4/visitor.h | 6 +- OMNotebook/OMNotebookQT4/xmlnodename.h | 38 +- OMNotebook/OMNotebookQT4/xmlparser.cpp | 30 +- OMNotebook/OMNotebookQT4/xmlparser.h | 48 +- OMNotebook/Pltpkg2/compoundWidget.cpp | 102 +- OMNotebook/Pltpkg2/compoundWidget.h | 20 +- OMNotebook/Pltpkg2/curve.cpp | 44 +- OMNotebook/Pltpkg2/curve.h | 26 +- OMNotebook/Pltpkg2/dataSelect.cpp | 16 +- OMNotebook/Pltpkg2/focusRect.h | 66 +- OMNotebook/Pltpkg2/graphScene.h | 30 +- OMNotebook/Pltpkg2/graphWidget.cpp | 150 +- OMNotebook/Pltpkg2/graphWidget.h | 348 +- OMNotebook/Pltpkg2/graphWindow.cpp | 74 +- OMNotebook/Pltpkg2/graphWindow.h | 22 +- OMNotebook/Pltpkg2/label.h | 44 +- OMNotebook/Pltpkg2/legendLabel.cpp | 146 +- OMNotebook/Pltpkg2/legendLabel.h | 50 +- OMNotebook/Pltpkg2/line2D.cpp | 2 +- OMNotebook/Pltpkg2/line2D.h | 6 +- OMNotebook/Pltpkg2/point.cpp | 38 +- OMNotebook/Pltpkg2/point.h | 2 +- OMNotebook/Pltpkg2/preferenceWindow.cpp | 160 +- OMNotebook/Pltpkg2/preferenceWindow.h | 16 +- OMNotebook/Pltpkg2/variableData.cpp | 16 +- OMNotebook/Pltpkg2/variableData.h | 20 +- OMNotebook/Pltpkg2/variablewindow.cpp | 146 +- OMNotebook/Pltpkg2/variablewindow.h | 24 +- OMNotebook/Pltpkg2/verticalLabel.h | 72 +- 113 files changed, 19712 insertions(+), 19712 deletions(-) diff --git a/OMNotebook/3Dpkg/SimulationData.cpp b/OMNotebook/3Dpkg/SimulationData.cpp index b76610941e1..0adc270892e 100644 --- a/OMNotebook/3Dpkg/SimulationData.cpp +++ b/OMNotebook/3Dpkg/SimulationData.cpp @@ -40,489 +40,489 @@ using namespace IAEX; using namespace std; namespace IAEX { - // Implementation SimulationData - SimulationData::SimulationData(void) - { - keyPoints_ = new QList(); - objects_ = new QList(); - visroot_ = new SoSeparator(); - - cam_ = new SoPerspectiveCamera(); - cam_->position = SbVec3f(5,5,5); - //visroot_->addChild(cam_); - // temp - //SimulationObject obj("cube", "obj", visroot_); - //objects_->append(obj); - //SimulationObject obj2("sphere", "obj2", visroot_); - //objects_->append(obj2); - } - - SimulationData::~SimulationData(void) - { - } - - void SimulationData::addObject(QString type, QString name, QString params) { - SimulationObject obj(type, name, params, visroot_); - objects_->append(obj); - } - - void SimulationData::parse(QString filename) { - //SimulationObject obj("sphere", "h", "", visroot_); - //objects_->append(obj); - - //start_time = 0; - //SimulationKeypoint point1(start_time); - //point1.addVar("x", SbVec3f(0,0,0)); - //point1.addVar("rot", SbVec3f(0,1,0)); - //keyPoints_->append(point1); - - //SimulationKeypoint point2(2.5); - //point2.addVar("x", SbVec3f(0,5,0)); - //point2.addVar("rot", SbVec3f(-0.2f,1,0.2f)); - //keyPoints_->append(point2); - - //end_time = 5; - //SimulationKeypoint point3(end_time); - //point3.addVar("x", SbVec3f(5,0,0)); - //point3.addVar("rot", SbVec3f(0.5,1,0.5)); - //keyPoints_->append(point3); - } - - void SimulationData::clear() { - //while (!keyPoints_->isEmpty()) { - // delete keyPoints_->takeFirst(); - //} - keyPoints_->clear(); - objects_->clear(); - visroot_->removeAllChildren(); - - SoSeparator *decoration = new SoSeparator(); - SoCube *hc = new SoCube();//5,0,5); - SoScale *sc = new SoScale();//5,0,2.5); - sc->scaleFactor.setValue(5, 0.001, 5); - SoDrawStyle *style = new SoDrawStyle(); - style->style = SoDrawStyleElement::LINES; - SoLightModel *lightm = new SoLightModel(); - lightm->model = SoLightModel::BASE_COLOR; - - decoration->addChild(style); - decoration->addChild(lightm); - decoration->addChild(sc); - decoration->addChild(hc); - - visroot_->addChild(decoration); - } - - int SimulationData::size(void) { - return keyPoints_->size(); - } - - // time in ms - float SimulationData::get_start_time(void) { - if (keyPoints_->size() > 0) { - return keyPoints_->at(0)->time; - } else { - return 0; - } - } - - float SimulationData::get_end_time(void) { - if (keyPoints_->size() > 0) { - return keyPoints_->back()->time; - } else { - return 0; - } - } - - void SimulationData::setFrame(float time) { -// cout << "setFrame(" << time << ")" << endl; - if (keyPoints_->size() < 2) { - // not enough! - return; - } - - if (time > end_time) { - return; - } - - QList::iterator k; - SimulationKeypoint *k1 = NULL; - SimulationKeypoint *k2 = NULL; - - for (k = keyPoints_->begin(); k != keyPoints_->end(); k++) { - float t = (*k)->time; - if (t > time) { - break; - } - } - if (k == keyPoints_->end()) { - k--; - } - - k2 = *k; - k--; - k1 = *k; - - QList keylist = k1->vars.keys(); - QList::iterator t; - //cout << "k1 keys: "; - //for (t = keylist.begin(); t != keylist.end(); t++) { - // cout << (*t).toStdString() << "=" << k1->vars.value(*t) << endl; - //} - //cout << endl; - - //keylist = k2->vars.keys(); - //cout << "k2 keys: "; - //for (t = keylist.begin(); t != keylist.end(); t++) { - // cout << (*t).toStdString() << "=" << k2->vars.value(*t) << endl; - //} - //cout << endl; - - QList::iterator i; - for (i = objects_->begin(); i != objects_->end(); i++) { - QString name = (*i).getName(); - //cout << name.toStdString() << ","; - - //QString pos = (*i).getPosVar(); - //QString rot = (*i).getDirVar(); - //QString type = (*i).getType(); - - if ((*i).hasPosition) { - SbVec3f p1; - p1[0] = k1->vars.value(name + ".frame_a[1]"); - p1[1] = k1->vars.value(name + ".frame_a[2]"); - p1[2] = k1->vars.value(name + ".frame_a[3]"); - SbVec3f p2; - p2[0] = k2->vars.value(name + ".frame_a[1]"); - p2[1] = k2->vars.value(name + ".frame_a[2]"); - p2[2] = k2->vars.value(name + ".frame_a[3]"); - SbVec3f p = p2 - p1; - p = p1 + p * (float)(time - k1->time)/(float)(k2->time - k1->time); - - (*i).setPosition(p); - } - - if ((*i).hasRotation) { - SbVec3f r1; - r1[0] = k1->vars.value(name + ".frame_b[1]"); - r1[1] = k1->vars.value(name + ".frame_b[2]"); - r1[2] = k1->vars.value(name + ".frame_b[3]"); - SbVec3f r2; - r2[0] = k2->vars.value(name + ".frame_b[1]"); - r2[1] = k2->vars.value(name + ".frame_b[2]"); - r2[2] = k2->vars.value(name + ".frame_b[3]"); - float t = (float)(time - k1->time)/(float)(k2->time - k1->time); - - //SbRotation rot1 = SbRotation(SbVec3f(0,1,0), r1 - (*i).translation->translation.getValue()); - //SbRotation rot2 = SbRotation(SbVec3f(0,1,0), r2 - (*i).translation->translation.getValue()); - - //SbRotation rot = SbRotation::slerp(rot1, rot2, t); - SbVec3f r = r2 - r1; - r = r1 + r * t; - SbRotation rot = SbRotation(SbVec3f(0,1,0), r - (*i).translation->translation.getValue()); - - (*i).setRotationDir(rot); - } - - if ((*i).hasSize) { - SbVec3f s1; - s1[0] = k1->vars.value(name + ".size[1]"); - s1[1] = k1->vars.value(name + ".size[2]"); - s1[2] = k1->vars.value(name + ".size[3]"); - SbVec3f s2; - s2[0] = k2->vars.value(name + ".size[1]"); - s2[1] = k2->vars.value(name + ".size[2]"); - s2[2] = k2->vars.value(name + ".size[3]"); - SbVec3f s = s2 - s1; - s = s1 + s * (float)(time - k1->time)/(float)(k2->time - k1->time); - - (*i).setScale(s); - } - - if ((*i).hasOffset) { - SbVec3f o1; - o1[0] = k1->vars.value(name + ".offset[1]"); - o1[1] = k1->vars.value(name + ".offset[2]"); - o1[2] = k1->vars.value(name + ".offset[3]"); - SbVec3f o2; - o2[0] = k2->vars.value(name + ".offset[1]"); - o2[1] = k2->vars.value(name + ".offset[2]"); - o2[2] = k2->vars.value(name + ".offset[3]"); - SbVec3f o = o2 - o1; - o = o1 + o * (float)(time - k1->time)/(float)(k2->time - k1->time); - - (*i).setOffset(o); - } - /* if (rot != "") { - SbVec3f r1 = k1->vars.value(rot); - SbVec3f r2 = k2->vars.value(rot); - if (r1.length() == 0) { - r1.setValue(0,1,0); - } - if (r2.length() == 0) { - r2.setValue(0,1,0); - } - - SbVec3f r = r2 - r1; - r = r1 + r * (time - k1->time)/(k2->time - k1->time); - //cout << r[0] << " " << r[1] << " " << r[2] << endl; - - (*i).setRotationDir(r); - }*/ - } - //cout << endl; - } - - void SimulationData::addKeypoint(SimulationKeypoint *point) { - //QString tmp = point->toString(); - //cout << tmp.toStdString() << endl; - keyPoints_->append(point); - start_time = keyPoints_->at(0)->time; - end_time = keyPoints_->back()->time; - //cout << "size: " << keyPoints_->size() << endl; - } - - void SimulationData::viewAll(SbViewportRegion vpr) { - cam_->viewAll(visroot_, vpr, 1.0); - } - - // Implementation SimulationKeypoint - SimulationKeypoint::SimulationKeypoint(double time) { - this->time = time; - } - - SimulationKeypoint::SimulationKeypoint() { - this->time = 0; - } - - SimulationKeypoint::~SimulationKeypoint() { - } - - void SimulationKeypoint::addVar(QString name, float value) { - //cout << "addVar(" << name.toStdString() << ")=" << value << endl; - vars.insert(name, value); - } - - void SimulationKeypoint::setTime(double time) { - this->time = time; - } - - QString SimulationKeypoint::toString(void) { - QString tmp = ""; - - tmp = QString("Time: %1\n").arg(this->time); - tmp += "Vars:\n"; - - QHashIterator i(vars); - while (i.hasNext()) { - i.next(); - tmp += QString("\"%1\" : %2\n").arg(i.key()).arg(i.value()); - } - - return tmp; - } - - // Implementation SimulationObject - SimulationObject::SimulationObject(QString type, QString name, QString params, SoSeparator *parent) { - this->type = type; - this->name = name; - this->parent = parent; - - hasPosition = hasSize = hasOffset = hasRotation = false; - - QString rest = params; - int pos; - color = new SbColor(0.6f, 0.6f, 0.6f); - - while ((pos = rest.indexOf(";")) > 0) { - QString pair = rest.left(pos); - QString p = pair.left(pair.indexOf("=")); - QString v = pair.mid(pair.indexOf("=")+1); - - if (p == "color") { - this->color = parseColor(v); - } else if (p == "model") { - this->modelfilename = v; - } else if (p == "shape") { - this->shape = v; - } - - rest = rest.mid(pos+1); - } - - objectGroup = new SoSeparator(); - - if (type == "SimpleVisual.PositionRotation") { - hasPosition = true; - hasRotation = true; - } else if (type == "SimpleVisual.PositionSize") { - hasPosition = true; - hasSize = true; - } else if (type == "SimpleVisual.PositionRotationSize") { - hasSize = true; - hasPosition = true; - hasRotation = true; - } else if (type == "SimpleVisual.PositionRotationSizeOffset") { - hasSize = true; - hasPosition = true; - hasRotation = true; - hasOffset = true; - } else { // type == "SimpleVisual.Position" or unknown - hasPosition = true; - } - - SoBaseColor *col = new SoBaseColor(); - col->rgb = *color; - objectGroup->addChild(col); - - if (hasPosition) { - translation = new SoTranslation(); - objectGroup->addChild(translation); - } - - if (hasRotation) { - rotation = new SoRotation(); - objectGroup->addChild(rotation); - } - - if (hasOffset) { - offset = new SoTranslation(); - objectGroup->addChild(offset); - } - - if (hasSize) { - scale = new SoScale(); - objectGroup->addChild(scale); - } - - if (!modelfilename.isEmpty()) { - SoInput in; - if (in.openFile(modelfilename.toStdString().c_str())) { - SoSeparator *model = SoDB::readAll(&in); - if (model) { - objectGroup->addChild(model); - } - } - } else if (shape == "cube") { - SoCube *cube = new SoCube(); - cube->width = 1; - cube->height = 1; - cube->depth = 1; - objectGroup->addChild(cube); - } else if (shape == "cylinder") { - SoCylinder *cylinder = new SoCylinder(); - cylinder->radius = 1; - cylinder->height = 1; - objectGroup->addChild(cylinder); - } else { // eg sphere or unknown - SoSphere *sphere = new SoSphere(); - sphere->radius = 0.5; - objectGroup->addChild(sphere); - } - //if (type == "SimpleVisual.Cube") { - // SoCube *cube = new SoCube(); - // cube->width = 1; - // cube->height = 1; - // cube->depth = 1; - // objectGroup->addChild(cube); - //} else if (type == "SimpleVisual.Sphere") { - // SoSphere *sphere = new SoSphere(); - // sphere->radius = 1; - // objectGroup->addChild(new SoSphere()); - //} else - // objectGroup->addChild(new SoSphere()); - - parent->addChild(objectGroup); - } - - SbColor* SimulationObject::parseColor(QString coldef) { - if (coldef == "red") - return new SbColor(1.0f, 0.0f, 0.0f); - else if (coldef == "green") - return new SbColor(0.0f, 1.0f, 0.0f); - else if (coldef == "blue") - return new SbColor(0.0f, 0.0f, 1.0f); - else - return new SbColor(0.6f, 0.6f, 0.6f); - } -/* SimulationObject::SimulationObject(QString type, QString posVar, QString dirVar, SoSeparator *parent) { - this->type = type; - this->posVar = posVar; - this->dirVar = dirVar; - this->parent = parent; - - objectGroup = new SoSeparator(); - translation = new SoTranslation(); - rotation = new SoRotation(); - objectGroup->addChild(translation); - objectGroup->addChild(rotation); - - if (type == "cube") { - objectGroup->addChild(new SoCube()); - } else if (type == "sphere") { - objectGroup->addChild(new SoCube()); - } - - parent->addChild(objectGroup); - }*/ - - SimulationObject::~SimulationObject() { - } - - void SimulationObject::setPosition(SbVec3f pos) { -// cout << "setpos(" << pos[0] << "," << pos[1] << "," << pos[2] << ")" << endl; - translation->translation.setValue(pos); - } - - void SimulationObject::setOffset(SbVec3f pos) { -// cout << "setpos(" << pos[0] << "," << pos[1] << "," << pos[2] << ")" << endl; - offset->translation.setValue(pos); - } - - void SimulationObject::setRotationDir(SbRotation dir) { - //if (dir.length() > 0.01) - rotation->rotation.setValue(dir);//SbRotation(SbVec3f(0,1,0), dir - translation->translation.getValue())); - } - - void SimulationObject::setScale(SbVec3f s) { - //if (0 == s[0] == s[1] == s[2]) { - // //sanity check - // scale->scaleFactor.setValue(1, 1, 1); - //} else { - scale->scaleFactor.setValue(s[0], s[1], s[2]); - //} - } - - QString SimulationObject::getPosVar() { - return posVar; - } - QString SimulationObject::getName() { - return name; - } - void SimulationObject::setPosVar(QString val) { - posVar = val; - } - - QString SimulationObject::getDirVar() { - return dirVar; - } - void SimulationObject::setDirVar(QString val) { - dirVar = val; - } - - QString SimulationObject::getType() { - return type; - } - void SimulationObject::setType(QString val) { - type = val; - } - - SoSeparator* SimulationObject::getParent() { - return parent; - } - void SimulationObject::setParent(SoSeparator *val) { - parent = val; - } + // Implementation SimulationData + SimulationData::SimulationData(void) + { + keyPoints_ = new QList(); + objects_ = new QList(); + visroot_ = new SoSeparator(); + + cam_ = new SoPerspectiveCamera(); + cam_->position = SbVec3f(5,5,5); + //visroot_->addChild(cam_); + // temp + //SimulationObject obj("cube", "obj", visroot_); + //objects_->append(obj); + //SimulationObject obj2("sphere", "obj2", visroot_); + //objects_->append(obj2); + } + + SimulationData::~SimulationData(void) + { + } + + void SimulationData::addObject(QString type, QString name, QString params) { + SimulationObject obj(type, name, params, visroot_); + objects_->append(obj); + } + + void SimulationData::parse(QString filename) { + //SimulationObject obj("sphere", "h", "", visroot_); + //objects_->append(obj); + + //start_time = 0; + //SimulationKeypoint point1(start_time); + //point1.addVar("x", SbVec3f(0,0,0)); + //point1.addVar("rot", SbVec3f(0,1,0)); + //keyPoints_->append(point1); + + //SimulationKeypoint point2(2.5); + //point2.addVar("x", SbVec3f(0,5,0)); + //point2.addVar("rot", SbVec3f(-0.2f,1,0.2f)); + //keyPoints_->append(point2); + + //end_time = 5; + //SimulationKeypoint point3(end_time); + //point3.addVar("x", SbVec3f(5,0,0)); + //point3.addVar("rot", SbVec3f(0.5,1,0.5)); + //keyPoints_->append(point3); + } + + void SimulationData::clear() { + //while (!keyPoints_->isEmpty()) { + // delete keyPoints_->takeFirst(); + //} + keyPoints_->clear(); + objects_->clear(); + visroot_->removeAllChildren(); + + SoSeparator *decoration = new SoSeparator(); + SoCube *hc = new SoCube();//5,0,5); + SoScale *sc = new SoScale();//5,0,2.5); + sc->scaleFactor.setValue(5, 0.001, 5); + SoDrawStyle *style = new SoDrawStyle(); + style->style = SoDrawStyleElement::LINES; + SoLightModel *lightm = new SoLightModel(); + lightm->model = SoLightModel::BASE_COLOR; + + decoration->addChild(style); + decoration->addChild(lightm); + decoration->addChild(sc); + decoration->addChild(hc); + + visroot_->addChild(decoration); + } + + int SimulationData::size(void) { + return keyPoints_->size(); + } + + // time in ms + float SimulationData::get_start_time(void) { + if (keyPoints_->size() > 0) { + return keyPoints_->at(0)->time; + } else { + return 0; + } + } + + float SimulationData::get_end_time(void) { + if (keyPoints_->size() > 0) { + return keyPoints_->back()->time; + } else { + return 0; + } + } + + void SimulationData::setFrame(float time) { +// cout << "setFrame(" << time << ")" << endl; + if (keyPoints_->size() < 2) { + // not enough! + return; + } + + if (time > end_time) { + return; + } + + QList::iterator k; + SimulationKeypoint *k1 = NULL; + SimulationKeypoint *k2 = NULL; + + for (k = keyPoints_->begin(); k != keyPoints_->end(); k++) { + float t = (*k)->time; + if (t > time) { + break; + } + } + if (k == keyPoints_->end()) { + k--; + } + + k2 = *k; + k--; + k1 = *k; + + QList keylist = k1->vars.keys(); + QList::iterator t; + //cout << "k1 keys: "; + //for (t = keylist.begin(); t != keylist.end(); t++) { + // cout << (*t).toStdString() << "=" << k1->vars.value(*t) << endl; + //} + //cout << endl; + + //keylist = k2->vars.keys(); + //cout << "k2 keys: "; + //for (t = keylist.begin(); t != keylist.end(); t++) { + // cout << (*t).toStdString() << "=" << k2->vars.value(*t) << endl; + //} + //cout << endl; + + QList::iterator i; + for (i = objects_->begin(); i != objects_->end(); i++) { + QString name = (*i).getName(); + //cout << name.toStdString() << ","; + + //QString pos = (*i).getPosVar(); + //QString rot = (*i).getDirVar(); + //QString type = (*i).getType(); + + if ((*i).hasPosition) { + SbVec3f p1; + p1[0] = k1->vars.value(name + ".frame_a[1]"); + p1[1] = k1->vars.value(name + ".frame_a[2]"); + p1[2] = k1->vars.value(name + ".frame_a[3]"); + SbVec3f p2; + p2[0] = k2->vars.value(name + ".frame_a[1]"); + p2[1] = k2->vars.value(name + ".frame_a[2]"); + p2[2] = k2->vars.value(name + ".frame_a[3]"); + SbVec3f p = p2 - p1; + p = p1 + p * (float)(time - k1->time)/(float)(k2->time - k1->time); + + (*i).setPosition(p); + } + + if ((*i).hasRotation) { + SbVec3f r1; + r1[0] = k1->vars.value(name + ".frame_b[1]"); + r1[1] = k1->vars.value(name + ".frame_b[2]"); + r1[2] = k1->vars.value(name + ".frame_b[3]"); + SbVec3f r2; + r2[0] = k2->vars.value(name + ".frame_b[1]"); + r2[1] = k2->vars.value(name + ".frame_b[2]"); + r2[2] = k2->vars.value(name + ".frame_b[3]"); + float t = (float)(time - k1->time)/(float)(k2->time - k1->time); + + //SbRotation rot1 = SbRotation(SbVec3f(0,1,0), r1 - (*i).translation->translation.getValue()); + //SbRotation rot2 = SbRotation(SbVec3f(0,1,0), r2 - (*i).translation->translation.getValue()); + + //SbRotation rot = SbRotation::slerp(rot1, rot2, t); + SbVec3f r = r2 - r1; + r = r1 + r * t; + SbRotation rot = SbRotation(SbVec3f(0,1,0), r - (*i).translation->translation.getValue()); + + (*i).setRotationDir(rot); + } + + if ((*i).hasSize) { + SbVec3f s1; + s1[0] = k1->vars.value(name + ".size[1]"); + s1[1] = k1->vars.value(name + ".size[2]"); + s1[2] = k1->vars.value(name + ".size[3]"); + SbVec3f s2; + s2[0] = k2->vars.value(name + ".size[1]"); + s2[1] = k2->vars.value(name + ".size[2]"); + s2[2] = k2->vars.value(name + ".size[3]"); + SbVec3f s = s2 - s1; + s = s1 + s * (float)(time - k1->time)/(float)(k2->time - k1->time); + + (*i).setScale(s); + } + + if ((*i).hasOffset) { + SbVec3f o1; + o1[0] = k1->vars.value(name + ".offset[1]"); + o1[1] = k1->vars.value(name + ".offset[2]"); + o1[2] = k1->vars.value(name + ".offset[3]"); + SbVec3f o2; + o2[0] = k2->vars.value(name + ".offset[1]"); + o2[1] = k2->vars.value(name + ".offset[2]"); + o2[2] = k2->vars.value(name + ".offset[3]"); + SbVec3f o = o2 - o1; + o = o1 + o * (float)(time - k1->time)/(float)(k2->time - k1->time); + + (*i).setOffset(o); + } + /* if (rot != "") { + SbVec3f r1 = k1->vars.value(rot); + SbVec3f r2 = k2->vars.value(rot); + if (r1.length() == 0) { + r1.setValue(0,1,0); + } + if (r2.length() == 0) { + r2.setValue(0,1,0); + } + + SbVec3f r = r2 - r1; + r = r1 + r * (time - k1->time)/(k2->time - k1->time); + //cout << r[0] << " " << r[1] << " " << r[2] << endl; + + (*i).setRotationDir(r); + }*/ + } + //cout << endl; + } + + void SimulationData::addKeypoint(SimulationKeypoint *point) { + //QString tmp = point->toString(); + //cout << tmp.toStdString() << endl; + keyPoints_->append(point); + start_time = keyPoints_->at(0)->time; + end_time = keyPoints_->back()->time; + //cout << "size: " << keyPoints_->size() << endl; + } + + void SimulationData::viewAll(SbViewportRegion vpr) { + cam_->viewAll(visroot_, vpr, 1.0); + } + + // Implementation SimulationKeypoint + SimulationKeypoint::SimulationKeypoint(double time) { + this->time = time; + } + + SimulationKeypoint::SimulationKeypoint() { + this->time = 0; + } + + SimulationKeypoint::~SimulationKeypoint() { + } + + void SimulationKeypoint::addVar(QString name, float value) { + //cout << "addVar(" << name.toStdString() << ")=" << value << endl; + vars.insert(name, value); + } + + void SimulationKeypoint::setTime(double time) { + this->time = time; + } + + QString SimulationKeypoint::toString(void) { + QString tmp = ""; + + tmp = QString("Time: %1\n").arg(this->time); + tmp += "Vars:\n"; + + QHashIterator i(vars); + while (i.hasNext()) { + i.next(); + tmp += QString("\"%1\" : %2\n").arg(i.key()).arg(i.value()); + } + + return tmp; + } + + // Implementation SimulationObject + SimulationObject::SimulationObject(QString type, QString name, QString params, SoSeparator *parent) { + this->type = type; + this->name = name; + this->parent = parent; + + hasPosition = hasSize = hasOffset = hasRotation = false; + + QString rest = params; + int pos; + color = new SbColor(0.6f, 0.6f, 0.6f); + + while ((pos = rest.indexOf(";")) > 0) { + QString pair = rest.left(pos); + QString p = pair.left(pair.indexOf("=")); + QString v = pair.mid(pair.indexOf("=")+1); + + if (p == "color") { + this->color = parseColor(v); + } else if (p == "model") { + this->modelfilename = v; + } else if (p == "shape") { + this->shape = v; + } + + rest = rest.mid(pos+1); + } + + objectGroup = new SoSeparator(); + + if (type == "SimpleVisual.PositionRotation") { + hasPosition = true; + hasRotation = true; + } else if (type == "SimpleVisual.PositionSize") { + hasPosition = true; + hasSize = true; + } else if (type == "SimpleVisual.PositionRotationSize") { + hasSize = true; + hasPosition = true; + hasRotation = true; + } else if (type == "SimpleVisual.PositionRotationSizeOffset") { + hasSize = true; + hasPosition = true; + hasRotation = true; + hasOffset = true; + } else { // type == "SimpleVisual.Position" or unknown + hasPosition = true; + } + + SoBaseColor *col = new SoBaseColor(); + col->rgb = *color; + objectGroup->addChild(col); + + if (hasPosition) { + translation = new SoTranslation(); + objectGroup->addChild(translation); + } + + if (hasRotation) { + rotation = new SoRotation(); + objectGroup->addChild(rotation); + } + + if (hasOffset) { + offset = new SoTranslation(); + objectGroup->addChild(offset); + } + + if (hasSize) { + scale = new SoScale(); + objectGroup->addChild(scale); + } + + if (!modelfilename.isEmpty()) { + SoInput in; + if (in.openFile(modelfilename.toStdString().c_str())) { + SoSeparator *model = SoDB::readAll(&in); + if (model) { + objectGroup->addChild(model); + } + } + } else if (shape == "cube") { + SoCube *cube = new SoCube(); + cube->width = 1; + cube->height = 1; + cube->depth = 1; + objectGroup->addChild(cube); + } else if (shape == "cylinder") { + SoCylinder *cylinder = new SoCylinder(); + cylinder->radius = 1; + cylinder->height = 1; + objectGroup->addChild(cylinder); + } else { // eg sphere or unknown + SoSphere *sphere = new SoSphere(); + sphere->radius = 0.5; + objectGroup->addChild(sphere); + } + //if (type == "SimpleVisual.Cube") { + // SoCube *cube = new SoCube(); + // cube->width = 1; + // cube->height = 1; + // cube->depth = 1; + // objectGroup->addChild(cube); + //} else if (type == "SimpleVisual.Sphere") { + // SoSphere *sphere = new SoSphere(); + // sphere->radius = 1; + // objectGroup->addChild(new SoSphere()); + //} else + // objectGroup->addChild(new SoSphere()); + + parent->addChild(objectGroup); + } + + SbColor* SimulationObject::parseColor(QString coldef) { + if (coldef == "red") + return new SbColor(1.0f, 0.0f, 0.0f); + else if (coldef == "green") + return new SbColor(0.0f, 1.0f, 0.0f); + else if (coldef == "blue") + return new SbColor(0.0f, 0.0f, 1.0f); + else + return new SbColor(0.6f, 0.6f, 0.6f); + } +/* SimulationObject::SimulationObject(QString type, QString posVar, QString dirVar, SoSeparator *parent) { + this->type = type; + this->posVar = posVar; + this->dirVar = dirVar; + this->parent = parent; + + objectGroup = new SoSeparator(); + translation = new SoTranslation(); + rotation = new SoRotation(); + objectGroup->addChild(translation); + objectGroup->addChild(rotation); + + if (type == "cube") { + objectGroup->addChild(new SoCube()); + } else if (type == "sphere") { + objectGroup->addChild(new SoCube()); + } + + parent->addChild(objectGroup); + }*/ + + SimulationObject::~SimulationObject() { + } + + void SimulationObject::setPosition(SbVec3f pos) { +// cout << "setpos(" << pos[0] << "," << pos[1] << "," << pos[2] << ")" << endl; + translation->translation.setValue(pos); + } + + void SimulationObject::setOffset(SbVec3f pos) { +// cout << "setpos(" << pos[0] << "," << pos[1] << "," << pos[2] << ")" << endl; + offset->translation.setValue(pos); + } + + void SimulationObject::setRotationDir(SbRotation dir) { + //if (dir.length() > 0.01) + rotation->rotation.setValue(dir);//SbRotation(SbVec3f(0,1,0), dir - translation->translation.getValue())); + } + + void SimulationObject::setScale(SbVec3f s) { + //if (0 == s[0] == s[1] == s[2]) { + // //sanity check + // scale->scaleFactor.setValue(1, 1, 1); + //} else { + scale->scaleFactor.setValue(s[0], s[1], s[2]); + //} + } + + QString SimulationObject::getPosVar() { + return posVar; + } + QString SimulationObject::getName() { + return name; + } + void SimulationObject::setPosVar(QString val) { + posVar = val; + } + + QString SimulationObject::getDirVar() { + return dirVar; + } + void SimulationObject::setDirVar(QString val) { + dirVar = val; + } + + QString SimulationObject::getType() { + return type; + } + void SimulationObject::setType(QString val) { + type = val; + } + + SoSeparator* SimulationObject::getParent() { + return parent; + } + void SimulationObject::setParent(SoSeparator *val) { + parent = val; + } } @@ -531,133 +531,133 @@ namespace IAEX { - //void SimulationData::traverse(QDomNode frame, SoSeparator *parent) { - // QDomNode n = frame; //->firstChild(); - - // // while(!n.isNull()) { - // if (!n.isNull()) { - // QDomElement e = n.toElement(); - // if(!e.isNull()) { - // //cout << e.tagName().toStdString() << " " - // // << e.attribute("name").toStdString() << endl; - - // //if (e.tagName() == "node") { - // // SoSeparator *tmp = new SoSeparator(); - // // parent->addChild(tmp); - // // traverse(&n, tmp); - // //} else - // if (e.tagName() == "object") { - // SoSeparator *group = new SoSeparator(); - // QDomNode obj = n.firstChild(); - // while (!obj.isNull()) { - // QDomElement obj_element = obj.toElement(); - // if (!obj_element.isNull()) { - // if (obj_element.tagName() == "translation") { - // float x,y,z = 0.0f; - // QString str; - // str = obj_element.attribute("x"); - // x = str.toFloat(); - // str = obj_element.attribute("y"); - // y = str.toFloat(); - // str = obj_element.attribute("z"); - // z = str.toFloat(); - - // SoTranslation *transl = new SoTranslation(); - // transl->translation.setValue(x, y, z); - // group->addChild(transl); - // } else if (obj_element.tagName() == "rotation") { - // float x,y,z,angle = 0.0f; - // QString str; - // str = obj_element.attribute("x"); - // x = str.toFloat(); - // str = obj_element.attribute("y"); - // y = str.toFloat(); - // str = obj_element.attribute("z"); - // z = str.toFloat(); - // str = obj_element.attribute("angle"); - // angle = str.toFloat(); - - // SoRotation *rot = new SoRotation(); - // rot->rotation.setValue(SbVec3f(x, y, z), angle); - // group->addChild(rot); - // } else if (obj_element.tagName() == "scale") { - // float x,y,z = 0.0f; - // QString str; - // str = obj_element.attribute("x"); - // x = str.toFloat(); - // str = obj_element.attribute("y"); - // y = str.toFloat(); - // str = obj_element.attribute("z"); - // z = str.toFloat(); - - // SoScale *scale = new SoScale(); - // scale->scaleFactor.setValue(x, y, z); - // group->addChild(scale); - // } else if (obj_element.tagName() == "color") { - // float r,g,b = 0.0f; - // QString str; - // str = obj_element.attribute("r"); - // r = str.toFloat(); - // str = obj_element.attribute("g"); - // g = str.toFloat(); - // str = obj_element.attribute("b"); - // b = str.toFloat(); - - // SoBaseColor *col = new SoBaseColor(); - // col->rgb = SbColor(r, g, b); - // group->addChild(col); - // } else if (obj_element.tagName() == "object") { - // traverse(obj, group); - // } - // } - // obj = obj.nextSibling(); - // } - - // QString name = e.attribute("name"); - - // if (!name.isNull()) { - // SoMFString str; - // str.setValue(name.toStdString().data()); - - // SoAnnotation *annotation = new SoAnnotation; - // SoFont *font = new SoFont; - // SoText2 *text = new SoText2; - // SoBaseColor *col = new SoBaseColor; - // col->rgb = SbColor(1.0f, 1.0f, 1.0f); - - // text->string = str; - // font->name = "Arial:bold"; - // font->size = 14; - // annotation->addChild(col); - // annotation->addChild(font); - // annotation->addChild(text); - // group->addChild(annotation); - // } - - // QString style = e.attribute("primitive"); - // QString meshfile = e.attribute("mesh"); - // if (!meshfile.isNull()) { - - // } - // else if (style == "cube") { - // SoCube *cube = new SoCube(); - // group->addChild(cube); - // } else if (style == "cone") { - // SoCone *cone = new SoCone(); - // group->addChild(cone); - // } else if (style == "cylinder") { - // SoCylinder *cylinder = new SoCylinder(); - // group->addChild(cylinder); - // } else if (style == "sphere") { - // SoSphere *sphere = new SoSphere(); - // group->addChild(sphere); - // } - - // parent->addChild(group); - // } - // } - // // n = n.nextSibling(); - // } - //} + //void SimulationData::traverse(QDomNode frame, SoSeparator *parent) { + // QDomNode n = frame; //->firstChild(); + + // // while(!n.isNull()) { + // if (!n.isNull()) { + // QDomElement e = n.toElement(); + // if(!e.isNull()) { + // //cout << e.tagName().toStdString() << " " + // // << e.attribute("name").toStdString() << endl; + + // //if (e.tagName() == "node") { + // // SoSeparator *tmp = new SoSeparator(); + // // parent->addChild(tmp); + // // traverse(&n, tmp); + // //} else + // if (e.tagName() == "object") { + // SoSeparator *group = new SoSeparator(); + // QDomNode obj = n.firstChild(); + // while (!obj.isNull()) { + // QDomElement obj_element = obj.toElement(); + // if (!obj_element.isNull()) { + // if (obj_element.tagName() == "translation") { + // float x,y,z = 0.0f; + // QString str; + // str = obj_element.attribute("x"); + // x = str.toFloat(); + // str = obj_element.attribute("y"); + // y = str.toFloat(); + // str = obj_element.attribute("z"); + // z = str.toFloat(); + + // SoTranslation *transl = new SoTranslation(); + // transl->translation.setValue(x, y, z); + // group->addChild(transl); + // } else if (obj_element.tagName() == "rotation") { + // float x,y,z,angle = 0.0f; + // QString str; + // str = obj_element.attribute("x"); + // x = str.toFloat(); + // str = obj_element.attribute("y"); + // y = str.toFloat(); + // str = obj_element.attribute("z"); + // z = str.toFloat(); + // str = obj_element.attribute("angle"); + // angle = str.toFloat(); + + // SoRotation *rot = new SoRotation(); + // rot->rotation.setValue(SbVec3f(x, y, z), angle); + // group->addChild(rot); + // } else if (obj_element.tagName() == "scale") { + // float x,y,z = 0.0f; + // QString str; + // str = obj_element.attribute("x"); + // x = str.toFloat(); + // str = obj_element.attribute("y"); + // y = str.toFloat(); + // str = obj_element.attribute("z"); + // z = str.toFloat(); + + // SoScale *scale = new SoScale(); + // scale->scaleFactor.setValue(x, y, z); + // group->addChild(scale); + // } else if (obj_element.tagName() == "color") { + // float r,g,b = 0.0f; + // QString str; + // str = obj_element.attribute("r"); + // r = str.toFloat(); + // str = obj_element.attribute("g"); + // g = str.toFloat(); + // str = obj_element.attribute("b"); + // b = str.toFloat(); + + // SoBaseColor *col = new SoBaseColor(); + // col->rgb = SbColor(r, g, b); + // group->addChild(col); + // } else if (obj_element.tagName() == "object") { + // traverse(obj, group); + // } + // } + // obj = obj.nextSibling(); + // } + + // QString name = e.attribute("name"); + + // if (!name.isNull()) { + // SoMFString str; + // str.setValue(name.toStdString().data()); + + // SoAnnotation *annotation = new SoAnnotation; + // SoFont *font = new SoFont; + // SoText2 *text = new SoText2; + // SoBaseColor *col = new SoBaseColor; + // col->rgb = SbColor(1.0f, 1.0f, 1.0f); + + // text->string = str; + // font->name = "Arial:bold"; + // font->size = 14; + // annotation->addChild(col); + // annotation->addChild(font); + // annotation->addChild(text); + // group->addChild(annotation); + // } + + // QString style = e.attribute("primitive"); + // QString meshfile = e.attribute("mesh"); + // if (!meshfile.isNull()) { + + // } + // else if (style == "cube") { + // SoCube *cube = new SoCube(); + // group->addChild(cube); + // } else if (style == "cone") { + // SoCone *cone = new SoCone(); + // group->addChild(cone); + // } else if (style == "cylinder") { + // SoCylinder *cylinder = new SoCylinder(); + // group->addChild(cylinder); + // } else if (style == "sphere") { + // SoSphere *sphere = new SoSphere(); + // group->addChild(sphere); + // } + + // parent->addChild(group); + // } + // } + // // n = n.nextSibling(); + // } + //} #endif diff --git a/OMNotebook/3Dpkg/SimulationData.h b/OMNotebook/3Dpkg/SimulationData.h index 27ecc0d0a4f..d4ae8f583f8 100644 --- a/OMNotebook/3Dpkg/SimulationData.h +++ b/OMNotebook/3Dpkg/SimulationData.h @@ -59,92 +59,92 @@ namespace IAEX { - class SimulationKeypoint { - public: - SimulationKeypoint(double time); - SimulationKeypoint(); - ~SimulationKeypoint(void); - - void setTime(double time); - void addVar(QString name, float value); - QHash vars; - double time; - QString toString(void); - - private: - }; - - class SimulationObject { - public: -// SimulationObject(QString type, QString posVar, QString dirVar, SoSeparator *parent); - SimulationObject(QString type, QString name, QString params, SoSeparator *parent); - SimulationObject(SoSeparator *parent); - ~SimulationObject(void); - - QString getName(); - QString getPosVar(); - void setPosVar(QString val); - QString getDirVar(); - void setDirVar(QString val); - QString getType(); - void setType(QString val); - SoSeparator* getParent(); - void setParent(SoSeparator *val); - SbColor* parseColor(QString coldef); - - void setPosition(SbVec3f pos); - void setRotationDir(SbRotation dir); - void setScale(SbVec3f scale); - void setOffset(SbVec3f offset); - - bool hasPosition; - bool hasRotation; - bool hasSize; - bool hasOffset; - - SoTranslation *translation; - SoRotation *rotation; - SoScale *scale; - SoTranslation *offset; - - private: - QString name; - QString type; - QString posVar; - QString dirVar; - QString modelfilename; - QString shape; - - SbColor *color; - SoSeparator *objectGroup; + class SimulationKeypoint { + public: + SimulationKeypoint(double time); + SimulationKeypoint(); + ~SimulationKeypoint(void); + + void setTime(double time); + void addVar(QString name, float value); + QHash vars; + double time; + QString toString(void); + + private: + }; + + class SimulationObject { + public: +// SimulationObject(QString type, QString posVar, QString dirVar, SoSeparator *parent); + SimulationObject(QString type, QString name, QString params, SoSeparator *parent); + SimulationObject(SoSeparator *parent); + ~SimulationObject(void); + + QString getName(); + QString getPosVar(); + void setPosVar(QString val); + QString getDirVar(); + void setDirVar(QString val); + QString getType(); + void setType(QString val); + SoSeparator* getParent(); + void setParent(SoSeparator *val); + SbColor* parseColor(QString coldef); + + void setPosition(SbVec3f pos); + void setRotationDir(SbRotation dir); + void setScale(SbVec3f scale); + void setOffset(SbVec3f offset); + + bool hasPosition; + bool hasRotation; + bool hasSize; + bool hasOffset; + + SoTranslation *translation; + SoRotation *rotation; + SoScale *scale; + SoTranslation *offset; + + private: + QString name; + QString type; + QString posVar; + QString dirVar; + QString modelfilename; + QString shape; + + SbColor *color; + SoSeparator *objectGroup; SoSeparator *parent; - }; - - class SimulationData { - public: - SimulationData(void); - ~SimulationData(void); - - void parse(QString filename); - void clear(void); - int size(void); - float get_start_time(void); - float get_end_time(void); - void setFrame(float); - SoSeparator *getSceneGraph() { return visroot_; } - void addKeypoint(SimulationKeypoint *); - void addObject(QString type, QString name, QString params); - void viewAll(SbViewportRegion vpr); - - - private: - SoSeparator *visroot_; - SoPerspectiveCamera *cam_; - QList *keyPoints_; - QList *objects_; - float start_time; - float end_time; - }; + }; + + class SimulationData { + public: + SimulationData(void); + ~SimulationData(void); + + void parse(QString filename); + void clear(void); + int size(void); + float get_start_time(void); + float get_end_time(void); + void setFrame(float); + SoSeparator *getSceneGraph() { return visroot_; } + void addKeypoint(SimulationKeypoint *); + void addObject(QString type, QString name, QString params); + void viewAll(SbViewportRegion vpr); + + + private: + SoSeparator *visroot_; + SoPerspectiveCamera *cam_; + QList *keyPoints_; + QList *objects_; + float start_time; + float end_time; + }; } #endif diff --git a/OMNotebook/3Dpkg/VisualizationWidget.cpp b/OMNotebook/3Dpkg/VisualizationWidget.cpp index 4e212b0ba14..00f91d80876 100644 --- a/OMNotebook/3Dpkg/VisualizationWidget.cpp +++ b/OMNotebook/3Dpkg/VisualizationWidget.cpp @@ -34,90 +34,90 @@ namespace IAEX { - VisualizationWidget::VisualizationWidget(QWidget *parent) : QWidget(parent) - { + VisualizationWidget::VisualizationWidget(QWidget *parent) : QWidget(parent) + { //#ifdef HAVE_COIN - this->setMinimumWidth(600); - this->setMinimumHeight(300); - this->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); + this->setMinimumWidth(600); + this->setMinimumHeight(300); + this->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); - visframe_ = new QWidget(this); + visframe_ = new QWidget(this); - visframe_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); + visframe_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); #ifdef HAVE_COIN - simdata_ = new SimulationData(); - simdata_->setFrame(0); + simdata_ = new SimulationData(); + simdata_->setFrame(0); #endif - QFrame *buttonframe = new QFrame(); - QPushButton *playbutton = new QPushButton("Play"); - playbutton->setFixedWidth(32); - QPushButton *stopbutton = new QPushButton("Stop"); - stopbutton->setFixedWidth(32); - QPushButton *rewbutton = new QPushButton("Rew"); - rewbutton->setFixedWidth(32); - label_ = new QLabel(); - label_->setText("0"); - slider_ = new QSlider(Qt::Vertical); + QFrame *buttonframe = new QFrame(); + QPushButton *playbutton = new QPushButton("Play"); + playbutton->setFixedWidth(32); + QPushButton *stopbutton = new QPushButton("Stop"); + stopbutton->setFixedWidth(32); + QPushButton *rewbutton = new QPushButton("Rew"); + rewbutton->setFixedWidth(32); + label_ = new QLabel(); + label_->setText("0"); + slider_ = new QSlider(Qt::Vertical); #ifdef HAVE_COIN - slider_->setRange(1000*simdata_->get_start_time(), 1000*simdata_->get_end_time()); + slider_->setRange(1000*simdata_->get_start_time(), 1000*simdata_->get_end_time()); #endif - slider_->setValue(0); + slider_->setValue(0); #ifdef HAVE_COIN currentTime_ = 1000*simdata_->get_start_time(); #endif - timer_ = new QTimer(this); - // 40 fps - timer_->setInterval(25); - - connect(slider_, SIGNAL(valueChanged(int)), - this, SLOT(sliderChanged(int))); - connect(playbutton, SIGNAL(clicked()), - timer_, SLOT(start())); - connect(stopbutton, SIGNAL(clicked()), - timer_, SLOT(stop())); - connect(timer_, SIGNAL(timeout()), - this, SLOT(nextFrame())); - - buttonlayout_ = new QVBoxLayout(); - buttonlayout_->addWidget(playbutton); - buttonlayout_->addWidget(stopbutton); - buttonlayout_->addWidget(rewbutton); - buttonlayout_->addWidget(slider_); - buttonlayout_->addWidget(label_); - buttonlayout_->setAlignment(slider_, Qt::AlignHCenter); - buttonlayout_->setAlignment(label_, Qt::AlignHCenter); - - buttonframe->setLayout(buttonlayout_); + timer_ = new QTimer(this); + // 40 fps + timer_->setInterval(25); + + connect(slider_, SIGNAL(valueChanged(int)), + this, SLOT(sliderChanged(int))); + connect(playbutton, SIGNAL(clicked()), + timer_, SLOT(start())); + connect(stopbutton, SIGNAL(clicked()), + timer_, SLOT(stop())); + connect(timer_, SIGNAL(timeout()), + this, SLOT(nextFrame())); + + buttonlayout_ = new QVBoxLayout(); + buttonlayout_->addWidget(playbutton); + buttonlayout_->addWidget(stopbutton); + buttonlayout_->addWidget(rewbutton); + buttonlayout_->addWidget(slider_); + buttonlayout_->addWidget(label_); + buttonlayout_->setAlignment(slider_, Qt::AlignHCenter); + buttonlayout_->setAlignment(label_, Qt::AlignHCenter); + + buttonframe->setLayout(buttonlayout_); #ifdef HAVE_COIN - eviewer_ = new SoQtExaminerViewer(visframe_, NULL, TRUE, SoQtFullViewer::BUILD_NONE); - //eviewer_->setSize(SbVec2s(600,400)); + eviewer_ = new SoQtExaminerViewer(visframe_, NULL, TRUE, SoQtFullViewer::BUILD_NONE); + //eviewer_->setSize(SbVec2s(600,400)); //eviewer_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); - eviewer_->setSceneGraph(simdata_->getSceneGraph()); - eviewer_->setBackgroundColor(SbColor(0.95f, 0.95f, 0.95f)); + eviewer_->setSceneGraph(simdata_->getSceneGraph()); + eviewer_->setBackgroundColor(SbColor(0.95f, 0.95f, 0.95f)); #else new QLabel(QString("Coin3D was disabled on this build.\nThe rest of the widget still works so\nthe application won't crash when we send it data."), visframe_); #endif - //SoCamera *cam = eviewer_->getCamera(); - //cam-> + //SoCamera *cam = eviewer_->getCamera(); + //cam-> - QHBoxLayout *framelayout = new QHBoxLayout(this); - framelayout->addWidget(visframe_); - framelayout->addWidget(buttonframe); - this->setLayout(framelayout); + QHBoxLayout *framelayout = new QHBoxLayout(this); + framelayout->addWidget(visframe_); + framelayout->addWidget(buttonframe); + this->setLayout(framelayout); - server = new QTcpServer(this); - server->setMaxPendingConnections(500); - activeSocket = 0; + server = new QTcpServer(this); + server->setMaxPendingConnections(500); + activeSocket = 0; //#endif - } + } - VisualizationWidget::~VisualizationWidget(void) - { + VisualizationWidget::~VisualizationWidget(void) + { delete slider_; #ifdef HAVE_COIN delete eviewer_; @@ -126,293 +126,293 @@ namespace IAEX { delete server; delete buttonlayout_; delete timer_; - } + } - void VisualizationWidget::sliderChanged(int val) { - currentTime_ = val; - QString num; - num.setNum(currentTime_/1000.0); - label_->setText(num); + void VisualizationWidget::sliderChanged(int val) { + currentTime_ = val; + QString num; + num.setNum(currentTime_/1000.0); + label_->setText(num); #ifdef HAVE_COIN - simdata_->setFrame(currentTime_/1000.0); + simdata_->setFrame(currentTime_/1000.0); #endif - } + } - void VisualizationWidget::nextFrame() { - currentTime_ += 25; // FIIIIX! + void VisualizationWidget::nextFrame() { + currentTime_ += 25; // FIIIIX! #ifdef HAVE_COIN - if (currentTime_ > 1000*simdata_->get_end_time()) { - currentTime_ = 0; - } + if (currentTime_ > 1000*simdata_->get_end_time()) { + currentTime_ = 0; + } #endif - QString num; - num.setNum(currentTime_/1000.0); - label_->setText(num); - slider_->setValue(currentTime_); + QString num; + num.setNum(currentTime_/1000.0); + label_->setText(num); + slider_->setValue(currentTime_); #ifdef HAVE_COIN - simdata_->setFrame(currentTime_/1000.0); + simdata_->setFrame(currentTime_/1000.0); #endif - } + } - void VisualizationWidget::setServerState(bool listen) - { + void VisualizationWidget::setServerState(bool listen) + { //#ifdef HAVE_COIN - if(listen) - { - - if(!getServerState()) - if(!server->listen(QHostAddress::Any, quint16(7778))) - { - QTcpSocket s(this); - s.connectToHost("localhost", quint16(7778)); - if(s.waitForConnected(2000)) - { - QByteArray b; - - QDataStream ds(&b, QIODevice::WriteOnly); - ds.setVersion(QDataStream::Qt_4_2); - ds << quint32(0); - ds << QString("closeServer"); - ds.device()->seek(0); - ds << quint32(b.size()-sizeof(quint32)); - s.write(b); - s.flush(); - - s.disconnect(); - - qApp->processEvents(); - server->listen(QHostAddress::Any, quint16(7778)); - qApp->processEvents(); - - } - } - - emit newMessage("Listening for connections"); - - emit serverState(server->isListening()); - if(!connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()))) - QMessageBox::critical(0, QString("fel!"), QString("fel")); - } - else - { - server->close(); - emit newMessage("Port closed"); - emit serverState(false); - } + if(listen) + { + + if(!getServerState()) + if(!server->listen(QHostAddress::Any, quint16(7778))) + { + QTcpSocket s(this); + s.connectToHost("localhost", quint16(7778)); + if(s.waitForConnected(2000)) + { + QByteArray b; + + QDataStream ds(&b, QIODevice::WriteOnly); + ds.setVersion(QDataStream::Qt_4_2); + ds << quint32(0); + ds << QString("closeServer"); + ds.device()->seek(0); + ds << quint32(b.size()-sizeof(quint32)); + s.write(b); + s.flush(); + + s.disconnect(); + + qApp->processEvents(); + server->listen(QHostAddress::Any, quint16(7778)); + qApp->processEvents(); + + } + } + + emit newMessage("Listening for connections"); + + emit serverState(server->isListening()); + if(!connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()))) + QMessageBox::critical(0, QString("fel!"), QString("fel")); + } + else + { + server->close(); + emit newMessage("Port closed"); + emit serverState(false); + } //#endif - } + } - bool VisualizationWidget::getServerState() - { + bool VisualizationWidget::getServerState() + { //#ifdef HAVE_COIN - return server->isListening(); + return server->isListening(); //#else return 0; //#endif - } + } - void VisualizationWidget::acceptConnection() - { + void VisualizationWidget::acceptConnection() + { //#ifdef HAVE_COIN - while(server && server->hasPendingConnections()) - { - if( (activeSocket && (activeSocket->state() == QAbstractSocket::UnconnectedState) || !activeSocket)) - { + while(server && server->hasPendingConnections()) + { + if( (activeSocket && (activeSocket->state() == QAbstractSocket::UnconnectedState) || !activeSocket)) + { - emit newMessage("New connection accepted"); + emit newMessage("New connection accepted"); - activeSocket = server->nextPendingConnection(); - ds.setDevice(activeSocket); - ds.setVersion(QDataStream::Qt_4_2); + activeSocket = server->nextPendingConnection(); + ds.setDevice(activeSocket); + ds.setVersion(QDataStream::Qt_4_2); - blockSize = 0; + blockSize = 0; - connect(activeSocket, SIGNAL(readyRead()), this, SLOT(getData())); - } + connect(activeSocket, SIGNAL(readyRead()), this, SLOT(getData())); + } - qApp->processEvents(); - } + qApp->processEvents(); + } //#endif - } + } - void VisualizationWidget::getData() { + void VisualizationWidget::getData() { //#ifdef HAVE_COIN - disconnect(activeSocket, SIGNAL(readyRead()), 0, 0); - connect(activeSocket, SIGNAL(readyRead()), this, SLOT(getData())); - - while(activeSocket->bytesAvailable()) - { - if (blockSize == 0) - { - if (activeSocket->bytesAvailable() < sizeof(quint32)) - return; - - ds >> blockSize; - } - - if (activeSocket->bytesAvailable() < blockSize) - return; - - QString command; - ds >> command; - - if(command == QString("closeServer")) - { - setServerState(false); - activeSocket->disconnect(); - activeSocket->disconnectFromHost(); - } - else if(command == QString("ptolemyDataStream")) - { + disconnect(activeSocket, SIGNAL(readyRead()), 0, 0); + connect(activeSocket, SIGNAL(readyRead()), this, SLOT(getData())); + + while(activeSocket->bytesAvailable()) + { + if (blockSize == 0) + { + if (activeSocket->bytesAvailable() < sizeof(quint32)) + return; + + ds >> blockSize; + } + + if (activeSocket->bytesAvailable() < blockSize) + return; + + QString command; + ds >> command; + + if(command == QString("closeServer")) + { + setServerState(false); + activeSocket->disconnect(); + activeSocket->disconnectFromHost(); + } + else if(command == QString("ptolemyDataStream")) + { #ifdef HAVE_COIN - simdata_->clear(); + simdata_->clear(); #endif - emit newMessage("Recieving streaming data..."); - disconnect(activeSocket, SIGNAL(readyRead()), 0, 0); + emit newMessage("Recieving streaming data..."); + disconnect(activeSocket, SIGNAL(readyRead()), 0, 0); - connect(activeSocket, SIGNAL(readyRead()), this, SLOT(readPtolemyDataStream())); - connect(activeSocket, SIGNAL(disconnected()), this, SLOT(ptolemyDataStreamClosed())); + connect(activeSocket, SIGNAL(readyRead()), this, SLOT(readPtolemyDataStream())); + connect(activeSocket, SIGNAL(disconnected()), this, SLOT(ptolemyDataStreamClosed())); - variableCount = 0; - packetSize = 0; + variableCount = 0; + packetSize = 0; - return; - } + return; + } - blockSize = 0; - } + blockSize = 0; + } - connect(activeSocket, SIGNAL(readyRead()), this, SLOT(getData())); + connect(activeSocket, SIGNAL(readyRead()), this, SLOT(getData())); //#endif - } + } - void VisualizationWidget::readPtolemyDataStream() { + void VisualizationWidget::readPtolemyDataStream() { //#ifdef HAVE_COIN - QString tmp; - //qint32 variableCount = 0; - // qint32 packetSize = 0; - double d; - quint32 it = 0; - - do - { - if(packetSize == 0) - { - if(ds.device()->bytesAvailable() >= sizeof(qint32)) - ds >> packetSize; - else - return; - } - - uint a = ds.device()->bytesAvailable(); - if(a < packetSize) { - return; - } - - - if(variableCount == 0) - { -// variables.clear(); - QString info; - ds >> info; - std::cout << "info: " << info.toStdString() << std::endl; - QString tmp = info.trimmed(); - bool finished = false; - while (!finished) { - QString compound, objname, objtype, params; - int i,j; - i = tmp.indexOf("\n"); - int q = tmp.indexOf("Q"); - std::cout << "i: " << i << " & tmp = " << tmp.toStdString() << std::endl; - if (i < 0) { - finished = true; - compound = tmp; - } else { - compound = tmp.left(i); - tmp = tmp.mid(i+1); - } - std::cout << "compound: " << compound.toStdString() << std::endl; - - i = compound.indexOf(","); - j = compound.indexOf(":"); - if (i < 0) { - continue; - } else { - objname = compound.left(i); - params = compound.mid(i+2,(j-i)-3); - objtype = compound.mid(j+1); - - std::cout << "name: " << objname.toStdString() - << " & type: " << objtype.toStdString() - << " & params: " << params.toStdString() << std::endl; + QString tmp; + //qint32 variableCount = 0; + // qint32 packetSize = 0; + double d; + quint32 it = 0; + + do + { + if(packetSize == 0) + { + if(ds.device()->bytesAvailable() >= sizeof(qint32)) + ds >> packetSize; + else + return; + } + + uint a = ds.device()->bytesAvailable(); + if(a < packetSize) { + return; + } + + + if(variableCount == 0) + { +// variables.clear(); + QString info; + ds >> info; + std::cout << "info: " << info.toStdString() << std::endl; + QString tmp = info.trimmed(); + bool finished = false; + while (!finished) { + QString compound, objname, objtype, params; + int i,j; + i = tmp.indexOf("\n"); + int q = tmp.indexOf("Q"); + std::cout << "i: " << i << " & tmp = " << tmp.toStdString() << std::endl; + if (i < 0) { + finished = true; + compound = tmp; + } else { + compound = tmp.left(i); + tmp = tmp.mid(i+1); + } + std::cout << "compound: " << compound.toStdString() << std::endl; + + i = compound.indexOf(","); + j = compound.indexOf(":"); + if (i < 0) { + continue; + } else { + objname = compound.left(i); + params = compound.mid(i+2,(j-i)-3); + objtype = compound.mid(j+1); + + std::cout << "name: " << objname.toStdString() + << " & type: " << objtype.toStdString() + << " & params: " << params.toStdString() << std::endl; #ifdef HAVE_COIN - simdata_->addObject(objtype, objname, params); + simdata_->addObject(objtype, objname, params); #endif - } - } - - ds >> variableCount; - //std::cout << "variables: " << variableCount << std::endl; - - for(quint32 i = 0; i < variableCount; ++i) - { - ds >> tmp; - - //tmp = tmp.trimmed(); - //std::cout << i << ": " << tmp.toStdString() << std::endl; - //if(variables.find(tmp) != variables.end()) - // delete variables[tmp]; - //variables[tmp] = new VariableData(tmp, color); - } - packetSize = 0; - continue; - } - - ds >> variableCount; + } + } + + ds >> variableCount; + //std::cout << "variables: " << variableCount << std::endl; + + for(quint32 i = 0; i < variableCount; ++i) + { + ds >> tmp; + + //tmp = tmp.trimmed(); + //std::cout << i << ": " << tmp.toStdString() << std::endl; + //if(variables.find(tmp) != variables.end()) + // delete variables[tmp]; + //variables[tmp] = new VariableData(tmp, color); + } + packetSize = 0; + continue; + } + + ds >> variableCount; #ifdef HAVE_COIN - SimulationKeypoint *point = new SimulationKeypoint(); - - for(quint32 i = 0; i < variableCount; ++i) - { - ds >> tmp; - ds >> d; - if (0 == tmp.compare("time")) { - point->setTime(d); - } else { - point->addVar(tmp, d); - } -// std::cout << "var: " << tmp.toStdString() << " = " << d << std::endl; - //variables[tmp]->push_back(d); - } - simdata_->addKeypoint(point); - - packetSize = 0; - ++it; + SimulationKeypoint *point = new SimulationKeypoint(); + + for(quint32 i = 0; i < variableCount; ++i) + { + ds >> tmp; + ds >> d; + if (0 == tmp.compare("time")) { + point->setTime(d); + } else { + point->addVar(tmp, d); + } +// std::cout << "var: " << tmp.toStdString() << " = " << d << std::endl; + //variables[tmp]->push_back(d); + } + simdata_->addKeypoint(point); + + packetSize = 0; + ++it; #endif - } - while(activeSocket->bytesAvailable() >= sizeof(quint32)); + } + while(activeSocket->bytesAvailable() >= sizeof(quint32)); - if(activeSocket->state() != QAbstractSocket::ConnectedState) - ptolemyDataStreamClosed(); + if(activeSocket->state() != QAbstractSocket::ConnectedState) + ptolemyDataStreamClosed(); //#endif - } + } - void VisualizationWidget::ptolemyDataStreamClosed() { + void VisualizationWidget::ptolemyDataStreamClosed() { #ifdef HAVE_COIN - slider_->setRange(1000*simdata_->get_start_time(), 1000*simdata_->get_end_time()); - slider_->setValue(0); - //for(map::iterator i = variables.begin(); i != variables.end(); ++i) - // variableData.append(i->second); - //variables.clear(); - setServerState(false); + slider_->setRange(1000*simdata_->get_start_time(), 1000*simdata_->get_end_time()); + slider_->setValue(0); + //for(map::iterator i = variables.begin(); i != variables.end(); ++i) + // variableData.append(i->second); + //variables.clear(); + setServerState(false); - SoCamera *cam = eviewer_->getCamera(); - cam->viewAll(simdata_->getSceneGraph(), eviewer_->getViewportRegion()); + SoCamera *cam = eviewer_->getCamera(); + cam->viewAll(simdata_->getSceneGraph(), eviewer_->getViewportRegion()); - emit newMessage("Connection closed"); + emit newMessage("Connection closed"); #endif } diff --git a/OMNotebook/3Dpkg/VisualizationWidget.h b/OMNotebook/3Dpkg/VisualizationWidget.h index 7c5602e7b22..fc1e1211581 100644 --- a/OMNotebook/3Dpkg/VisualizationWidget.h +++ b/OMNotebook/3Dpkg/VisualizationWidget.h @@ -62,54 +62,54 @@ #include "SimulationData.h" namespace IAEX { - class VisualizationWidget : - public QWidget - { - Q_OBJECT + class VisualizationWidget : + public QWidget + { + Q_OBJECT - public: - VisualizationWidget(QWidget *parent); - ~VisualizationWidget(void); + public: + VisualizationWidget(QWidget *parent); + ~VisualizationWidget(void); - void setServerState(bool listen); - bool getServerState(void); + void setServerState(bool listen); + bool getServerState(void); signals: - void newMessage(QString message); - void serverState(bool); + void newMessage(QString message); + void serverState(bool); - public slots: - void getData(); - void acceptConnection(); - void sliderChanged(int val); - void nextFrame(); - void readPtolemyDataStream(); - void ptolemyDataStreamClosed(); + public slots: + void getData(); + void acceptConnection(); + void sliderChanged(int val); + void nextFrame(); + void readPtolemyDataStream(); + void ptolemyDataStreamClosed(); - private: + private: #ifdef HAVE_COIN - SoQtExaminerViewer *eviewer_; - SoQtRenderArea *renderarea_; + SoQtExaminerViewer *eviewer_; + SoQtRenderArea *renderarea_; #endif - QFrame *frame_; - QSlider *slider_; - QLabel *label_; + QFrame *frame_; + QSlider *slider_; + QLabel *label_; #ifdef HAVE_COIN - SimulationData *simdata_; + SimulationData *simdata_; #endif QWidget *visframe_; QVBoxLayout *buttonlayout_; QTimer* timer_; - int currentTime_; - QTextBrowser *input_; + int currentTime_; + QTextBrowser *input_; - QTcpServer* server; - QTcpSocket* activeSocket; - QDataStream ds; - quint32 blockSize; - quint32 variableCount; - quint32 packetSize; + QTcpServer* server; + QTcpSocket* activeSocket; + QDataStream ds; + quint32 blockSize; + quint32 variableCount; + quint32 packetSize; - }; + }; } diff --git a/OMNotebook/NotebookParser/notebookgrammarTokenTypes.hpp b/OMNotebook/NotebookParser/notebookgrammarTokenTypes.hpp index fab0c93b01e..1bc6123cf5e 100644 --- a/OMNotebook/NotebookParser/notebookgrammarTokenTypes.hpp +++ b/OMNotebook/NotebookParser/notebookgrammarTokenTypes.hpp @@ -10,182 +10,182 @@ #ifdef __cplusplus struct CUSTOM_API notebookgrammarTokenTypes { #endif - enum { - EOF_ = 1, - MODULENAME = 4, - LIST = 5, - LIST_SMALL = 6, - NOTEBOOK = 7, - CELL = 8, - TEXTDATA = 9, - CELLGROUPDATA = 10, - RULE = 11, - RULE_SMALL = 12, - RULEDELAYED = 13, - GRAYLEVEL = 14, - RGBCOLOR = 15, - FILENAME = 16, - STYLEBOX = 17, - STYLEDATA = 18, - BOXDATA = 19, - BUTTONBOX = 20, - FORMBOX = 21, - ROWBOX = 22, - GRIDBOX = 23, - TAGBOX = 24, - COUNTERBOX = 25, - ADJUSTMENTBOX = 26, - SUPERSCRBOX = 27, - SUBSCRBOX = 28, - SUBSUPERSCRIPTBOX = 29, - UNDERSCRIPTBOX = 30, - OVERSCRIPTBOX = 31, - UNDEROVERSCRIPTBOX = 32, - FRACTIONBOX = 33, - SQRTBOX = 34, - RADICALBOX = 35, - INTERPRETATIONBOX = 36, - ANNOTATION = 37, - EQUAL = 38, - DIAGRAM = 39, - ICON = 40, - POLYGON = 41, - ELLIPSE = 42, - LINE = 43, - DIREXTEDINFINITY = 44, - NOT_MATH_STARTMODELEDITOR = 45, - NOT_MATH_OLEDATE = 46, - FONTSLANT = 47, - FONTSIZE = 48, - FONTCOLOR = 49, - FONTWEIGHT = 50, - FONTFAMILY = 51, - FONTVARIATIONS = 52, - TEXTALIGNMENT = 53, - TEXTJUSTIFICATION = 54, - INITIALIZATIONCELL = 55, - FORMATTYPE_TOKEN = 56, - PAGEWIDTH = 57, - PAGEHEADERS = 58, - PAGEHEADERLINES = 59, - PAGEFOOTERS = 60, - PAGEFOOTERLINES = 61, - PAGEBREAKBELOW = 62, - PAGEBREAKWITHIN = 63, - BOXMARGINS = 64, - BOXBASELINESHIFT = 65, - LINESPACING = 66, - HYPHENATION = 67, - ACTIVE_TOKEN = 68, - VISIBLE_TOKEN = 69, - EVALUATABLE = 70, - BUTTONFUNCTION = 71, - BUTTONDATA = 72, - BUTTONEVALUATOR = 73, - BUTTONSTYLE = 74, - CHARACHTERENCODING = 75, - SHOWSTRINGCHARACTERS = 76, - SCREENRECTANGLE = 77, - AUTOGENERATEDPACKAGE = 78, - AUTOITALICWORDS = 79, - INPUTAUTOREPLACEMENTS = 80, - SCRIPTMINSIZE = 81, - STYLEMEMULISTING = 82, - COUNTERINCREMENTS = 83, - COUNTERASSIGNMENTS = 84, - PRIVATEEVALOPTIONS = 85, - GROUPPAGEBREAKWITHIN = 86, - DEFAULTFORMATTYPE = 87, - NUMBERMARKS = 88, - LINEBREAKADJUSTMENTS = 89, - VISIOLINEFORMAT = 90, - VISIOFILLFORMAT = 91, - EXTENT = 92, - NAMEPOSITION = 93, - CELLTAGS = 94, - CELLFRAME = 95, - CELLFRAMECOLOR = 96, - CELLFRAMELABELS = 97, - CELLFRAMEMARGINS = 98, - CELLFRAMELABELMARGINS = 99, - CELLLABRLMARGINS = 100, - CELLLABELPOSITIONING = 101, - CELLMARGINS = 102, - CELLDINGBAT = 103, - CELLHORIZONTALSCROLL = 104, - CELLOPEN = 105, - CELLGENERATED = 106, - SHOWCELLBRACKET = 107, - SHOWCELLLABEL = 108, - CELLBRACKETOPT = 109, - EDITABLE = 110, - BACKGROUNT = 111, - CELLGROUPINGRULES = 112, - WINDOWSIZE = 113, - WINDOWMARGINS = 114, - WINDOWFRAME = 115, - WINDOWELEMENTS = 116, - WINDOWTITLE = 117, - WINDOWTOOLBARS = 118, - WINDOWMOVEABLE = 119, - WINDOWFLOATING = 120, - WINDOWCLICKSELECT = 121, - STYLEDEFINITIONS = 122, - FRONTENDVERSION = 123, - SCREENSTYLEENV = 124, - PRINTINGSTYLEENV = 125, - PRINTINGOPTIONS = 126, - PRINTINGCOPIES = 127, - PRINTINGPAGERANGE = 128, - PRIVATEFONTOPTIONS = 129, - CELLGROUPOPEN = 130, - CELLGROUPCLOSED = 131, - VALUERIGHT = 132, - VALUELEFT = 133, - VALUECENTER = 134, - VALUESMALLER = 135, - INHERITED = 136, - PAPERWIDTH = 137, - WINDOWWIDTH = 138, - TRUE_ = 139, - FALSE_ = 140, - AUTOMATIC = 141, - TRADITIONALFORM = 142, - STANDARDFORM = 143, - INPUTFORM = 144, - OUTPUTFORM = 145, - DEFAULTINPUTFORMATTYPE = 146, - NULLSYM = 147, - NONESYM = 148, - ALLSYM = 149, - GRAPHICSDATA = 150, - IMAGESIZE = 151, - IMAGEMARGINS = 152, - IMAGEREGION = 153, - IMAGERANGECACHE = 154, - IMAGECACHE = 155, - NOT_MATH_MODELEDITOR = 156, - GENERATECELL = 157, - CELLAUTOOVRT = 158, - MAGNIFICATION = 159, - PARENTDIRECTORY = 160, - RBRACK = 161, - LBRACK = 162, - RCURLY = 163, - LCURLY = 164, - COMMA = 165, - THICK = 166, - COMMENTSTART = 167, - COMMENTEND = 168, - NUMBER = 169, - ID = 170, - EXP = 171, - DIGIT = 172, - QSTRING = 173, - WHITESPACE = 174, - COMMENT = 175, - NULL_TREE_LOOKAHEAD = 3 - }; + enum { + EOF_ = 1, + MODULENAME = 4, + LIST = 5, + LIST_SMALL = 6, + NOTEBOOK = 7, + CELL = 8, + TEXTDATA = 9, + CELLGROUPDATA = 10, + RULE = 11, + RULE_SMALL = 12, + RULEDELAYED = 13, + GRAYLEVEL = 14, + RGBCOLOR = 15, + FILENAME = 16, + STYLEBOX = 17, + STYLEDATA = 18, + BOXDATA = 19, + BUTTONBOX = 20, + FORMBOX = 21, + ROWBOX = 22, + GRIDBOX = 23, + TAGBOX = 24, + COUNTERBOX = 25, + ADJUSTMENTBOX = 26, + SUPERSCRBOX = 27, + SUBSCRBOX = 28, + SUBSUPERSCRIPTBOX = 29, + UNDERSCRIPTBOX = 30, + OVERSCRIPTBOX = 31, + UNDEROVERSCRIPTBOX = 32, + FRACTIONBOX = 33, + SQRTBOX = 34, + RADICALBOX = 35, + INTERPRETATIONBOX = 36, + ANNOTATION = 37, + EQUAL = 38, + DIAGRAM = 39, + ICON = 40, + POLYGON = 41, + ELLIPSE = 42, + LINE = 43, + DIREXTEDINFINITY = 44, + NOT_MATH_STARTMODELEDITOR = 45, + NOT_MATH_OLEDATE = 46, + FONTSLANT = 47, + FONTSIZE = 48, + FONTCOLOR = 49, + FONTWEIGHT = 50, + FONTFAMILY = 51, + FONTVARIATIONS = 52, + TEXTALIGNMENT = 53, + TEXTJUSTIFICATION = 54, + INITIALIZATIONCELL = 55, + FORMATTYPE_TOKEN = 56, + PAGEWIDTH = 57, + PAGEHEADERS = 58, + PAGEHEADERLINES = 59, + PAGEFOOTERS = 60, + PAGEFOOTERLINES = 61, + PAGEBREAKBELOW = 62, + PAGEBREAKWITHIN = 63, + BOXMARGINS = 64, + BOXBASELINESHIFT = 65, + LINESPACING = 66, + HYPHENATION = 67, + ACTIVE_TOKEN = 68, + VISIBLE_TOKEN = 69, + EVALUATABLE = 70, + BUTTONFUNCTION = 71, + BUTTONDATA = 72, + BUTTONEVALUATOR = 73, + BUTTONSTYLE = 74, + CHARACHTERENCODING = 75, + SHOWSTRINGCHARACTERS = 76, + SCREENRECTANGLE = 77, + AUTOGENERATEDPACKAGE = 78, + AUTOITALICWORDS = 79, + INPUTAUTOREPLACEMENTS = 80, + SCRIPTMINSIZE = 81, + STYLEMEMULISTING = 82, + COUNTERINCREMENTS = 83, + COUNTERASSIGNMENTS = 84, + PRIVATEEVALOPTIONS = 85, + GROUPPAGEBREAKWITHIN = 86, + DEFAULTFORMATTYPE = 87, + NUMBERMARKS = 88, + LINEBREAKADJUSTMENTS = 89, + VISIOLINEFORMAT = 90, + VISIOFILLFORMAT = 91, + EXTENT = 92, + NAMEPOSITION = 93, + CELLTAGS = 94, + CELLFRAME = 95, + CELLFRAMECOLOR = 96, + CELLFRAMELABELS = 97, + CELLFRAMEMARGINS = 98, + CELLFRAMELABELMARGINS = 99, + CELLLABRLMARGINS = 100, + CELLLABELPOSITIONING = 101, + CELLMARGINS = 102, + CELLDINGBAT = 103, + CELLHORIZONTALSCROLL = 104, + CELLOPEN = 105, + CELLGENERATED = 106, + SHOWCELLBRACKET = 107, + SHOWCELLLABEL = 108, + CELLBRACKETOPT = 109, + EDITABLE = 110, + BACKGROUNT = 111, + CELLGROUPINGRULES = 112, + WINDOWSIZE = 113, + WINDOWMARGINS = 114, + WINDOWFRAME = 115, + WINDOWELEMENTS = 116, + WINDOWTITLE = 117, + WINDOWTOOLBARS = 118, + WINDOWMOVEABLE = 119, + WINDOWFLOATING = 120, + WINDOWCLICKSELECT = 121, + STYLEDEFINITIONS = 122, + FRONTENDVERSION = 123, + SCREENSTYLEENV = 124, + PRINTINGSTYLEENV = 125, + PRINTINGOPTIONS = 126, + PRINTINGCOPIES = 127, + PRINTINGPAGERANGE = 128, + PRIVATEFONTOPTIONS = 129, + CELLGROUPOPEN = 130, + CELLGROUPCLOSED = 131, + VALUERIGHT = 132, + VALUELEFT = 133, + VALUECENTER = 134, + VALUESMALLER = 135, + INHERITED = 136, + PAPERWIDTH = 137, + WINDOWWIDTH = 138, + TRUE_ = 139, + FALSE_ = 140, + AUTOMATIC = 141, + TRADITIONALFORM = 142, + STANDARDFORM = 143, + INPUTFORM = 144, + OUTPUTFORM = 145, + DEFAULTINPUTFORMATTYPE = 146, + NULLSYM = 147, + NONESYM = 148, + ALLSYM = 149, + GRAPHICSDATA = 150, + IMAGESIZE = 151, + IMAGEMARGINS = 152, + IMAGEREGION = 153, + IMAGERANGECACHE = 154, + IMAGECACHE = 155, + NOT_MATH_MODELEDITOR = 156, + GENERATECELL = 157, + CELLAUTOOVRT = 158, + MAGNIFICATION = 159, + PARENTDIRECTORY = 160, + RBRACK = 161, + LBRACK = 162, + RCURLY = 163, + LCURLY = 164, + COMMA = 165, + THICK = 166, + COMMENTSTART = 167, + COMMENTEND = 168, + NUMBER = 169, + ID = 170, + EXP = 171, + DIGIT = 172, + QSTRING = 173, + WHITESPACE = 174, + COMMENT = 175, + NULL_TREE_LOOKAHEAD = 3 + }; #ifdef __cplusplus }; #endif diff --git a/OMNotebook/OMNotebookQT4/application.h b/OMNotebook/OMNotebookQT4/application.h index 16c04af4f9c..17d7f9bdc3c 100644 --- a/OMNotebook/OMNotebookQT4/application.h +++ b/OMNotebook/OMNotebookQT4/application.h @@ -63,9 +63,9 @@ namespace IAEX virtual void clearPasteboard() = 0; virtual vector pasteboard() = 0; virtual void open(const QString filename, int readmode = READMODE_NORMAL) = 0; - virtual void removeTempFiles(QString filename) = 0; // Added 2006-01-16 AF - virtual vector documentViewList() = 0; // Added 2006-01-27 AF - virtual void removeDocumentView(DocumentView *view) = 0; // Added 2006-01-27 AF + virtual void removeTempFiles(QString filename) = 0; // Added 2006-01-16 AF + virtual vector documentViewList() = 0; // Added 2006-01-27 AF + virtual void removeDocumentView(DocumentView *view) = 0; // Added 2006-01-27 AF }; }; diff --git a/OMNotebook/OMNotebookQT4/cell.cpp b/OMNotebook/OMNotebookQT4/cell.cpp index f0ff88ae736..6fa515f4dc2 100644 --- a/OMNotebook/OMNotebookQT4/cell.cpp +++ b/OMNotebook/OMNotebookQT4/cell.cpp @@ -53,571 +53,571 @@ using namespace std; namespace IAEX { - /*! - * \class Cell - * \author Ingemar Axelsson and Anders Ferström - * - * \brief Cellinterface contains all functionality required to be a cell. - * - * It implements the cells core functionality. Objects of this - * class should never be created. Instead tailored objects from - * subclasses such as TextCell, InputCell, CellGroup or ImageCell - * should be used. - * - * To extend the Qt Notebook application with new type of cells - * subclass this class. Then subclass or reimplement a CellFactory - * so it creates the new type of cell. Examples of adding new cell - * look at InputCell and ImageCell. - * - * Cells contains of two parts, a mainwidget containing the cells - * data, and the treewidget containing the treeview at the right side - * of the cell. - * - * - * \todo Implement a widgetstack for the treeview. This to make it - * possible to implement other treeview structures. (Ingemar Axelsson) - */ - - - /*! - * \author Ingemar Axelsson - * - * \brief The class constructor - */ - Cell::Cell(QWidget *parent) - : QWidget(parent), - selected_(false), - treeviewVisible_(true), - viewexpression_(false), - backgroundColor_(QColor(255,255,255)), - parent_(0), - next_(0), - last_(0), - previous_(0), - child_(0), - references_(0) - { - setMouseTracking(true); - setEnabled(true); - - mainlayout_ = new QGridLayout(this); - mainlayout_->setMargin(0); - mainlayout_->setSpacing(0); - - setLayout( mainlayout_ );//AF - setLabel(new QLabel(this)); - - setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum)); - // PORT >> setBackgroundMode(Qt::PaletteBase); - setBackgroundRole( QPalette::Base ); - setTreeWidget(new TreeView(this)); - - QPalette palette; - palette.setColor(backgroundRole(), backgroundColor()); - setPalette(palette); - } - - Cell::Cell(Cell &c) : QWidget() - { - setMouseTracking(true); - - mainlayout_ = new QGridLayout(this); - mainlayout_->setMargin(0); - mainlayout_->setSpacing(0); - - setLabel(new QLabel(this)); - - setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum)); - // PORT >> setBackgroundMode(Qt::PaletteBase); - setBackgroundRole( QPalette::Base ); - setTreeWidget(new TreeView(this)); - setStyle( *c.style() ); // Added 2005-10-27 AF - - - QPalette palette; - palette.setColor(c.backgroundRole(), c.backgroundColor()); - setPalette(palette); - } - - /*! - * \author Ingemar Axelsson - * - * \brief The class destructor - */ - Cell::~Cell() - { - //Delete if there are no references to this cell. - if(references_ <= 0) - { - setMouseTracking(false); - - delete treeView_; - delete mainWidget_; - delete label_; - } - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Set cell style - * - * \param stylename The style name of the style that is to be applyed to the cell - */ - void Cell::setStyle(const QString &stylename) - { - - Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); - CellStyle style = sheet->getStyle( stylename ); - - if( style.name() != "null" ) - setStyle( style ); - else - { - cout << "Can't set style, style name: " << stylename.toStdString() << " is not valid" << endl; - } - } - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * - * \brief Set the current cell style. - * - * \param style The cell style that is to be applyed to the cell - */ - void Cell::setStyle(CellStyle style) - { - - style_ = style; - applyRulesToStyle(); - } - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * - * \brief Get the current cell style. - * - * \return current cell style - */ - CellStyle *Cell::style() - { - return &style_; - } - - /*! - * \author Anders Fernström - * \date 2006-01-16 - * - * \brief Set cells tag name - */ - void Cell::setCellTag(QString tagname) - { - celltag_ = tagname; - } - - /*! - * \author Anders Fernström - * \date 2006-01-16 - * - * \brief Get the cell tag name - * - * \return cell tag name - */ - QString Cell::cellTag() - { - return celltag_; - } - - /*! - * \author Anders Fernström - * \date 2005-11-02 - * - * \brief Function for telling if the function viewExpression is - * activated or not. - * - * \return boolean, that tells if the cell is set to view expression - */ - const bool Cell::isViewExpression() const - { - return viewexpression_; - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2006-02-09 (update) - * - * \brief Adds a rule to the cell - * - * - * 2006-02-03 AF, check and see if rule already existes, if it dose - * only replace the value - * 2006-02-09 AF, ignore some types of rules - * - * \param r The rule that will be added - * - * - * \todo Implement functionality for 'InitializationCell': - * inputcells should be evaled from the start if the value is true. - * (Anders Fernström) - */ - void Cell::addRule(Rule *r) - { - // TODO: DEBUG code: Remove when doing release, - // just a check to find new rules - QRegExp expression( "InitializationCell|CellTags|FontSlant|TextAlignment|TextJustification|FontSize|FontWeight|FontFamily|PageWidth|CellMargins|CellDingbat|ImageSize|ImageMargins|ImageRegion|OMNotebook_Margin|OMNotebook_Padding|OMNotebook_Border" ); - if( 0 > r->attribute().indexOf( expression )) - { - cout << "[NEW] Rule <" << r->attribute().toStdString() << "> <" << r->value().toStdString() << ">" << endl; - } - else - { - if( r->attribute() == "FontSlant" ) - { - QRegExp fontslant( "Italic" ); - if( 0 > r->value().indexOf( fontslant )) - cout << "[NEW] Rule Value , VALUE: " << r->value().toStdString() << endl; - } - else if( r->attribute() == "TextAlignment" ) - { - QRegExp textalignment( "Right|Left|Center" ); - if( 0 > r->value().indexOf( textalignment )) - cout << "[NEW] Rule Value , VALUE: " << r->value().toStdString() << endl; - } - else if( r->attribute() == "TextJustification" ) - { - QRegExp textjustification( "1|0" ); - if( 0 > r->value().indexOf( textjustification )) - cout << "[NEW] Rule Value , VALUE: " << r->value().toStdString() << endl; - } - else if( r->attribute() == "FontWeight" ) - { - QRegExp fontweight( "Bold|Plain" ); - if( 0 > r->value().indexOf( fontweight )) - cout << "[NEW] Rule Value , VALUE: " << r->value().toStdString() << endl; - } - } - - - - - - // *** THE REAL FUNCTION *** - - - // 2006-02-09 AF, ignore some rules. This rules are not added - // to the cell - QRegExp ignoreRules( "PageWidth|CellMargins|CellDingbat|ImageSize|ImageMargins|ImageRegion" ); - - if( 0 > r->attribute().indexOf( ignoreRules ) ) - { - // check if rule already existes - bool found = false; - rules_t::iterator iter = rules_.begin(); - while( iter != rules_.end() ) - { - if( 0 == (*iter)->attribute().indexOf( r->attribute(), 0, Qt::CaseInsensitive ) ) - { - found = true; - (*iter)->setValue( r->value() ); - break; - } - ++iter; - } - - if( !found ) - rules_.push_back(r); - } - } - - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * - * \brief Apply any rules to the current cellstyle - * - * \todo Implement functionality for 'TextJustification'. - */ - void Cell::applyRulesToStyle() - { - rules_t::iterator current = rules_.begin(); - while( current != rules_.end() ) - { - if( (*current)->attribute() == "FontSlant" ) - { - if( (*current)->value() == "Italic" ) - style_.textCharFormat()->setFontItalic( true ); - } - else if( (*current)->attribute() == "TextAlignment" ) - { - if( (*current)->value() == "Left" ) - style_.setAlignment( Qt::AlignLeft ); - else if( (*current)->value() == "Right" ) - style_.setAlignment( Qt::AlignRight ); - else if( (*current)->value() == "Center" ) - style_.setAlignment( Qt::AlignHCenter ); - else if( (*current)->value() == "Justify" ) - style_.setAlignment( Qt::AlignJustify ); - } - else if( (*current)->attribute() == "TextJustification" ) - { - //values: 1,0 - } - else if( (*current)->attribute() == "FontSize" ) - { - bool ok; - int size = (*current)->value().toInt(&ok); - - if(ok) - { - if( size > 0 ) - style_.textCharFormat()->setFontPointSize( size ); - } - } - else if( (*current)->attribute() == "FontWeight" ) - { - - if( (*current)->value() == "Bold" ) - style_.textCharFormat()->setFontWeight( QFont::Bold ); - if( (*current)->value() == "Plain" ) - style_.textCharFormat()->setFontWeight( QFont::Normal ); - } - else if( (*current)->attribute() == "FontFamily" ) - { - style_.textCharFormat()->setFontFamily( (*current)->value() ); - } - else if( (*current)->attribute() == "InitializationCell" ) - {} - else if( (*current)->attribute() == "CellTags" ) - { - celltag_ = (*current)->value(); - } - else if( (*current)->attribute() == "OMNotebook_Margin" ) - { - bool ok; - int value = (*current)->value().toInt(&ok); - - if(ok) - { - if( value > 0 ) - style_.textFrameFormat()->setMargin( value ); - } - } - else if( (*current)->attribute() == "OMNotebook_Padding" ) - { - bool ok; - int value = (*current)->value().toInt(&ok); - - if(ok) - { - if( value > 0 ) - style_.textFrameFormat()->setPadding( value ); - } - } - else if( (*current)->attribute() == "OMNotebook_Border" ) - { - bool ok; - int value = (*current)->value().toInt(&ok); - - if(ok) - { - if( value > 0 ) - style_.textFrameFormat()->setBorder( value ); - } - } - - ++current; - } - } - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * - * \brief return the cells text cursor. if the cell don't have - * a cursor that have been created by the default constructor and - * is a null cursor. - * - * \return The cells text cursor - */ - QTextCursor Cell::textCursor() - { - QTextCursor cursor; - return cursor; - } - - void Cell::wheelEvent(QWheelEvent * event) - { - // ignore event and send it up in the event hierarchy - event->ignore(); - - if( parentCell() ) - { - parentCell()->wheelEvent( event ); - } - else - { - // if no parent cell -> top cell - parent()->event( event ); - } - } - - /*! - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief Update the cell layout with a chapter counter - */ - void Cell::addChapterCounter(QWidget *counter) - { - mainlayout_->removeWidget( mainWidget_ ); - mainlayout_->removeWidget( treeView_ ); - mainlayout_->addWidget( counter, 1, 1 ); - mainlayout_->addWidget( mainWidget_, 1, 2 ); - mainlayout_->addWidget( treeView_, 1, 3, Qt::AlignTop ); - } - - - - - - - - - - - // *************************************************************** - - - - - - - /*! \brief Set the cells mainwidget. - * - * \todo Delete old widget. (Ingemar Axelsson) - * - * \param newWidget A pointer to the cells new mainwidget. - */ - void Cell::setMainWidget(QWidget *newWidget) - { - if(newWidget != 0) - { - mainWidget_ = newWidget; - mainlayout_->addWidget(newWidget,1,1); - - mainWidget_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum)); - - QPalette palette; - palette.setColor(mainWidget_->backgroundRole(), backgroundColor()); - mainWidget_->setPalette(palette); - } - else - mainWidget_= 0; - } - - /*! - * \author Ingemar Axelsson - * \return A pointer to the mainwidget for the cell. - */ - QWidget *Cell::mainWidget() - { - if(!mainWidget_) - throw logic_error("Cell::mainWidget(): No mainWidget set."); - - return mainWidget_; - } - - - void Cell::setLabel(QLabel *label) - { - label_ = label; - mainlayout_->addWidget(label,1,0); - - QPalette palette; - palette.setColor(label_->backgroundRole(), backgroundColor()); - label_->setPalette(palette); - - label_->hide(); - } - - QLabel *Cell::label() - { - return label_; - } - - /*! - * \brief Add a treeview widget to the cell. - */ - void Cell::setTreeWidget(TreeView *newTreeWidget) - { - treeView_ = newTreeWidget; - treeView_->setFocusPolicy(Qt::NoFocus); - mainlayout_->addWidget(newTreeWidget,1,2, Qt::AlignTop); - treeView_->setBackgroundColor(backgroundColor()); - treeView_->show(); - - connect(this, SIGNAL(selected(const bool)), - treeView_, SLOT(setSelected(const bool))); - } - - TreeView *Cell::treeView() - { - if(!treeView_) - throw logic_error("Cell::treeView(): No treeView set."); - - return treeView_; - } - - /*! - * \todo The treewidget should not only be hidden, the mainwidget - * should be resized.(Ingemar Axelsson) - * - *\todo test if repaint is needed here. (Ingemar Axelsson) - */ - void Cell::hideTreeView(const bool hidden) - { - if(hidden) - { - treeView_->hide(); - } - else - { - treeView_->show(); - } - - treeviewVisible_ = !hidden; - repaint(); - } - - /*! \return TRUE if treeview is hidden. Otherwise FALSE. - */ - const bool Cell::isTreeViewVisible() const - { - return treeviewVisible_; - } - - /*! \brief Sets the height of the cell. - * \author Ingemar Axelsson - * - * \param height New height for cell. - */ - void Cell::setHeight(const int height) - { - int h = height; - - //! \bug Implement Cell::setHeight() in a correct way. Does not work for - //! widgets larger than 32767. (qt limitation) - /*if(height > 32000) - { - h = 32000; - }*/ - - if(!treeView_) - throw logic_error("SetHeight(const int height): TreeView is not set."); + /*! + * \class Cell + * \author Ingemar Axelsson and Anders Ferström + * + * \brief Cellinterface contains all functionality required to be a cell. + * + * It implements the cells core functionality. Objects of this + * class should never be created. Instead tailored objects from + * subclasses such as TextCell, InputCell, CellGroup or ImageCell + * should be used. + * + * To extend the Qt Notebook application with new type of cells + * subclass this class. Then subclass or reimplement a CellFactory + * so it creates the new type of cell. Examples of adding new cell + * look at InputCell and ImageCell. + * + * Cells contains of two parts, a mainwidget containing the cells + * data, and the treewidget containing the treeview at the right side + * of the cell. + * + * + * \todo Implement a widgetstack for the treeview. This to make it + * possible to implement other treeview structures. (Ingemar Axelsson) + */ + + + /*! + * \author Ingemar Axelsson + * + * \brief The class constructor + */ + Cell::Cell(QWidget *parent) + : QWidget(parent), + selected_(false), + treeviewVisible_(true), + viewexpression_(false), + backgroundColor_(QColor(255,255,255)), + parent_(0), + next_(0), + last_(0), + previous_(0), + child_(0), + references_(0) + { + setMouseTracking(true); + setEnabled(true); + + mainlayout_ = new QGridLayout(this); + mainlayout_->setMargin(0); + mainlayout_->setSpacing(0); + + setLayout( mainlayout_ );//AF + setLabel(new QLabel(this)); + + setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum)); + // PORT >> setBackgroundMode(Qt::PaletteBase); + setBackgroundRole( QPalette::Base ); + setTreeWidget(new TreeView(this)); + + QPalette palette; + palette.setColor(backgroundRole(), backgroundColor()); + setPalette(palette); + } + + Cell::Cell(Cell &c) : QWidget() + { + setMouseTracking(true); + + mainlayout_ = new QGridLayout(this); + mainlayout_->setMargin(0); + mainlayout_->setSpacing(0); + + setLabel(new QLabel(this)); + + setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum)); + // PORT >> setBackgroundMode(Qt::PaletteBase); + setBackgroundRole( QPalette::Base ); + setTreeWidget(new TreeView(this)); + setStyle( *c.style() ); // Added 2005-10-27 AF + + + QPalette palette; + palette.setColor(c.backgroundRole(), c.backgroundColor()); + setPalette(palette); + } + + /*! + * \author Ingemar Axelsson + * + * \brief The class destructor + */ + Cell::~Cell() + { + //Delete if there are no references to this cell. + if(references_ <= 0) + { + setMouseTracking(false); + + delete treeView_; + delete mainWidget_; + delete label_; + } + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Set cell style + * + * \param stylename The style name of the style that is to be applyed to the cell + */ + void Cell::setStyle(const QString &stylename) + { + + Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); + CellStyle style = sheet->getStyle( stylename ); + + if( style.name() != "null" ) + setStyle( style ); + else + { + cout << "Can't set style, style name: " << stylename.toStdString() << " is not valid" << endl; + } + } + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * + * \brief Set the current cell style. + * + * \param style The cell style that is to be applyed to the cell + */ + void Cell::setStyle(CellStyle style) + { + + style_ = style; + applyRulesToStyle(); + } + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * + * \brief Get the current cell style. + * + * \return current cell style + */ + CellStyle *Cell::style() + { + return &style_; + } + + /*! + * \author Anders Fernström + * \date 2006-01-16 + * + * \brief Set cells tag name + */ + void Cell::setCellTag(QString tagname) + { + celltag_ = tagname; + } + + /*! + * \author Anders Fernström + * \date 2006-01-16 + * + * \brief Get the cell tag name + * + * \return cell tag name + */ + QString Cell::cellTag() + { + return celltag_; + } + + /*! + * \author Anders Fernström + * \date 2005-11-02 + * + * \brief Function for telling if the function viewExpression is + * activated or not. + * + * \return boolean, that tells if the cell is set to view expression + */ + const bool Cell::isViewExpression() const + { + return viewexpression_; + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2006-02-09 (update) + * + * \brief Adds a rule to the cell + * + * + * 2006-02-03 AF, check and see if rule already existes, if it dose + * only replace the value + * 2006-02-09 AF, ignore some types of rules + * + * \param r The rule that will be added + * + * + * \todo Implement functionality for 'InitializationCell': + * inputcells should be evaled from the start if the value is true. + * (Anders Fernström) + */ + void Cell::addRule(Rule *r) + { + // TODO: DEBUG code: Remove when doing release, + // just a check to find new rules + QRegExp expression( "InitializationCell|CellTags|FontSlant|TextAlignment|TextJustification|FontSize|FontWeight|FontFamily|PageWidth|CellMargins|CellDingbat|ImageSize|ImageMargins|ImageRegion|OMNotebook_Margin|OMNotebook_Padding|OMNotebook_Border" ); + if( 0 > r->attribute().indexOf( expression )) + { + cout << "[NEW] Rule <" << r->attribute().toStdString() << "> <" << r->value().toStdString() << ">" << endl; + } + else + { + if( r->attribute() == "FontSlant" ) + { + QRegExp fontslant( "Italic" ); + if( 0 > r->value().indexOf( fontslant )) + cout << "[NEW] Rule Value , VALUE: " << r->value().toStdString() << endl; + } + else if( r->attribute() == "TextAlignment" ) + { + QRegExp textalignment( "Right|Left|Center" ); + if( 0 > r->value().indexOf( textalignment )) + cout << "[NEW] Rule Value , VALUE: " << r->value().toStdString() << endl; + } + else if( r->attribute() == "TextJustification" ) + { + QRegExp textjustification( "1|0" ); + if( 0 > r->value().indexOf( textjustification )) + cout << "[NEW] Rule Value , VALUE: " << r->value().toStdString() << endl; + } + else if( r->attribute() == "FontWeight" ) + { + QRegExp fontweight( "Bold|Plain" ); + if( 0 > r->value().indexOf( fontweight )) + cout << "[NEW] Rule Value , VALUE: " << r->value().toStdString() << endl; + } + } + + + + + + // *** THE REAL FUNCTION *** + + + // 2006-02-09 AF, ignore some rules. This rules are not added + // to the cell + QRegExp ignoreRules( "PageWidth|CellMargins|CellDingbat|ImageSize|ImageMargins|ImageRegion" ); + + if( 0 > r->attribute().indexOf( ignoreRules ) ) + { + // check if rule already existes + bool found = false; + rules_t::iterator iter = rules_.begin(); + while( iter != rules_.end() ) + { + if( 0 == (*iter)->attribute().indexOf( r->attribute(), 0, Qt::CaseInsensitive ) ) + { + found = true; + (*iter)->setValue( r->value() ); + break; + } + ++iter; + } + + if( !found ) + rules_.push_back(r); + } + } + + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * + * \brief Apply any rules to the current cellstyle + * + * \todo Implement functionality for 'TextJustification'. + */ + void Cell::applyRulesToStyle() + { + rules_t::iterator current = rules_.begin(); + while( current != rules_.end() ) + { + if( (*current)->attribute() == "FontSlant" ) + { + if( (*current)->value() == "Italic" ) + style_.textCharFormat()->setFontItalic( true ); + } + else if( (*current)->attribute() == "TextAlignment" ) + { + if( (*current)->value() == "Left" ) + style_.setAlignment( Qt::AlignLeft ); + else if( (*current)->value() == "Right" ) + style_.setAlignment( Qt::AlignRight ); + else if( (*current)->value() == "Center" ) + style_.setAlignment( Qt::AlignHCenter ); + else if( (*current)->value() == "Justify" ) + style_.setAlignment( Qt::AlignJustify ); + } + else if( (*current)->attribute() == "TextJustification" ) + { + //values: 1,0 + } + else if( (*current)->attribute() == "FontSize" ) + { + bool ok; + int size = (*current)->value().toInt(&ok); + + if(ok) + { + if( size > 0 ) + style_.textCharFormat()->setFontPointSize( size ); + } + } + else if( (*current)->attribute() == "FontWeight" ) + { + + if( (*current)->value() == "Bold" ) + style_.textCharFormat()->setFontWeight( QFont::Bold ); + if( (*current)->value() == "Plain" ) + style_.textCharFormat()->setFontWeight( QFont::Normal ); + } + else if( (*current)->attribute() == "FontFamily" ) + { + style_.textCharFormat()->setFontFamily( (*current)->value() ); + } + else if( (*current)->attribute() == "InitializationCell" ) + {} + else if( (*current)->attribute() == "CellTags" ) + { + celltag_ = (*current)->value(); + } + else if( (*current)->attribute() == "OMNotebook_Margin" ) + { + bool ok; + int value = (*current)->value().toInt(&ok); + + if(ok) + { + if( value > 0 ) + style_.textFrameFormat()->setMargin( value ); + } + } + else if( (*current)->attribute() == "OMNotebook_Padding" ) + { + bool ok; + int value = (*current)->value().toInt(&ok); + + if(ok) + { + if( value > 0 ) + style_.textFrameFormat()->setPadding( value ); + } + } + else if( (*current)->attribute() == "OMNotebook_Border" ) + { + bool ok; + int value = (*current)->value().toInt(&ok); + + if(ok) + { + if( value > 0 ) + style_.textFrameFormat()->setBorder( value ); + } + } + + ++current; + } + } + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * + * \brief return the cells text cursor. if the cell don't have + * a cursor that have been created by the default constructor and + * is a null cursor. + * + * \return The cells text cursor + */ + QTextCursor Cell::textCursor() + { + QTextCursor cursor; + return cursor; + } + + void Cell::wheelEvent(QWheelEvent * event) + { + // ignore event and send it up in the event hierarchy + event->ignore(); + + if( parentCell() ) + { + parentCell()->wheelEvent( event ); + } + else + { + // if no parent cell -> top cell + parent()->event( event ); + } + } + + /*! + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief Update the cell layout with a chapter counter + */ + void Cell::addChapterCounter(QWidget *counter) + { + mainlayout_->removeWidget( mainWidget_ ); + mainlayout_->removeWidget( treeView_ ); + mainlayout_->addWidget( counter, 1, 1 ); + mainlayout_->addWidget( mainWidget_, 1, 2 ); + mainlayout_->addWidget( treeView_, 1, 3, Qt::AlignTop ); + } + + + + + + + + + + + // *************************************************************** + + + + + + + /*! \brief Set the cells mainwidget. + * + * \todo Delete old widget. (Ingemar Axelsson) + * + * \param newWidget A pointer to the cells new mainwidget. + */ + void Cell::setMainWidget(QWidget *newWidget) + { + if(newWidget != 0) + { + mainWidget_ = newWidget; + mainlayout_->addWidget(newWidget,1,1); + + mainWidget_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum)); + + QPalette palette; + palette.setColor(mainWidget_->backgroundRole(), backgroundColor()); + mainWidget_->setPalette(palette); + } + else + mainWidget_= 0; + } + + /*! + * \author Ingemar Axelsson + * \return A pointer to the mainwidget for the cell. + */ + QWidget *Cell::mainWidget() + { + if(!mainWidget_) + throw logic_error("Cell::mainWidget(): No mainWidget set."); + + return mainWidget_; + } + + + void Cell::setLabel(QLabel *label) + { + label_ = label; + mainlayout_->addWidget(label,1,0); + + QPalette palette; + palette.setColor(label_->backgroundRole(), backgroundColor()); + label_->setPalette(palette); + + label_->hide(); + } + + QLabel *Cell::label() + { + return label_; + } + + /*! + * \brief Add a treeview widget to the cell. + */ + void Cell::setTreeWidget(TreeView *newTreeWidget) + { + treeView_ = newTreeWidget; + treeView_->setFocusPolicy(Qt::NoFocus); + mainlayout_->addWidget(newTreeWidget,1,2, Qt::AlignTop); + treeView_->setBackgroundColor(backgroundColor()); + treeView_->show(); + + connect(this, SIGNAL(selected(const bool)), + treeView_, SLOT(setSelected(const bool))); + } + + TreeView *Cell::treeView() + { + if(!treeView_) + throw logic_error("Cell::treeView(): No treeView set."); + + return treeView_; + } + + /*! + * \todo The treewidget should not only be hidden, the mainwidget + * should be resized.(Ingemar Axelsson) + * + *\todo test if repaint is needed here. (Ingemar Axelsson) + */ + void Cell::hideTreeView(const bool hidden) + { + if(hidden) + { + treeView_->hide(); + } + else + { + treeView_->show(); + } + + treeviewVisible_ = !hidden; + repaint(); + } + + /*! \return TRUE if treeview is hidden. Otherwise FALSE. + */ + const bool Cell::isTreeViewVisible() const + { + return treeviewVisible_; + } + + /*! \brief Sets the height of the cell. + * \author Ingemar Axelsson + * + * \param height New height for cell. + */ + void Cell::setHeight(const int height) + { + int h = height; + + //! \bug Implement Cell::setHeight() in a correct way. Does not work for + //! widgets larger than 32767. (qt limitation) + /*if(height > 32000) + { + h = 32000; + }*/ + + if(!treeView_) + throw logic_error("SetHeight(const int height): TreeView is not set."); #ifdef __APPLE_CC__ setMinimumHeight(h); @@ -628,288 +628,288 @@ namespace IAEX treeView_->setFixedHeight(h); emit heightChanged(); - } - - - /*! \brief Describes what will happen if a mousebutton is released - * when the mouse is over the treeview widget. - * \author Ingemar Axelsson - * - * \bug Should be done in the TreeView instead. Then a - * signal could be emitted. - */ - void Cell::mouseReleaseEvent(QMouseEvent *event) - { - // PORT >> if(treeView_->hasMouse()) - if(treeView_->testAttribute(Qt::WA_UnderMouse)) - { - this->setSelected(!isSelected()); - emit cellselected(this, event->modifiers()); - } - else - { - //Do nothing. - } - } - - /*! \brief - * Mouse move event is triggered when the mouse is moved. - * - * This method must be implemented when adding support for drag and - * drop. Also look at the QT manual for more information about drag - * and drop. - * - * \param event QMouseEvent sent from widgets parent. - * - * \todo Needs a cursor->moveBefore member. (Ingemar Axelsson) - */ - void Cell::mouseMoveEvent(QMouseEvent *event) - { - if(event->pos().x() < 0 || event->pos().x() > this->width()) - { - //Not inside widget. Do not care - } - else - { - if(event->pos().y() < 0) - { - //if(hasPrevious()) - // doc()->executeCommand(new CursorMoveAfterCommand(previous())) - // doc()->executeCommand(new CursorMoveAfterCommand(this)); - // else - // { - // if(parentCell()->hasParentCell()) //Check for errors - // doc()->executeCommand(new CursorMoveAfterCommand(parentCell()->previous())); - // else - // { - // //Do nothing! - // } - // } - } - - // else // if(event->pos().y() < height()) - // { - // doc()->executeCommand(new CursorMoveAfterCommand(this)); - // } - - // if((doc()->getCursor())->currentCell() != this) - // { - // doc()->executeCommand(new CursorMoveAfterCommand(this)); - // } - } - } - - void Cell::resizeEvent(QResizeEvent *event) - { - setHeight(height()); - QWidget::resizeEvent(event); - } - - /*! - * \return true if cell is selected, false otherwise. - */ - const bool Cell::isSelected() const - { - return selected_; - } - - /*! \brief Set the value for selectec_ to true if the cell is - * selected. - * \author Ingemar Axelsson - * - * This slot is used to change the state of the cell. - * - * \todo Tell the treeview that the cell has changed state. Should the - * cell be responsible to decide if it has been selected or should the - * treeview decide? Probably better if the cell decides. (Ingemar Axelsson) - * - * \param selected true if cell should be selected, false otherwise - */ - void Cell::setSelected(const bool sel) - { - selected_ = sel; - emit selected(selected_); - } - - /*! \brief Set the cells background color. - * \author Ingemar Axelsson - * - * Sets cells backgroundcolor. Also propagates the background color to - * the cells child widgets. - * - * \param color new color. - */ - void Cell::setBackgroundColor(const QColor color) - { - backgroundColor_ = color; - - QPalette palette; - palette.setColor(backgroundRole(), color); - setPalette(palette); - } - - /*!\brief get the current backgroundcolor. - * \author Ingemar Axelsson - * - * \return current background color. - */ - const QColor Cell::backgroundColor() const - { - return backgroundColor_; - } - - - Cell::rules_t Cell::rules() const - { - return rules_; - } - - /////VIRTUALS //////////////////////////////// - - - /*! \brief Implements visitor acceptability. - * - */ - void Cell::accept(Visitor &v) - { - v.visitCellNodeBefore(this); - - if(hasChilds()) - child()->accept(v); - - v.visitCellNodeAfter(this); - - //Move along. - if(hasNext()) - next()->accept(v); - } - - void Cell::addCellWidget(Cell *newCell) - { - parentCell()->addCellWidget(newCell); - } - - ////// DATASTRUCTURE IMPLEMENTATION /////////////////////////// - - void Cell::setNext(Cell *nxt) - { - next_ = nxt; - } - - Cell *Cell::next() - { - return next_; - } - - bool Cell::hasNext() - { - return next_ != 0; - } - - void Cell::setLast(Cell *last) - { - last_ = last; - } - - Cell *Cell::last() - { - return last_; - } - - bool Cell::hasLast() - { - return hasChilds(); - } - - void Cell::setPrevious(Cell *prev) - { - previous_ = prev; - } - - Cell *Cell::previous() - { - return previous_; - } - - bool Cell::hasPrevious() - { - return previous_ != 0; - } - - Cell *Cell::parentCell() - { - return parent_; - } - - void Cell::setParentCell(Cell *parent) - { - //setParent( parent ); - parent_ = parent; - } - - bool Cell::hasParentCell() - { - return parent_ != 0; - } - - void Cell::setChild(Cell *child) - { - child_ = child; - } - - Cell *Cell::child() - { - return child_; - } - - bool Cell::hasChilds() - { - return child_ != 0; - } - - void Cell::printCell(Cell *current) - { - cout << "This: " << current << endl - << "Parent: " << current->parentCell() << endl - << "Child: " << current->child() << endl - << "Last: " << current->last() << endl - << "Next: " << current->next() << endl - << "Prev: " << current->previous() << endl; - } - - void Cell::printSurrounding(Cell *current) - { - printCell(current); - - //Print surroundings - if(current->hasNext()) - { - printCell(current->next()); - } - - if(current->hasPrevious()) - { - printCell(current->previous()); - } - - if(current->hasParentCell()) - { - printCell(current->parentCell()); - } - - if(current->hasChilds()) - { - printCell(current->child()); - } - } - - // void Cell::retain(s) - // { - // references_ += 1; - // } - - // void Cell::release() - // { - // references_ -= 1; - // } + } + + + /*! \brief Describes what will happen if a mousebutton is released + * when the mouse is over the treeview widget. + * \author Ingemar Axelsson + * + * \bug Should be done in the TreeView instead. Then a + * signal could be emitted. + */ + void Cell::mouseReleaseEvent(QMouseEvent *event) + { + // PORT >> if(treeView_->hasMouse()) + if(treeView_->testAttribute(Qt::WA_UnderMouse)) + { + this->setSelected(!isSelected()); + emit cellselected(this, event->modifiers()); + } + else + { + //Do nothing. + } + } + + /*! \brief + * Mouse move event is triggered when the mouse is moved. + * + * This method must be implemented when adding support for drag and + * drop. Also look at the QT manual for more information about drag + * and drop. + * + * \param event QMouseEvent sent from widgets parent. + * + * \todo Needs a cursor->moveBefore member. (Ingemar Axelsson) + */ + void Cell::mouseMoveEvent(QMouseEvent *event) + { + if(event->pos().x() < 0 || event->pos().x() > this->width()) + { + //Not inside widget. Do not care + } + else + { + if(event->pos().y() < 0) + { + //if(hasPrevious()) + // doc()->executeCommand(new CursorMoveAfterCommand(previous())) + // doc()->executeCommand(new CursorMoveAfterCommand(this)); + // else + // { + // if(parentCell()->hasParentCell()) //Check for errors + // doc()->executeCommand(new CursorMoveAfterCommand(parentCell()->previous())); + // else + // { + // //Do nothing! + // } + // } + } + + // else // if(event->pos().y() < height()) + // { + // doc()->executeCommand(new CursorMoveAfterCommand(this)); + // } + + // if((doc()->getCursor())->currentCell() != this) + // { + // doc()->executeCommand(new CursorMoveAfterCommand(this)); + // } + } + } + + void Cell::resizeEvent(QResizeEvent *event) + { + setHeight(height()); + QWidget::resizeEvent(event); + } + + /*! + * \return true if cell is selected, false otherwise. + */ + const bool Cell::isSelected() const + { + return selected_; + } + + /*! \brief Set the value for selectec_ to true if the cell is + * selected. + * \author Ingemar Axelsson + * + * This slot is used to change the state of the cell. + * + * \todo Tell the treeview that the cell has changed state. Should the + * cell be responsible to decide if it has been selected or should the + * treeview decide? Probably better if the cell decides. (Ingemar Axelsson) + * + * \param selected true if cell should be selected, false otherwise + */ + void Cell::setSelected(const bool sel) + { + selected_ = sel; + emit selected(selected_); + } + + /*! \brief Set the cells background color. + * \author Ingemar Axelsson + * + * Sets cells backgroundcolor. Also propagates the background color to + * the cells child widgets. + * + * \param color new color. + */ + void Cell::setBackgroundColor(const QColor color) + { + backgroundColor_ = color; + + QPalette palette; + palette.setColor(backgroundRole(), color); + setPalette(palette); + } + + /*!\brief get the current backgroundcolor. + * \author Ingemar Axelsson + * + * \return current background color. + */ + const QColor Cell::backgroundColor() const + { + return backgroundColor_; + } + + + Cell::rules_t Cell::rules() const + { + return rules_; + } + + /////VIRTUALS //////////////////////////////// + + + /*! \brief Implements visitor acceptability. + * + */ + void Cell::accept(Visitor &v) + { + v.visitCellNodeBefore(this); + + if(hasChilds()) + child()->accept(v); + + v.visitCellNodeAfter(this); + + //Move along. + if(hasNext()) + next()->accept(v); + } + + void Cell::addCellWidget(Cell *newCell) + { + parentCell()->addCellWidget(newCell); + } + + ////// DATASTRUCTURE IMPLEMENTATION /////////////////////////// + + void Cell::setNext(Cell *nxt) + { + next_ = nxt; + } + + Cell *Cell::next() + { + return next_; + } + + bool Cell::hasNext() + { + return next_ != 0; + } + + void Cell::setLast(Cell *last) + { + last_ = last; + } + + Cell *Cell::last() + { + return last_; + } + + bool Cell::hasLast() + { + return hasChilds(); + } + + void Cell::setPrevious(Cell *prev) + { + previous_ = prev; + } + + Cell *Cell::previous() + { + return previous_; + } + + bool Cell::hasPrevious() + { + return previous_ != 0; + } + + Cell *Cell::parentCell() + { + return parent_; + } + + void Cell::setParentCell(Cell *parent) + { + //setParent( parent ); + parent_ = parent; + } + + bool Cell::hasParentCell() + { + return parent_ != 0; + } + + void Cell::setChild(Cell *child) + { + child_ = child; + } + + Cell *Cell::child() + { + return child_; + } + + bool Cell::hasChilds() + { + return child_ != 0; + } + + void Cell::printCell(Cell *current) + { + cout << "This: " << current << endl + << "Parent: " << current->parentCell() << endl + << "Child: " << current->child() << endl + << "Last: " << current->last() << endl + << "Next: " << current->next() << endl + << "Prev: " << current->previous() << endl; + } + + void Cell::printSurrounding(Cell *current) + { + printCell(current); + + //Print surroundings + if(current->hasNext()) + { + printCell(current->next()); + } + + if(current->hasPrevious()) + { + printCell(current->previous()); + } + + if(current->hasParentCell()) + { + printCell(current->parentCell()); + } + + if(current->hasChilds()) + { + printCell(current->child()); + } + } + + // void Cell::retain(s) + // { + // references_ += 1; + // } + + // void Cell::release() + // { + // references_ -= 1; + // } } diff --git a/OMNotebook/OMNotebookQT4/cell.h b/OMNotebook/OMNotebookQT4/cell.h index da041b68c36..cfa9c90357e 100644 --- a/OMNotebook/OMNotebookQT4/cell.h +++ b/OMNotebook/OMNotebookQT4/cell.h @@ -70,151 +70,151 @@ using namespace Qt; namespace IAEX { - class Cell : public QWidget - { - Q_OBJECT - - public: - typedef vector rules_t; - - Cell(QWidget *parent=0); // Changed 2005-10-27 AF - Cell(Cell &c); - virtual ~Cell(); - - //Datastructure interface. - void setNext(Cell *nxt); - Cell *next(); - bool hasNext(); - - void setLast(Cell *last); - Cell *last(); - bool hasLast(); - - void setPrevious(Cell *prev); - Cell *previous(); - bool hasPrevious(); - - Cell *parentCell(); - void setParentCell(Cell *parent); - bool hasParentCell(); - - void setChild(Cell *child); - Cell *child(); - bool hasChilds(); - - void printCell(Cell *current); - void printSurrounding(Cell *current); - - //TextCell interface. - virtual QString text() = 0; - virtual QString textHtml(){return QString::null;} // Added 2005-10-27 AF - virtual QTextCursor textCursor(); // Added 2005-10-27 AF - virtual QTextEdit* textEdit(){return 0;} // Added 2005-10-27 AF - virtual void viewExpression(const bool){}; - - //Cellgroup interface. - virtual void addChild(Cell *){} - virtual void removeChild(Cell *){} - virtual bool isClosed() const{ return false;} - virtual void setClosed(const bool closed, bool update = true){} // Changed 2006-08-24 - - virtual void addCellWidget(Cell *newCell); //Protected? - - //Rename to insertCellWidgets() instead. - virtual void addCellWidgets(){parentCell()->addCellWidgets();} - virtual void removeCellWidgets(){parentCell()->removeCellWidgets();} - - //Traversal methods - virtual void accept(Visitor &v); - - //Flags - const bool isSelected() const; - const bool isTreeViewVisible() const; - virtual bool isEditable() = 0; // Added 2005-10-27 AF - const bool isViewExpression() const; // Added 2005-11-02 AF - - //Properties - const QColor backgroundColor() const; - virtual CellStyle *style(); // Changed 2005-10-27 AF - QString cellTag(); // Added 2006-01-16 AF - virtual rules_t rules() const; - QWidget *mainWidget(); - TreeView *treeView(); - QLabel *label(); - - - - public slots: - virtual void addRule(Rule *r); - virtual void setText(QString text){} - virtual void setText(QString text, QTextCharFormat format){} // Added 2005-10-27 AF - virtual void setTextHtml(QString html){} // Added 2005-10-27 AF - virtual void setStyle(const QString &stylename); // Changed 2005-10-28 AF - virtual void setStyle(CellStyle style); // Changed 2005-10-27 AF - void setCellTag(QString tagname); // Added 2006-01-16 AF - virtual void setReadOnly(const bool){} - virtual void setFocus(const bool focus) = 0; - virtual void applyLinksToText(){} // Added 2005-11-09 AF - - virtual void setBackgroundColor(const QColor color); - virtual void setSelected(const bool selected); - virtual void setHeight(const int height); - void hideTreeView(const bool hidden); - - void wheelEvent(QWheelEvent * event); //tmp - - protected slots: - void setLabel(QLabel *label); - void setTreeWidget(TreeView *newTreeWidget); - void setMainWidget(QWidget *newWidget); - void addChapterCounter(QWidget *counter); // Added 2006-02-03 AF - - signals: - void clicked(Cell*); - void doubleClicked(int); - void changedWidth(const int); - void selected(const bool); - - // 2005-10-06 AF, bytt från Qt::ButtonState till - // Qt::KeyboardModifiers p.g.a. portning - void cellselected(Cell *, Qt::KeyboardModifiers); - - void heightChanged(); - void openLink(const QUrl *link); - void cellOpened(Cell *, const bool); - - protected: - //Events - void resizeEvent(QResizeEvent *event); - void mouseReleaseEvent(QMouseEvent *event); - void mouseMoveEvent(QMouseEvent *event); - - void applyRulesToStyle(); // Added 2005-10-27 AF - - // variables - bool viewexpression_; // Added 2005-11-02 AF - CellStyle style_; // Changed 2005-10-27 AF - - private: - QString celltag_; // Added 2005-11-03 AF - QGridLayout *mainlayout_; - TreeView *treeView_; - QWidget *mainWidget_; - QLabel *label_; - - bool selected_; - bool treeviewVisible_; - QColor backgroundColor_; - - rules_t rules_; - - Cell *parent_; - Cell *next_; - Cell *last_; - Cell *previous_; - Cell *child_; - - int references_; - }; + class Cell : public QWidget + { + Q_OBJECT + + public: + typedef vector rules_t; + + Cell(QWidget *parent=0); // Changed 2005-10-27 AF + Cell(Cell &c); + virtual ~Cell(); + + //Datastructure interface. + void setNext(Cell *nxt); + Cell *next(); + bool hasNext(); + + void setLast(Cell *last); + Cell *last(); + bool hasLast(); + + void setPrevious(Cell *prev); + Cell *previous(); + bool hasPrevious(); + + Cell *parentCell(); + void setParentCell(Cell *parent); + bool hasParentCell(); + + void setChild(Cell *child); + Cell *child(); + bool hasChilds(); + + void printCell(Cell *current); + void printSurrounding(Cell *current); + + //TextCell interface. + virtual QString text() = 0; + virtual QString textHtml(){return QString::null;} // Added 2005-10-27 AF + virtual QTextCursor textCursor(); // Added 2005-10-27 AF + virtual QTextEdit* textEdit(){return 0;} // Added 2005-10-27 AF + virtual void viewExpression(const bool){}; + + //Cellgroup interface. + virtual void addChild(Cell *){} + virtual void removeChild(Cell *){} + virtual bool isClosed() const{ return false;} + virtual void setClosed(const bool closed, bool update = true){} // Changed 2006-08-24 + + virtual void addCellWidget(Cell *newCell); //Protected? + + //Rename to insertCellWidgets() instead. + virtual void addCellWidgets(){parentCell()->addCellWidgets();} + virtual void removeCellWidgets(){parentCell()->removeCellWidgets();} + + //Traversal methods + virtual void accept(Visitor &v); + + //Flags + const bool isSelected() const; + const bool isTreeViewVisible() const; + virtual bool isEditable() = 0; // Added 2005-10-27 AF + const bool isViewExpression() const; // Added 2005-11-02 AF + + //Properties + const QColor backgroundColor() const; + virtual CellStyle *style(); // Changed 2005-10-27 AF + QString cellTag(); // Added 2006-01-16 AF + virtual rules_t rules() const; + QWidget *mainWidget(); + TreeView *treeView(); + QLabel *label(); + + + + public slots: + virtual void addRule(Rule *r); + virtual void setText(QString text){} + virtual void setText(QString text, QTextCharFormat format){} // Added 2005-10-27 AF + virtual void setTextHtml(QString html){} // Added 2005-10-27 AF + virtual void setStyle(const QString &stylename); // Changed 2005-10-28 AF + virtual void setStyle(CellStyle style); // Changed 2005-10-27 AF + void setCellTag(QString tagname); // Added 2006-01-16 AF + virtual void setReadOnly(const bool){} + virtual void setFocus(const bool focus) = 0; + virtual void applyLinksToText(){} // Added 2005-11-09 AF + + virtual void setBackgroundColor(const QColor color); + virtual void setSelected(const bool selected); + virtual void setHeight(const int height); + void hideTreeView(const bool hidden); + + void wheelEvent(QWheelEvent * event); //tmp + + protected slots: + void setLabel(QLabel *label); + void setTreeWidget(TreeView *newTreeWidget); + void setMainWidget(QWidget *newWidget); + void addChapterCounter(QWidget *counter); // Added 2006-02-03 AF + + signals: + void clicked(Cell*); + void doubleClicked(int); + void changedWidth(const int); + void selected(const bool); + + // 2005-10-06 AF, bytt från Qt::ButtonState till + // Qt::KeyboardModifiers p.g.a. portning + void cellselected(Cell *, Qt::KeyboardModifiers); + + void heightChanged(); + void openLink(const QUrl *link); + void cellOpened(Cell *, const bool); + + protected: + //Events + void resizeEvent(QResizeEvent *event); + void mouseReleaseEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); + + void applyRulesToStyle(); // Added 2005-10-27 AF + + // variables + bool viewexpression_; // Added 2005-11-02 AF + CellStyle style_; // Changed 2005-10-27 AF + + private: + QString celltag_; // Added 2005-11-03 AF + QGridLayout *mainlayout_; + TreeView *treeView_; + QWidget *mainWidget_; + QLabel *label_; + + bool selected_; + bool treeviewVisible_; + QColor backgroundColor_; + + rules_t rules_; + + Cell *parent_; + Cell *next_; + Cell *last_; + Cell *previous_; + Cell *child_; + + int references_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/cellapplication.cpp b/OMNotebook/OMNotebookQT4/cellapplication.cpp index 9a56eb6c4d8..2e95a1283c5 100644 --- a/OMNotebook/OMNotebookQT4/cellapplication.cpp +++ b/OMNotebook/OMNotebookQT4/cellapplication.cpp @@ -30,7 +30,7 @@ * regarding the Qt licence: http://www.trolltech.com/products/qt/licensing.html */ -#define RUN_DRMODELICA_CONVERTION false +#define RUN_DRMODELICA_CONVERTION false //QT Headers #include @@ -58,652 +58,652 @@ namespace IAEX { - /*! - * \class CellApplication - * \author Ingemar Axelsson and Anders Fernström - * \date 2006-04-10 (update) - * - * \brief Implements the application interface. This class is the - * main controller of the program. - * - * This class has the responsibility to open new windows, open new - * documents and handle commands. Commands are sent to a - * commandCenter object where they are executed and stored (they - * should be stored). - * - * 2005-10-25 AF, Added a check to see if OMC is running, if not - - * try to start OMC. - * 2005-12-16 AF, Added code that create an instance of - * CommandCompletion, so all commands are loaded from the beginning. - * 2005-12-17 AF, Added code that create instance of stylesheet, so - * the styles are loaded from the beginning. - * 2006-01-09 AF, added a new highlight thread with the - * 'openmodelicahighlighter' as the highlighter that should be used. - * 2006-02-09 AF, code for starting omc have been moved to the - * omc interactive environment. - * 2006-02-13 AF, create temp dir - * 2006-02-27 AF, use environment variable to find DrModelica - * 2006-03-24 AF, first look for DrModelica.onb, and then for - * DrModelica.nb - * 2006-04-10 AF, use environment variable to find xml files - * 2006-04-10 AF, Open file that is sent to main - */ - CellApplication::CellApplication( int &argc, char *argv[] ) - : QObject() - { - app_ = new QApplication(argc, argv); + /*! + * \class CellApplication + * \author Ingemar Axelsson and Anders Fernström + * \date 2006-04-10 (update) + * + * \brief Implements the application interface. This class is the + * main controller of the program. + * + * This class has the responsibility to open new windows, open new + * documents and handle commands. Commands are sent to a + * commandCenter object where they are executed and stored (they + * should be stored). + * + * 2005-10-25 AF, Added a check to see if OMC is running, if not - + * try to start OMC. + * 2005-12-16 AF, Added code that create an instance of + * CommandCompletion, so all commands are loaded from the beginning. + * 2005-12-17 AF, Added code that create instance of stylesheet, so + * the styles are loaded from the beginning. + * 2006-01-09 AF, added a new highlight thread with the + * 'openmodelicahighlighter' as the highlighter that should be used. + * 2006-02-09 AF, code for starting omc have been moved to the + * omc interactive environment. + * 2006-02-13 AF, create temp dir + * 2006-02-27 AF, use environment variable to find DrModelica + * 2006-03-24 AF, first look for DrModelica.onb, and then for + * DrModelica.nb + * 2006-04-10 AF, use environment variable to find xml files + * 2006-04-10 AF, Open file that is sent to main + */ + CellApplication::CellApplication( int &argc, char *argv[] ) + : QObject() + { + app_ = new QApplication(argc, argv); #ifdef HAVE_COIN mainWindow = SoQt::init(argc, argv, argv[0]); #else mainWindow = new QMainWindow(); #endif - QDir dir; - - // 2006-05-03 AF, Notebook socket... - notebooksocket_ = new NotebookSocket( this ); - - try - { - if( notebooksocket_->connectToNotebook() ) - { - // found another OMNotebook process - cout << "SOCKET: Connected" << endl; - - if( argc > 1 ) - { - QString fileToOpen( argv[1] ); - if( dir.exists( fileToOpen ) && ( fileToOpen.endsWith( ".onb" ) || fileToOpen.endsWith( ".onbz" ) || fileToOpen.endsWith( ".nb" ))) - { - if( notebooksocket_->sendFilename( fileToOpen )) - { - cout << "SOCKET: sent filename" << endl; - exit( -1 ); - } - else - cout << "SOCKET: unable to send filename" << endl; - } - else - cout << "SOCKET: Specified filename do not exist" << endl; - - - } - else - cout << "SOCKET: No filename specified" << endl; - } - else - cout << "SOCKET: Server" << endl; - } - catch( exception &e ) - { + QDir dir; + + // 2006-05-03 AF, Notebook socket... + notebooksocket_ = new NotebookSocket( this ); + + try + { + if( notebooksocket_->connectToNotebook() ) + { + // found another OMNotebook process + cout << "SOCKET: Connected" << endl; + + if( argc > 1 ) + { + QString fileToOpen( argv[1] ); + if( dir.exists( fileToOpen ) && ( fileToOpen.endsWith( ".onb" ) || fileToOpen.endsWith( ".onbz" ) || fileToOpen.endsWith( ".nb" ))) + { + if( notebooksocket_->sendFilename( fileToOpen )) + { + cout << "SOCKET: sent filename" << endl; + exit( -1 ); + } + else + cout << "SOCKET: unable to send filename" << endl; + } + else + cout << "SOCKET: Specified filename do not exist" << endl; + + + } + else + cout << "SOCKET: No filename specified" << endl; + } + else + cout << "SOCKET: Server" << endl; + } + catch( exception &e ) + { e.what(); -// string msg = string( "Unable to create socket, the application will not work as supposed:\nTry restarting OMNotebook." )+ e.what(); -// QMessageBox::warning( 0, "Socket Error", msg.c_str() ); - } +// string msg = string( "Unable to create socket, the application will not work as supposed:\nTry restarting OMNotebook." )+ e.what(); +// QMessageBox::warning( 0, "Socket Error", msg.c_str() ); + } - // 2005-10-25 AF, added a check if omc is running, otherwise - // try to start it - // 2006-02-09 AF, Start of OMC have been moved to omcineractice- - // environment - try - { + // 2005-10-25 AF, added a check if omc is running, otherwise + // try to start it + // 2006-02-09 AF, Start of OMC have been moved to omcineractice- + // environment + try + { OmcInteractiveEnvironment* zz = OmcInteractiveEnvironment::getInstance(); - } - catch( exception &e ) - { + } + catch( exception &e ) + { e.what(); - if( !OmcInteractiveEnvironment::startOMC() ) - { - QMessageBox::critical( 0, "OMC Error", "Was unable to start OMC, OMNotebook will therefore be unable to evaluate Modelica expressions." ); - //exit( -1 ); - } - } - - // when last window closed, the applicaiton should quit also - QObject::connect(app_, SIGNAL(lastWindowClosed()), - app_, SLOT(quit())); - - //Create a commandCenter. - cmdCenter_ = new CellCommandCenter(this); - - // 2006-04-10 AF, use environment variable to find xml files - QString openmodelica = OmcInteractiveEnvironment::OpenModelicaHome(); - -// if( openmodelica.isEmpty() ) - QDir d(openmodelica); - if(!d.exists(openmodelica)) - { - QMessageBox::critical( 0, "OpenModelica Error", "The environment variable OPENMODELICAHOME="+openmodelica+" is not a valid directory" ); - exit(1); - } - - // 2006-02-13 AF, create temp dir - if( !dir.exists( "OMNotebook_tempfiles" ) ) - dir.mkdir( "OMNotebook_tempfiles" ); - - // 2005-12-17 AF, Create instance (load styles) of stylesheet - // 2006-04-10 AF, use environment variable to find stylesheet.xml - Stylesheet *sheet; - try - { - QString stylesheetfile; - if( openmodelica.endsWith("/") || openmodelica.endsWith( "\\") ) - stylesheetfile = openmodelica + "share/omnotebook/stylesheet.xml"; - else - stylesheetfile = openmodelica + "/share/omnotebook/stylesheet.xml"; - - sheet = Stylesheet::instance( stylesheetfile ); - } - catch( exception &e ) - { - QMessageBox::warning( 0, "Error", e.what(), "OK" ); - exit(-1); - } - - // 2005-12-16 AF, Create instance of CommandCompletion. - // 2006-04-10 AF, use environment variable to find commands.xml - try - { - QString commandfile; - if( openmodelica.endsWith("/") || openmodelica.endsWith( "\\") ) - commandfile = openmodelica + "share/omnotebook/commands.xml"; - else - commandfile = openmodelica + "/share/omnotebook/commands.xml"; - - CommandCompletion::instance( commandfile ); - } - catch( exception &e ) - { - QString msg = e.what(); - msg += "\nCould not create command completion class, exiting OMNotebook"; - QMessageBox::warning( 0, "Error", msg, "OK" ); - std::exit(-1); - } - - - // 2006-03-21 AF, code for converting DrModelica from mathematica - // fullform to OMNotebook (.onb) - if( RUN_DRMODELICA_CONVERTION ) - { - convertDrModelica(); - } - else - { - // 2006-01-09 AF, create a new highlight thread with the - // 'openmodelicahighlighter' as the highlighter that should be - // used. - // 2006-04-10 AF, use environment variable to find modelicacolors.xml - try - { - Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); - CellStyle style = sheet->getStyle( "Input" ); - style.textCharFormat()->setBackground( QBrush( QColor( 200, 200, 255 ) )); - - QString modelicacolorsfile; - if( openmodelica.endsWith("/") || openmodelica.endsWith( "\\") ) - modelicacolorsfile = openmodelica + "share/omnotebook/modelicacolors.xml"; - else - modelicacolorsfile = openmodelica + "/share/omnotebook/modelicacolors.xml"; - - OpenModelicaHighlighter *highlighter = new OpenModelicaHighlighter( modelicacolorsfile, *style.textCharFormat() ); - HighlighterThread *thread = HighlighterThread::instance( highlighter ); - //thread->start( QThread::LowPriority ); - } - catch( exception &e ) - { - QString msg = e.what(); - msg += "\nCould not create highlighter thread, exiting OMNotebook"; - QMessageBox::warning( 0, "Error", msg, "OK" ); - std::exit(-1); - } - - - // second arg is a file that should be opened. - if( argc > 1 ) - { - QString fileToOpen( argv[1] ); - if( dir.exists( fileToOpen ) && ( fileToOpen.endsWith( ".onb" ) || fileToOpen.endsWith( ".onbz" ) || fileToOpen.endsWith( ".nb" ))) - { - open( fileToOpen ); - } - else - { - cout << "File not found: " << fileToOpen.toStdString() << endl; - open(QString::null); - } - } - else - { - // 2006-02-27 AF, use environment variable to find DrModelica - // 2006-03-24 AF, First try to find DrModelica.onb, then .nb + if( !OmcInteractiveEnvironment::startOMC() ) + { + QMessageBox::critical( 0, "OMC Error", "Was unable to start OMC, OMNotebook will therefore be unable to evaluate Modelica expressions." ); + //exit( -1 ); + } + } + + // when last window closed, the applicaiton should quit also + QObject::connect(app_, SIGNAL(lastWindowClosed()), + app_, SLOT(quit())); + + //Create a commandCenter. + cmdCenter_ = new CellCommandCenter(this); + + // 2006-04-10 AF, use environment variable to find xml files + QString openmodelica = OmcInteractiveEnvironment::OpenModelicaHome(); + +// if( openmodelica.isEmpty() ) + QDir d(openmodelica); + if(!d.exists(openmodelica)) + { + QMessageBox::critical( 0, "OpenModelica Error", "The environment variable OPENMODELICAHOME="+openmodelica+" is not a valid directory" ); + exit(1); + } + + // 2006-02-13 AF, create temp dir + if( !dir.exists( "OMNotebook_tempfiles" ) ) + dir.mkdir( "OMNotebook_tempfiles" ); + + // 2005-12-17 AF, Create instance (load styles) of stylesheet + // 2006-04-10 AF, use environment variable to find stylesheet.xml + Stylesheet *sheet; + try + { + QString stylesheetfile; + if( openmodelica.endsWith("/") || openmodelica.endsWith( "\\") ) + stylesheetfile = openmodelica + "share/omnotebook/stylesheet.xml"; + else + stylesheetfile = openmodelica + "/share/omnotebook/stylesheet.xml"; + + sheet = Stylesheet::instance( stylesheetfile ); + } + catch( exception &e ) + { + QMessageBox::warning( 0, "Error", e.what(), "OK" ); + exit(-1); + } + + // 2005-12-16 AF, Create instance of CommandCompletion. + // 2006-04-10 AF, use environment variable to find commands.xml + try + { + QString commandfile; + if( openmodelica.endsWith("/") || openmodelica.endsWith( "\\") ) + commandfile = openmodelica + "share/omnotebook/commands.xml"; + else + commandfile = openmodelica + "/share/omnotebook/commands.xml"; + + CommandCompletion::instance( commandfile ); + } + catch( exception &e ) + { + QString msg = e.what(); + msg += "\nCould not create command completion class, exiting OMNotebook"; + QMessageBox::warning( 0, "Error", msg, "OK" ); + std::exit(-1); + } + + + // 2006-03-21 AF, code for converting DrModelica from mathematica + // fullform to OMNotebook (.onb) + if( RUN_DRMODELICA_CONVERTION ) + { + convertDrModelica(); + } + else + { + // 2006-01-09 AF, create a new highlight thread with the + // 'openmodelicahighlighter' as the highlighter that should be + // used. + // 2006-04-10 AF, use environment variable to find modelicacolors.xml + try + { + Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); + CellStyle style = sheet->getStyle( "Input" ); + style.textCharFormat()->setBackground( QBrush( QColor( 200, 200, 255 ) )); + + QString modelicacolorsfile; + if( openmodelica.endsWith("/") || openmodelica.endsWith( "\\") ) + modelicacolorsfile = openmodelica + "share/omnotebook/modelicacolors.xml"; + else + modelicacolorsfile = openmodelica + "/share/omnotebook/modelicacolors.xml"; + + OpenModelicaHighlighter *highlighter = new OpenModelicaHighlighter( modelicacolorsfile, *style.textCharFormat() ); + HighlighterThread *thread = HighlighterThread::instance( highlighter ); + //thread->start( QThread::LowPriority ); + } + catch( exception &e ) + { + QString msg = e.what(); + msg += "\nCould not create highlighter thread, exiting OMNotebook"; + QMessageBox::warning( 0, "Error", msg, "OK" ); + std::exit(-1); + } + + + // second arg is a file that should be opened. + if( argc > 1 ) + { + QString fileToOpen( argv[1] ); + if( dir.exists( fileToOpen ) && ( fileToOpen.endsWith( ".onb" ) || fileToOpen.endsWith( ".onbz" ) || fileToOpen.endsWith( ".nb" ))) + { + open( fileToOpen ); + } + else + { + cout << "File not found: " << fileToOpen.toStdString() << endl; + open(QString::null); + } + } + else + { + // 2006-02-27 AF, use environment variable to find DrModelica + // 2006-03-24 AF, First try to find DrModelica.onb, then .nb QString drmodelica = getenv("DRMODELICAHOME"); // openmodelica; - drmodelica.remove("\""); - - // ONB - if( drmodelica.endsWith("/") || drmodelica.endsWith( "\\") ) - drmodelica += "DrModelica.onb"; - else - drmodelica += "/DrModelica.onb"; - - - if( dir.exists( drmodelica )) - open(drmodelica); - else if( dir.exists( "DrModelica/DrModelica.onb" )) - open( "DrModelica/DrModelica.onb" ); - else - { - cout << "Unable to find (1): " << drmodelica.toStdString() << endl; - cout << "Unable to find (2): DrModelica/DrModelica.onb" << endl; - - // NB - drmodelica = getenv( "DRMODELICAHOME" ); - if( drmodelica.endsWith("/") || drmodelica.endsWith( "\\") ) - drmodelica += "DrModelica.nb"; - else - drmodelica += "/DrModelica.nb"; - - if( dir.exists( drmodelica )) - open(drmodelica); - else if( dir.exists( "DrModelica/DrModelica.nb" )) - open( "DrModelica/DrModelica.nb" ); - else - { - cout << "Unable to find (3): " << drmodelica.toStdString() << endl; - cout << "Unable to find (4): DrModelica/DrModelica.nb" << endl; - open(QString::null); - } - } - } - } - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2006-05-03 (update) - * - * \brief Class destructor - * - * 2005-11-24 AF, Added code that quited OMC, if it was still running. - * 2005-12-19 AF, Added code that stopped the highlighter thread, - * if it is running - * 2006-01-16 AF, Go Through remove list and remove all temporary - * files. - * 2006-02-09 AF, moved code for quiting omc to notebook windows - * closeEvent handler - * 2006-02-13 AF, remove temp dir - * 2006-05-03 AF, delete notebook socket - */ - CellApplication::~CellApplication() - { - // 2006-05-03 AF, delete notebook socket - notebooksocket_->closeNotebookSocket(); - delete notebooksocket_; - - // 2005-12-19 AF, stop highlighter thread - HighlighterThread *thread = HighlighterThread::instance(); - thread->exit(); - - // 2006-02-09 AF, moved code for quiting omc to the notebook windos - - // 2006-01-16 AF, remove temporary files - QDir dir; - for( int i = 0; i < removeList_.size(); i++ ) - { - if( !dir.remove( removeList_.at(i) )) - { - QString msg = "Could not remove temporary image " + removeList_.at(i) + " from harddrive."; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - - // 2006-02-13 AF, remove temp dir - dir.rmdir( "OMNotebook_tempfiles" ); - } - - /*! - * \author Ingemar Axelsson - */ - CommandCenter *CellApplication::commandCenter() - { - return cmdCenter_; - } - - /*! - * \author Ingemar Axelsson - */ - void CellApplication::setCommandCenter(CommandCenter *c) - { - cmdCenter_ = c; - cmdCenter_->setApplication(this); - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2006-01-12 (update) - * - * 2006-01-12 AF, added so any images in the cell are copied. - * 2006-02-13 AF, removed code for copy image - * - * \todo Create a pasteboard class as a Singleton that should be - * used instead of having a singleton inside the application class. - * Other things to do is to use the systemwide pasteboard instead. - * (Ingemar Axelsson) - */ - void CellApplication::addToPasteboard(Cell *c) - { - /* - // 2006-02-13 AF, DON'T KNOW IF I NEED TO COPY IMAGE - - // 2006-01-12 AF, copy any images in the cell - QString html = c->textHtml(); - if( typeid(InputCell) == typeid( (*c) )) - { - InputCell *iCell = dynamic_cast(c); - html = iCell->textOutputHtml(); - } - - int pos(0); - while( true ) - { - int start = html.indexOf( "= 0 ) - { - // found start of imagename - start += 10; - int end = html.indexOf( "\"", start ); - if( end >= 0 ) - { - //found end of imagename - QString imagename = html.mid( start, end - start ); - imagename.remove( "file:///" ); - QImage image( imagename ); - QString newImagename = imagename.mid( 0, imagename.length() - 4 ) + "_omnotebook_pasteboardcopy.png"; - - //cout << "PASTEBOARD:Imagename = " << imagename.toStdString() << endl; - //cout << "PASTEBOARD:Imagename = " << newImagename.toStdString() << endl; - - if( !image.isNull() ) - { - // 2006-02-13 AF, store images in temp dir - QDir dir; - dir.setPath( dir.absolutePath() + "/OMNotebook_tempfiles" ); - - QImageWriter writer( dir.absolutePath() + "/" + newImagename, "png" ); - writer.setDescription( "Temporary OMNotebook image" ); - writer.setQuality( 100 ); - writer.write( image ); - - html.replace( imagename, newImagename ); - removeTempFiles( newImagename ); - } - - pos = start + newImagename.length() + 1; - } - else - break; - } - else - break; - } - - //set html back - if( typeid(InputCell) == typeid( (*c) )) - { - InputCell *iCell = dynamic_cast(c); - iCell->setTextOutputHtml( html ); - pasteboard_.push_back(iCell); - } - else - { - c->setTextHtml( html ); - pasteboard_.push_back(c); - } - */ - pasteboard_.push_back(c); - } - - /*! - * \author Ingemar Axelsson - * - * This is used to clear the pasteboard. This is an ugly solution. - */ - void CellApplication::clearPasteboard() - { - pasteboard_.clear(); - } - - /*! - * \author Ingemar Axelsson - * - * \breif returns a vector with all content of the pasteboard. - */ - vector CellApplication::pasteboard() - { - return pasteboard_; - } - - /*! - * \author Ingemar Axelsson - */ - int CellApplication::exec() - { - return app_->exec(); - } - - /*! - * \author Ingemar Axelsson - */ - void CellApplication::add(Document *d) - { - documents_.push_back(d); - } - - /*! - * \author Ingemar Axelsson - */ - void CellApplication::add(DocumentView *d) - { - views_.push_back(d); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2006-05-03 (update) - * - * \brief Open an file, and display the content of hte file - * - * 2005-09-22 AF, added the filename to the NotebookWindow() call - * 2005-10-11 AF, Porting, added resize call, so all cells get the - * correct size. Ugly way! - * 2005-11-30 AF, added code to launch the visitor that applies - * hide() and show() to groupcells. - * 2005-12-01 AF, added a try-catch statment around the function - * 2006-01-17 AF, added code that set the change variable in a - * document to false. - * 2006-01-31 AF, open windows minimized, then show normal when - * all operations are done on the window. - * 2006-05-03 AF, during open, stop highlighter - */ - void CellApplication::open( const QString filename, int readmode ) - { - // 2005-12-01 AF, Added try-catch - try - { - //2006-05-03 AF, during open, stop highlighter - HighlighterThread *thread = HighlighterThread::instance(); - thread->setStop( true ); - - //1. Create a new document. - Document *d = new CellDocument( this, filename, readmode ); - add(d); - - //2. Create a new View. - // 2005-09-22 AF: Added 'filename' in NotebookWindow() call - DocumentView *v = new NotebookWindow(d, filename); - add(v); - - // 2006-01-31 AF, Open window minimized insted of normal - v->showMinimized(); - - // 2005-10-11 AF, Porting, added resize so all cells get the - // correct size. Ugly way! - -// v->resize( 810, 610 ); //not working with Qt 4.3 - - // 2006-01-17 AF, when the document have been opened, set the - // changed variable to false. - v->document()->setChanged( false ); - - // 2006-01-31 AF, show window again - v->showNormal(); - - v->resize( 801, 600 ); //fjass - - // 2005-11-30 AF, apply hide() and show() to closed groupcells - // childs in the documentview - UpdateGroupcellVisitor visitor; - v->document()->runVisitor( visitor ); - - - // 2006-05-03 AF, done, start highlighter again - thread->setStop( false ); - } - catch( exception &e ) - { - throw e; - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-16 - * - * \brief Add filename to a list of temporary files that should - * be deleted when the applicaiton quits. - */ - void CellApplication::removeTempFiles(QString filename) - { - removeList_.append( filename ); - } - - /*! - * \author Anders Fernström - * \date 2006-01-27 - * - * \brief returns list of all current doucment views - */ - vector CellApplication::documentViewList() - { - return views_; - } - - /*! - * \author Anders Fernström - * \date 2006-01-27 - * - * \brief remove document view from internal list, also remove - * document - */ - void CellApplication::removeDocumentView( DocumentView *view ) - { - vector::iterator d_iter = documents_.begin(); - while( d_iter != documents_.end() ) - { - if( (*d_iter) == view->document() ) - { - documents_.erase( d_iter ); - break; - } - else - ++d_iter; - } - - vector::iterator dv_iter = views_.begin(); - while( dv_iter != views_.end() ) - { - if( (*dv_iter) == view ) - { - views_.erase( dv_iter ); - break; - } - else - ++dv_iter; - } - } - - /*! - * \author Anders Fernström - * \date 2006-03-21 - * - * \brief convert DrModelica documentation into OMNotebook format - * (.onb). - * - * NO A WORKING FUNCTION - * -Temporary function - * -The function is not called anywhere. - * -The function asume that DrModelia is located in 'C:\OpenModelica132\DrModelicaConv' - * -Save documents to 'C:\OpenModelica132\DrModelicaConv' - * -remove all .nb file - */ - void CellApplication::convertDrModelica() - { - cout << "CONVERTING DRMODELICA" << endl; - cout << "---------------------" << endl << endl; - - // load from - QString path = "C:/OpenModelica132/DrModelicaConv"; - QDir dir( path ); - dir.setSorting( QDir::Name ); - - if( dir.exists() ) - { - // get dirs - dir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot); - QStringList dirList = dir.entryList(); - dirList.prepend( "" ); - - for( int i = 0; i < dirList.size(); ++i ) - { - // get file names - QDir fileDir( dir.absolutePath() + "/" + dirList.at(i) ); - fileDir.setSorting( QDir::Name ); - fileDir.setFilter( QDir::Files ); - //fileDir.setNameFilters( QStringList(".nb") ); - QStringList fileList = fileDir.entryList(); - - // loop through all files - for( int j = 0; j < fileList.size(); ++j ) - { - cout << "Loading: " << fileDir.absolutePath().toStdString() + - string( "/" ) + fileList.at(j).toStdString() << endl; - - Document *d = new CellDocument( this, fileDir.absolutePath() + - QString( "/" ) + fileList.at(j), READMODE_CONVERTING_ONB ); - - // save file - QString filename = fileList.at(j); - filename.replace( ".nb", ".onb" ); - - cout << "Saving: " << dir.absolutePath().toStdString() + - string( "/" ) + dirList.at(i).toStdString() + string( "/" ) + - filename.toStdString() << endl; - - SaveDocumentCommand command( d, dir.absolutePath() + - QString( "/" ) + dirList.at(i) + QString( "/" ) + filename ); - this->commandCenter()->executeCommand( &command ); - - cout << "DONE!" << endl << endl; - - // delete file - delete d; - fileDir.remove( fileList.at(j) ); - } - } - } - - cout << "CONVERTION DONE !!!" << endl; - } + drmodelica.remove("\""); + + // ONB + if( drmodelica.endsWith("/") || drmodelica.endsWith( "\\") ) + drmodelica += "DrModelica.onb"; + else + drmodelica += "/DrModelica.onb"; + + + if( dir.exists( drmodelica )) + open(drmodelica); + else if( dir.exists( "DrModelica/DrModelica.onb" )) + open( "DrModelica/DrModelica.onb" ); + else + { + cout << "Unable to find (1): " << drmodelica.toStdString() << endl; + cout << "Unable to find (2): DrModelica/DrModelica.onb" << endl; + + // NB + drmodelica = getenv( "DRMODELICAHOME" ); + if( drmodelica.endsWith("/") || drmodelica.endsWith( "\\") ) + drmodelica += "DrModelica.nb"; + else + drmodelica += "/DrModelica.nb"; + + if( dir.exists( drmodelica )) + open(drmodelica); + else if( dir.exists( "DrModelica/DrModelica.nb" )) + open( "DrModelica/DrModelica.nb" ); + else + { + cout << "Unable to find (3): " << drmodelica.toStdString() << endl; + cout << "Unable to find (4): DrModelica/DrModelica.nb" << endl; + open(QString::null); + } + } + } + } + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2006-05-03 (update) + * + * \brief Class destructor + * + * 2005-11-24 AF, Added code that quited OMC, if it was still running. + * 2005-12-19 AF, Added code that stopped the highlighter thread, + * if it is running + * 2006-01-16 AF, Go Through remove list and remove all temporary + * files. + * 2006-02-09 AF, moved code for quiting omc to notebook windows + * closeEvent handler + * 2006-02-13 AF, remove temp dir + * 2006-05-03 AF, delete notebook socket + */ + CellApplication::~CellApplication() + { + // 2006-05-03 AF, delete notebook socket + notebooksocket_->closeNotebookSocket(); + delete notebooksocket_; + + // 2005-12-19 AF, stop highlighter thread + HighlighterThread *thread = HighlighterThread::instance(); + thread->exit(); + + // 2006-02-09 AF, moved code for quiting omc to the notebook windos + + // 2006-01-16 AF, remove temporary files + QDir dir; + for( int i = 0; i < removeList_.size(); i++ ) + { + if( !dir.remove( removeList_.at(i) )) + { + QString msg = "Could not remove temporary image " + removeList_.at(i) + " from harddrive."; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + + // 2006-02-13 AF, remove temp dir + dir.rmdir( "OMNotebook_tempfiles" ); + } + + /*! + * \author Ingemar Axelsson + */ + CommandCenter *CellApplication::commandCenter() + { + return cmdCenter_; + } + + /*! + * \author Ingemar Axelsson + */ + void CellApplication::setCommandCenter(CommandCenter *c) + { + cmdCenter_ = c; + cmdCenter_->setApplication(this); + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2006-01-12 (update) + * + * 2006-01-12 AF, added so any images in the cell are copied. + * 2006-02-13 AF, removed code for copy image + * + * \todo Create a pasteboard class as a Singleton that should be + * used instead of having a singleton inside the application class. + * Other things to do is to use the systemwide pasteboard instead. + * (Ingemar Axelsson) + */ + void CellApplication::addToPasteboard(Cell *c) + { + /* + // 2006-02-13 AF, DON'T KNOW IF I NEED TO COPY IMAGE + + // 2006-01-12 AF, copy any images in the cell + QString html = c->textHtml(); + if( typeid(InputCell) == typeid( (*c) )) + { + InputCell *iCell = dynamic_cast(c); + html = iCell->textOutputHtml(); + } + + int pos(0); + while( true ) + { + int start = html.indexOf( "= 0 ) + { + // found start of imagename + start += 10; + int end = html.indexOf( "\"", start ); + if( end >= 0 ) + { + //found end of imagename + QString imagename = html.mid( start, end - start ); + imagename.remove( "file:///" ); + QImage image( imagename ); + QString newImagename = imagename.mid( 0, imagename.length() - 4 ) + "_omnotebook_pasteboardcopy.png"; + + //cout << "PASTEBOARD:Imagename = " << imagename.toStdString() << endl; + //cout << "PASTEBOARD:Imagename = " << newImagename.toStdString() << endl; + + if( !image.isNull() ) + { + // 2006-02-13 AF, store images in temp dir + QDir dir; + dir.setPath( dir.absolutePath() + "/OMNotebook_tempfiles" ); + + QImageWriter writer( dir.absolutePath() + "/" + newImagename, "png" ); + writer.setDescription( "Temporary OMNotebook image" ); + writer.setQuality( 100 ); + writer.write( image ); + + html.replace( imagename, newImagename ); + removeTempFiles( newImagename ); + } + + pos = start + newImagename.length() + 1; + } + else + break; + } + else + break; + } + + //set html back + if( typeid(InputCell) == typeid( (*c) )) + { + InputCell *iCell = dynamic_cast(c); + iCell->setTextOutputHtml( html ); + pasteboard_.push_back(iCell); + } + else + { + c->setTextHtml( html ); + pasteboard_.push_back(c); + } + */ + pasteboard_.push_back(c); + } + + /*! + * \author Ingemar Axelsson + * + * This is used to clear the pasteboard. This is an ugly solution. + */ + void CellApplication::clearPasteboard() + { + pasteboard_.clear(); + } + + /*! + * \author Ingemar Axelsson + * + * \breif returns a vector with all content of the pasteboard. + */ + vector CellApplication::pasteboard() + { + return pasteboard_; + } + + /*! + * \author Ingemar Axelsson + */ + int CellApplication::exec() + { + return app_->exec(); + } + + /*! + * \author Ingemar Axelsson + */ + void CellApplication::add(Document *d) + { + documents_.push_back(d); + } + + /*! + * \author Ingemar Axelsson + */ + void CellApplication::add(DocumentView *d) + { + views_.push_back(d); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2006-05-03 (update) + * + * \brief Open an file, and display the content of hte file + * + * 2005-09-22 AF, added the filename to the NotebookWindow() call + * 2005-10-11 AF, Porting, added resize call, so all cells get the + * correct size. Ugly way! + * 2005-11-30 AF, added code to launch the visitor that applies + * hide() and show() to groupcells. + * 2005-12-01 AF, added a try-catch statment around the function + * 2006-01-17 AF, added code that set the change variable in a + * document to false. + * 2006-01-31 AF, open windows minimized, then show normal when + * all operations are done on the window. + * 2006-05-03 AF, during open, stop highlighter + */ + void CellApplication::open( const QString filename, int readmode ) + { + // 2005-12-01 AF, Added try-catch + try + { + //2006-05-03 AF, during open, stop highlighter + HighlighterThread *thread = HighlighterThread::instance(); + thread->setStop( true ); + + //1. Create a new document. + Document *d = new CellDocument( this, filename, readmode ); + add(d); + + //2. Create a new View. + // 2005-09-22 AF: Added 'filename' in NotebookWindow() call + DocumentView *v = new NotebookWindow(d, filename); + add(v); + + // 2006-01-31 AF, Open window minimized insted of normal + v->showMinimized(); + + // 2005-10-11 AF, Porting, added resize so all cells get the + // correct size. Ugly way! + +// v->resize( 810, 610 ); //not working with Qt 4.3 + + // 2006-01-17 AF, when the document have been opened, set the + // changed variable to false. + v->document()->setChanged( false ); + + // 2006-01-31 AF, show window again + v->showNormal(); + + v->resize( 801, 600 ); //fjass + + // 2005-11-30 AF, apply hide() and show() to closed groupcells + // childs in the documentview + UpdateGroupcellVisitor visitor; + v->document()->runVisitor( visitor ); + + + // 2006-05-03 AF, done, start highlighter again + thread->setStop( false ); + } + catch( exception &e ) + { + throw e; + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-16 + * + * \brief Add filename to a list of temporary files that should + * be deleted when the applicaiton quits. + */ + void CellApplication::removeTempFiles(QString filename) + { + removeList_.append( filename ); + } + + /*! + * \author Anders Fernström + * \date 2006-01-27 + * + * \brief returns list of all current doucment views + */ + vector CellApplication::documentViewList() + { + return views_; + } + + /*! + * \author Anders Fernström + * \date 2006-01-27 + * + * \brief remove document view from internal list, also remove + * document + */ + void CellApplication::removeDocumentView( DocumentView *view ) + { + vector::iterator d_iter = documents_.begin(); + while( d_iter != documents_.end() ) + { + if( (*d_iter) == view->document() ) + { + documents_.erase( d_iter ); + break; + } + else + ++d_iter; + } + + vector::iterator dv_iter = views_.begin(); + while( dv_iter != views_.end() ) + { + if( (*dv_iter) == view ) + { + views_.erase( dv_iter ); + break; + } + else + ++dv_iter; + } + } + + /*! + * \author Anders Fernström + * \date 2006-03-21 + * + * \brief convert DrModelica documentation into OMNotebook format + * (.onb). + * + * NO A WORKING FUNCTION + * -Temporary function + * -The function is not called anywhere. + * -The function asume that DrModelia is located in 'C:\OpenModelica132\DrModelicaConv' + * -Save documents to 'C:\OpenModelica132\DrModelicaConv' + * -remove all .nb file + */ + void CellApplication::convertDrModelica() + { + cout << "CONVERTING DRMODELICA" << endl; + cout << "---------------------" << endl << endl; + + // load from + QString path = "C:/OpenModelica132/DrModelicaConv"; + QDir dir( path ); + dir.setSorting( QDir::Name ); + + if( dir.exists() ) + { + // get dirs + dir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot); + QStringList dirList = dir.entryList(); + dirList.prepend( "" ); + + for( int i = 0; i < dirList.size(); ++i ) + { + // get file names + QDir fileDir( dir.absolutePath() + "/" + dirList.at(i) ); + fileDir.setSorting( QDir::Name ); + fileDir.setFilter( QDir::Files ); + //fileDir.setNameFilters( QStringList(".nb") ); + QStringList fileList = fileDir.entryList(); + + // loop through all files + for( int j = 0; j < fileList.size(); ++j ) + { + cout << "Loading: " << fileDir.absolutePath().toStdString() + + string( "/" ) + fileList.at(j).toStdString() << endl; + + Document *d = new CellDocument( this, fileDir.absolutePath() + + QString( "/" ) + fileList.at(j), READMODE_CONVERTING_ONB ); + + // save file + QString filename = fileList.at(j); + filename.replace( ".nb", ".onb" ); + + cout << "Saving: " << dir.absolutePath().toStdString() + + string( "/" ) + dirList.at(i).toStdString() + string( "/" ) + + filename.toStdString() << endl; + + SaveDocumentCommand command( d, dir.absolutePath() + + QString( "/" ) + dirList.at(i) + QString( "/" ) + filename ); + this->commandCenter()->executeCommand( &command ); + + cout << "DONE!" << endl << endl; + + // delete file + delete d; + fileDir.remove( fileList.at(j) ); + } + } + } + + cout << "CONVERTION DONE !!!" << endl; + } } diff --git a/OMNotebook/OMNotebookQT4/cellapplication.h b/OMNotebook/OMNotebookQT4/cellapplication.h index 4c498d464d1..55e3fbac6d1 100644 --- a/OMNotebook/OMNotebookQT4/cellapplication.h +++ b/OMNotebook/OMNotebookQT4/cellapplication.h @@ -45,49 +45,49 @@ namespace IAEX { - // forward declaration - class NotebookSocket; + // forward declaration + class NotebookSocket; - class CellApplication : public QObject, public Application - { - Q_OBJECT - public: - CellApplication(int &argc, char *argv[]); - virtual ~CellApplication(); + class CellApplication : public QObject, public Application + { + Q_OBJECT + public: + CellApplication(int &argc, char *argv[]); + virtual ~CellApplication(); - virtual CommandCenter *commandCenter(); - virtual void setCommandCenter(CommandCenter *c); + virtual CommandCenter *commandCenter(); + virtual void setCommandCenter(CommandCenter *c); - virtual void addToPasteboard(Cell *c); - virtual void clearPasteboard(); - vector pasteboard(); + virtual void addToPasteboard(Cell *c); + virtual void clearPasteboard(); + vector pasteboard(); - int exec(); - void add(Document *doc); - void add(DocumentView *view); + int exec(); + void add(Document *doc); + void add(DocumentView *view); - void open(const QString filename, int readmode = READMODE_NORMAL ); - void removeTempFiles(QString filename); // Added 2006-01-16 AF - vector documentViewList(); // Added 2006-01-27 AF - void removeDocumentView( DocumentView *view ); // Added 2006-01-27 AF + void open(const QString filename, int readmode = READMODE_NORMAL ); + void removeTempFiles(QString filename); // Added 2006-01-16 AF + vector documentViewList(); // Added 2006-01-27 AF + void removeDocumentView( DocumentView *view ); // Added 2006-01-27 AF QApplication* getApplication() { return app_; } QWidget* getMainWindow() { return mainWindow; } - private: - void convertDrModelica(); // Added 2006-03-21 AF + private: + void convertDrModelica(); // Added 2006-03-21 AF - private: - QApplication *app_; + private: + QApplication *app_; QWidget* mainWindow; - vector documents_; - vector views_; - CommandCenter *cmdCenter_; - vector pasteboard_; - QStringList removeList_; // Added 2006-01-16 AF + vector documents_; + vector views_; + CommandCenter *cmdCenter_; + vector pasteboard_; + QStringList removeList_; // Added 2006-01-16 AF - NotebookSocket *notebooksocket_; - }; + NotebookSocket *notebooksocket_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/cellcommandcenter.cpp b/OMNotebook/OMNotebookQT4/cellcommandcenter.cpp index df654e94f2e..782e57240e9 100644 --- a/OMNotebook/OMNotebookQT4/cellcommandcenter.cpp +++ b/OMNotebook/OMNotebookQT4/cellcommandcenter.cpp @@ -63,33 +63,33 @@ namespace IAEX storeCommands(); } - void CellCommandCenter::executeCommand(Command *cmd) - { - cmd->setApplication(application()); - - //Save for undo redo, or atleast for printing. - storage_.push_back(cmd); - - // 2005-12-01 AF, Added try-catch and messagebox - try - { - cmd->execute(); - } - catch( exception &e ) - { - QString msg = e.what(); - - if( 0 <= msg.indexOf( "OpenFileCommand()", 0, Qt::CaseInsensitive )) - { - msg += QString("\r\n\r\nIf you are trying to open an old ") + - QString("OMNotebook file, use menu 'File->Import->") + - QString("Old OMNotebook file' instead."); - } - - // display message box - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } + void CellCommandCenter::executeCommand(Command *cmd) + { + cmd->setApplication(application()); + + //Save for undo redo, or atleast for printing. + storage_.push_back(cmd); + + // 2005-12-01 AF, Added try-catch and messagebox + try + { + cmd->execute(); + } + catch( exception &e ) + { + QString msg = e.what(); + + if( 0 <= msg.indexOf( "OpenFileCommand()", 0, Qt::CaseInsensitive )) + { + msg += QString("\r\n\r\nIf you are trying to open an old ") + + QString("OMNotebook file, use menu 'File->Import->") + + QString("Old OMNotebook file' instead."); + } + + // display message box + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } CellApplication *CellCommandCenter::application() { @@ -109,7 +109,7 @@ namespace IAEX for(;i!= storage_.end();++i) { - diskstorage << (*i)->commandName().toStdString() << endl; + diskstorage << (*i)->commandName().toStdString() << endl; } } } diff --git a/OMNotebook/OMNotebookQT4/cellcommands.cpp b/OMNotebook/OMNotebookQT4/cellcommands.cpp index 897200e7dbe..e6f64a17117 100644 --- a/OMNotebook/OMNotebookQT4/cellcommands.cpp +++ b/OMNotebook/OMNotebookQT4/cellcommands.cpp @@ -59,80 +59,80 @@ namespace IAEX { /*! * \class AddCellCommand - * \author Ingemar Axelsson and Anders Fernström + * \author Ingemar Axelsson and Anders Fernström * * \brief Command for adding a new cell to the cellstructure. */ - void AddCellCommand::execute() - { - try - { - CellCursor *cursor = document()->getCursor(); - - Factory *fac = document()->cellFactory(); - - // 2005-10-28 AF, changed style from QString to CellStyle - CellStyle style; - - if(cursor->currentCell()->hasChilds()) - style = *cursor->currentCell()->child()->style(); - else - style = *cursor->currentCell()->style(); - - - //This does not work. - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(true); - cursor->currentCell()->child()->setFocus(false); - } - } - else - { - cursor->currentCell()->setReadOnly(true); - cursor->currentCell()->setFocus(false); - } - - // 2005-11-21 AF, Added check if the current cell is a - // inputcell, set style to 'text' insted. - // 2006-02-03 AF, added check if the current cell is a - // groupcell - if( style.name() == "input" || style.name() == "Input" || style.name() == "ModelicaInput" || - style.name() == "cellgroup" ) - cursor->addBefore(fac->createCell( "Text" )); - else - cursor->addBefore(fac->createCell(style.name())); - - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(false); - cursor->currentCell()->child()->setFocus(true); - } - } - else - { - cursor->currentCell()->setReadOnly(false); - cursor->currentCell()->setFocus(true); - } - - //2006-01-18 AF, set docuement changed - document()->setChanged( true ); - } - catch(exception &e) - { - // 2006-01-30 AF, add exception - string str = string("AddCellCommand(), Exception: \n") + e.what(); - throw runtime_error( str.c_str() ); - } - } + void AddCellCommand::execute() + { + try + { + CellCursor *cursor = document()->getCursor(); + + Factory *fac = document()->cellFactory(); + + // 2005-10-28 AF, changed style from QString to CellStyle + CellStyle style; + + if(cursor->currentCell()->hasChilds()) + style = *cursor->currentCell()->child()->style(); + else + style = *cursor->currentCell()->style(); + + + //This does not work. + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(true); + cursor->currentCell()->child()->setFocus(false); + } + } + else + { + cursor->currentCell()->setReadOnly(true); + cursor->currentCell()->setFocus(false); + } + + // 2005-11-21 AF, Added check if the current cell is a + // inputcell, set style to 'text' insted. + // 2006-02-03 AF, added check if the current cell is a + // groupcell + if( style.name() == "input" || style.name() == "Input" || style.name() == "ModelicaInput" || + style.name() == "cellgroup" ) + cursor->addBefore(fac->createCell( "Text" )); + else + cursor->addBefore(fac->createCell(style.name())); + + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(false); + cursor->currentCell()->child()->setFocus(true); + } + } + else + { + cursor->currentCell()->setReadOnly(false); + cursor->currentCell()->setFocus(true); + } + + //2006-01-18 AF, set docuement changed + document()->setChanged( true ); + } + catch(exception &e) + { + // 2006-01-30 AF, add exception + string str = string("AddCellCommand(), Exception: \n") + e.what(); + throw runtime_error( str.c_str() ); + } + } /*! * \class CreateNewCellCommand - * \author Ingemar Axelsson + * \author Ingemar Axelsson * * \brief Command for creating a new cell. */ @@ -140,60 +140,60 @@ namespace IAEX { try { - CellCursor *cursor = document()->getCursor(); - - Factory *fac = document()->cellFactory(); - - //This does not work. - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(true); - cursor->currentCell()->child()->setFocus(false); - } - } - else - { - cursor->currentCell()->setReadOnly(true); - cursor->currentCell()->setFocus(false); - } - - cursor->addBefore(fac->createCell(style_)); - - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(false); - cursor->currentCell()->child()->setFocus(true); - } - } - else - { - cursor->currentCell()->setReadOnly(false); - cursor->currentCell()->setFocus(true); - } - - //2006-01-18 AF, set docuement changed - document()->setChanged( true ); + CellCursor *cursor = document()->getCursor(); + + Factory *fac = document()->cellFactory(); + + //This does not work. + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(true); + cursor->currentCell()->child()->setFocus(false); + } + } + else + { + cursor->currentCell()->setReadOnly(true); + cursor->currentCell()->setFocus(false); + } + + cursor->addBefore(fac->createCell(style_)); + + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(false); + cursor->currentCell()->child()->setFocus(true); + } + } + else + { + cursor->currentCell()->setReadOnly(false); + cursor->currentCell()->setFocus(true); + } + + //2006-01-18 AF, set docuement changed + document()->setChanged( true ); } catch(exception &e) { - // 2006-01-30 AF, add exception - string str = string("CreateNewCommand(), Exception: \n") + e.what(); - throw runtime_error( str.c_str() ); + // 2006-01-30 AF, add exception + string str = string("CreateNewCommand(), Exception: \n") + e.what(); + throw runtime_error( str.c_str() ); } } /*! * \class CopySelectedCellsCommand - * \author Ingemar Axelsson - * + * \author Ingemar Axelsson + * * \brief copy a cell. Adds a copy of the cell on the pasteboard. * - * + * * \todo Implement some kind of internal state or copy constructors * for all cells. This to make the copy process more general.(Ingemar Axelsson) * @@ -208,21 +208,21 @@ namespace IAEX if(cells.empty()) { - return; - //Empty pasteboard. - //application()->clearPasteboard(); - //application()->addToPasteboard(c->currentCell()); + return; + //Empty pasteboard. + //application()->clearPasteboard(); + //application()->addToPasteboard(c->currentCell()); } else { - document()->clearSelection(); //Notice - application()->clearPasteboard(); - - vector::iterator i = cells.begin(); - for(;i != cells.end();++i) - { - application()->addToPasteboard((*i)); - } + document()->clearSelection(); //Notice + application()->clearPasteboard(); + + vector::iterator i = cells.begin(); + for(;i != cells.end();++i) + { + application()->addToPasteboard((*i)); + } } } @@ -232,45 +232,45 @@ namespace IAEX { try { - CellCursor *c = document()->getCursor(); - vector cells = document()->getSelection(); - - if(cells.empty()) - { - return; - //Empty pasteboard. - //application()->clearPasteboard(); - //application()->addToPasteboard(c->currentCell()); - - //c->removeCurrentCell(); - } - else - { - - document()->clearSelection(); //Notice - application()->clearPasteboard(); - - vector::iterator i = cells.begin(); - for(;i != cells.end();++i) - { - c->moveAfter((*i)); - - //1. Copy cell to pasteboard. - application()->addToPasteboard(c->currentCell()); - - //2. Delete Cell. - c->removeCurrentCell(); - } - } - - //2006-01-18 AF, set docuement changed - document()->setChanged( true ); + CellCursor *c = document()->getCursor(); + vector cells = document()->getSelection(); + + if(cells.empty()) + { + return; + //Empty pasteboard. + //application()->clearPasteboard(); + //application()->addToPasteboard(c->currentCell()); + + //c->removeCurrentCell(); + } + else + { + + document()->clearSelection(); //Notice + application()->clearPasteboard(); + + vector::iterator i = cells.begin(); + for(;i != cells.end();++i) + { + c->moveAfter((*i)); + + //1. Copy cell to pasteboard. + application()->addToPasteboard(c->currentCell()); + + //2. Delete Cell. + c->removeCurrentCell(); + } + } + + //2006-01-18 AF, set docuement changed + document()->setChanged( true ); } catch(exception &e) { - // 2006-01-30 AF, add message box - string str = string("DeleteCurrentCellsCommand(), Exception: \n") + e.what(); - throw runtime_error( str.c_str() ); + // 2006-01-30 AF, add message box + string str = string("DeleteCurrentCellsCommand(), Exception: \n") + e.what(); + throw runtime_error( str.c_str() ); } } @@ -282,169 +282,169 @@ namespace IAEX // gruppceller specialbehandlas så att deras subceller också // kopieras. Just nu funkar det att kopiera enstaka celler. Men // inte gruppceller. - void PasteCellsCommand::execute() - { - try - { - vector cells = application()->pasteboard(); - - // Insert new cells before this position. - if(!cells.empty()) - { - //Reverse iterator!!!!! - //vector::reverse_iterator i = cells.rbegin(); - //for(;i != cells.rend();++i) - // AF, Not reverse - vector::iterator i = cells.begin(); - for(;i != cells.end();++i) - { - try - { - pasteCell( (*i) ); - } - catch(exception &e) - { - throw e; - } - } - } - - //2006-01-18 AF, set docuement changed - document()->setChanged( true ); - } - catch(exception &e) - { - // 2006-01-30 AF, add exception - string str = string("PasteCellsCommand(), Exception: \n") + e.what(); - throw runtime_error( str.c_str() ); - } - } - - // 2006-01-16 AF, move this code to a seperated function - // 2006-09-04 AF, redid entire function, so groupcells are created, have there - // children added and THEN add to the documnet - void PasteCellsCommand::pasteCell( Cell *cell, CellGroup *groupcell ) - { - // get cursor, factory and cell style - CellCursor *cursor = document()->getCursor(); - Factory *factory = document()->cellFactory(); - CellStyle style = *cell->style(); - - // set focus and readonly stuff (from old implementation, IA) - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(true); - cursor->currentCell()->child()->setFocus(false); - } - } - else - { - cursor->currentCell()->setReadOnly(true); - cursor->currentCell()->setFocus(false); - } - - // create the new cell, if there exists a groupcell add the new cell to - // that groupcell. - Cell* newCell = factory->createCell( style.name() ); -// if( groupcell ) -// groupcell->addChild( newCell ); - - - // set content of cell - // ************************************************************************* - - // COPY - EVERY CELL TYPE - // ---------------------- - newCell->setCellTag( cell->cellTag() ); - - // rules - rules_t rules = cell->rules(); - rules_t::iterator current = rules.begin(); - while( current != rules.end() ) - { - newCell->addRule( (*current) ); - ++current; - } - - // COPY - SPECIFIC FOR CELL TYPE - // ----------------------------- - if( typeid(CellGroup) == typeid( *newCell )) - { - CellGroup *newCellGroup = dynamic_cast( newCell ); - newCellGroup->setClosed( cell->isClosed() ); - - if( cell->hasChilds() ) - { - Cell* child = cell->child(); - while( child ) - { - pasteCell( child, newCellGroup ); - child = child->next(); - } - } - } - else if( typeid(InputCell) == typeid( *newCell )) - { - InputCell *newInputCell = dynamic_cast( newCell ); - InputCell *oldInputCell = dynamic_cast( cell ); - - newInputCell->setStyle( style ); - newInputCell->setText( oldInputCell->text() ); - - if( oldInputCell->isEvaluated() ) - { - newInputCell->setEvaluated( true ); - - if( oldInputCell->isJavaPlot() ) - newInputCell->setTextOutputHtml( oldInputCell->textOutputHtml() ); - else - newInputCell->setTextOutput( oldInputCell->textOutput() ); - } - else - newInputCell->setEvaluated( false ); - - newInputCell->setClosed( oldInputCell->isClosed() ); - } - else if( typeid(TextCell) == typeid( *newCell )) - { - newCell->setStyle( style ); - newCell->setTextHtml( cell->textHtml() ); - } - else - { - // Error - throw runtime_error("pasteCell(): Unknown celltype."); - } - // ************************************************************************* - - - // Add cell to document - if( !groupcell ) - cursor->addBefore( newCell ); - else //if there exists a groupcell add the new cell to that groupcell. - groupcell->addChild( newCell ); - - // set focus and readonly stuff (from old implementation, IA) - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(false); - cursor->currentCell()->child()->setFocus(true); - } - } - else - { - cursor->currentCell()->setReadOnly(false); - cursor->currentCell()->setFocus(true); - } - } + void PasteCellsCommand::execute() + { + try + { + vector cells = application()->pasteboard(); + + // Insert new cells before this position. + if(!cells.empty()) + { + //Reverse iterator!!!!! + //vector::reverse_iterator i = cells.rbegin(); + //for(;i != cells.rend();++i) + // AF, Not reverse + vector::iterator i = cells.begin(); + for(;i != cells.end();++i) + { + try + { + pasteCell( (*i) ); + } + catch(exception &e) + { + throw e; + } + } + } + + //2006-01-18 AF, set docuement changed + document()->setChanged( true ); + } + catch(exception &e) + { + // 2006-01-30 AF, add exception + string str = string("PasteCellsCommand(), Exception: \n") + e.what(); + throw runtime_error( str.c_str() ); + } + } + + // 2006-01-16 AF, move this code to a seperated function + // 2006-09-04 AF, redid entire function, so groupcells are created, have there + // children added and THEN add to the documnet + void PasteCellsCommand::pasteCell( Cell *cell, CellGroup *groupcell ) + { + // get cursor, factory and cell style + CellCursor *cursor = document()->getCursor(); + Factory *factory = document()->cellFactory(); + CellStyle style = *cell->style(); + + // set focus and readonly stuff (from old implementation, IA) + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(true); + cursor->currentCell()->child()->setFocus(false); + } + } + else + { + cursor->currentCell()->setReadOnly(true); + cursor->currentCell()->setFocus(false); + } + + // create the new cell, if there exists a groupcell add the new cell to + // that groupcell. + Cell* newCell = factory->createCell( style.name() ); +// if( groupcell ) +// groupcell->addChild( newCell ); + + + // set content of cell + // ************************************************************************* + + // COPY - EVERY CELL TYPE + // ---------------------- + newCell->setCellTag( cell->cellTag() ); + + // rules + rules_t rules = cell->rules(); + rules_t::iterator current = rules.begin(); + while( current != rules.end() ) + { + newCell->addRule( (*current) ); + ++current; + } + + // COPY - SPECIFIC FOR CELL TYPE + // ----------------------------- + if( typeid(CellGroup) == typeid( *newCell )) + { + CellGroup *newCellGroup = dynamic_cast( newCell ); + newCellGroup->setClosed( cell->isClosed() ); + + if( cell->hasChilds() ) + { + Cell* child = cell->child(); + while( child ) + { + pasteCell( child, newCellGroup ); + child = child->next(); + } + } + } + else if( typeid(InputCell) == typeid( *newCell )) + { + InputCell *newInputCell = dynamic_cast( newCell ); + InputCell *oldInputCell = dynamic_cast( cell ); + + newInputCell->setStyle( style ); + newInputCell->setText( oldInputCell->text() ); + + if( oldInputCell->isEvaluated() ) + { + newInputCell->setEvaluated( true ); + + if( oldInputCell->isJavaPlot() ) + newInputCell->setTextOutputHtml( oldInputCell->textOutputHtml() ); + else + newInputCell->setTextOutput( oldInputCell->textOutput() ); + } + else + newInputCell->setEvaluated( false ); + + newInputCell->setClosed( oldInputCell->isClosed() ); + } + else if( typeid(TextCell) == typeid( *newCell )) + { + newCell->setStyle( style ); + newCell->setTextHtml( cell->textHtml() ); + } + else + { + // Error + throw runtime_error("pasteCell(): Unknown celltype."); + } + // ************************************************************************* + + + // Add cell to document + if( !groupcell ) + cursor->addBefore( newCell ); + else //if there exists a groupcell add the new cell to that groupcell. + groupcell->addChild( newCell ); + + // set focus and readonly stuff (from old implementation, IA) + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(false); + cursor->currentCell()->child()->setFocus(true); + } + } + else + { + cursor->currentCell()->setReadOnly(false); + cursor->currentCell()->setFocus(true); + } + } /*! * \class DeleteSelectedCellsCommand - * \author Ingemar Axelsson + * \author Ingemar Axelsson * * Deletes all selected cells. If no cell is selected the cell that * is before the cursor is deleted. @@ -462,99 +462,99 @@ namespace IAEX { try { - vector cells = document()->getSelection(); - if(cells.empty()) - { - document()->getCursor()->deleteCurrentCell(); - } - else - { - document()->clearSelection(); //Notice - - vector::iterator i = cells.begin(); - for(;i != cells.end();++i) - { - (document()->getCursor())->moveAfter((*i)); - (document()->getCursor())->deleteCurrentCell(); - } - } - - //2006-01-18 AF, set docuement changed - document()->setChanged( true ); + vector cells = document()->getSelection(); + if(cells.empty()) + { + document()->getCursor()->deleteCurrentCell(); + } + else + { + document()->clearSelection(); //Notice + + vector::iterator i = cells.begin(); + for(;i != cells.end();++i) + { + (document()->getCursor())->moveAfter((*i)); + (document()->getCursor())->deleteCurrentCell(); + } + } + + //2006-01-18 AF, set docuement changed + document()->setChanged( true ); } catch(exception &e) { - // 2006-01-30 AF, add exception - string str = string("DeleteSelectedCellsCommand(), Exception: \n") + e.what(); - throw runtime_error( str.c_str() ); + // 2006-01-30 AF, add exception + string str = string("DeleteSelectedCellsCommand(), Exception: \n") + e.what(); + throw runtime_error( str.c_str() ); } } - /*! - * \class ChangeStyleOnSelectedCellsCommand - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-10-28 (update) - * - * \brief Changes style on selected cells. - * - * This does not work on selected Cellgroups. This because I have + /*! + * \class ChangeStyleOnSelectedCellsCommand + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-10-28 (update) + * + * \brief Changes style on selected cells. + * + * This does not work on selected Cellgroups. This because I have * not defined what will happen if I change style on a * cellgroup. Probably all its children will get the same style. - * - * 2005-10-28, updated style_ from a QString object to a CellStyle - * object. Needed to do some major change of the class. /AF - * - */ - void ChangeStyleOnSelectedCellsCommand::execute() - { - try - { - vector cells = document()->getSelection(); - - if(cells.empty()) - { - document()->getCursor()->currentCell()->setStyle(style_); - } - else - {; - vector::iterator i = cells.begin(); - - for(;i != cells.end() ;++i) - { - //This makes an segfault. Do not now why? - (*i)->setStyle(style_); - } - - } - - //2006-01-18 AF, set docuement changed - document()->setChanged( true ); - } - catch(exception &e) - { - // 2006-01-30 AF, add exception - string str = string("ChangeStyleOnSelectedCellsCommand(), Exception: \n") + e.what(); - throw runtime_error( str.c_str() ); - } - } + * + * 2005-10-28, updated style_ from a QString object to a CellStyle + * object. Needed to do some major change of the class. /AF + * + */ + void ChangeStyleOnSelectedCellsCommand::execute() + { + try + { + vector cells = document()->getSelection(); + + if(cells.empty()) + { + document()->getCursor()->currentCell()->setStyle(style_); + } + else + {; + vector::iterator i = cells.begin(); + + for(;i != cells.end() ;++i) + { + //This makes an segfault. Do not now why? + (*i)->setStyle(style_); + } + + } + + //2006-01-18 AF, set docuement changed + document()->setChanged( true ); + } + catch(exception &e) + { + // 2006-01-30 AF, add exception + string str = string("ChangeStyleOnSelectedCellsCommand(), Exception: \n") + e.what(); + throw runtime_error( str.c_str() ); + } + } void ChangeStyleOnCurrentCellCommand::execute() { try { - document()->getCursor()->currentCell()->setStyle(style_); + document()->getCursor()->currentCell()->setStyle(style_); - //2006-01-18 AF, set docuement changed - document()->setChanged( true ); + //2006-01-18 AF, set docuement changed + document()->setChanged( true ); } catch(exception &e) { - // 2006-01-30 AF, add exception - string str = string("ChangeStyleOnCurrentCellCommand(), Exception: \n") + e.what(); - throw runtime_error( str.c_str() ); + // 2006-01-30 AF, add exception + string str = string("ChangeStyleOnCurrentCellCommand(), Exception: \n") + e.what(); + throw runtime_error( str.c_str() ); } } @@ -563,26 +563,26 @@ namespace IAEX { try { - Factory *fac = document()->cellFactory(); - CellCursor *cursor = document()->getCursor(); + Factory *fac = document()->cellFactory(); + CellCursor *cursor = document()->getCursor(); - Cell *prev = cursor->currentCell(); - cursor->currentCell()->parentCell()->removeChild(prev); + Cell *prev = cursor->currentCell(); + cursor->currentCell()->parentCell()->removeChild(prev); - Cell *group = fac->createCell("cellgroup", cursor->parentCell()); + Cell *group = fac->createCell("cellgroup", cursor->parentCell()); - group->addChild(prev); - cursor->addBefore(group); - cursor->moveToLastChild(group); + group->addChild(prev); + cursor->addBefore(group); + cursor->moveToLastChild(group); - //2006-01-18 AF, set docuement changed - document()->setChanged( true ); + //2006-01-18 AF, set docuement changed + document()->setChanged( true ); } catch(exception &e) { - // 2006-01-30 AF, add exception - string str = string("MakeGroupCellCommand(), Exception: \n") + e.what(); - throw runtime_error( str.c_str() ); + // 2006-01-30 AF, add exception + string str = string("MakeGroupCellCommand(), Exception: \n") + e.what(); + throw runtime_error( str.c_str() ); } } @@ -594,91 +594,91 @@ namespace IAEX * * \brief Ungroup the cell */ - void UngroupCellCommand::execute() - { - try - { - vector cells = document()->getSelection(); - - if( !cells.empty() ) - { - // clear selection before changing cell strucure - document()->clearSelection(); - - vector::iterator c_iter = cells.begin(); - for(; c_iter != cells.end() ; ++c_iter ) - { - //check if groupcell - if( typeid( *(*c_iter) ) == typeid( CellGroup )) - { - if( !(*c_iter)->hasChilds() ) - throw runtime_error( "No children" ); - - // get child - Cell* child = (*c_iter)->child(); - Cell* deletedCellsParent = (*c_iter)->parentCell(); - Cell* deletedCellsPrevious = (*c_iter)->previous(); - Cell* deletedCellsNext = (*c_iter)->next(); - - // if previous is 0 = first in cell - child->setPrevious( deletedCellsPrevious ); - if( !child->hasPrevious() ) - deletedCellsParent->setChild( child ); - else - deletedCellsPrevious->setNext( child ); - - // add all children - while( child != 0 ) - { - //child->setParent( (*c_iter)->parent() ); - child->setParentCell( deletedCellsParent ); - - if( child->hasNext() ) + void UngroupCellCommand::execute() + { + try + { + vector cells = document()->getSelection(); + + if( !cells.empty() ) + { + // clear selection before changing cell strucure + document()->clearSelection(); + + vector::iterator c_iter = cells.begin(); + for(; c_iter != cells.end() ; ++c_iter ) + { + //check if groupcell + if( typeid( *(*c_iter) ) == typeid( CellGroup )) + { + if( !(*c_iter)->hasChilds() ) + throw runtime_error( "No children" ); + + // get child + Cell* child = (*c_iter)->child(); + Cell* deletedCellsParent = (*c_iter)->parentCell(); + Cell* deletedCellsPrevious = (*c_iter)->previous(); + Cell* deletedCellsNext = (*c_iter)->next(); + + // if previous is 0 = first in cell + child->setPrevious( deletedCellsPrevious ); + if( !child->hasPrevious() ) + deletedCellsParent->setChild( child ); + else + deletedCellsPrevious->setNext( child ); + + // add all children + while( child != 0 ) + { + //child->setParent( (*c_iter)->parent() ); + child->setParentCell( deletedCellsParent ); + + if( child->hasNext() ) child = child->next(); - else - { - child->setNext( deletedCellsNext ); - if( !child->hasNext() ) - { - // update last value on all cells - Cell* current = child; - while( current != 0 ) - { - current->setLast( child ); - current = current->previous(); - } - } - else - deletedCellsNext->setPrevious( child ); - - break; - } - } - - (*c_iter)->setChild( 0 ); - (*c_iter)->hide(); - - // must update groupcells parents layout - deletedCellsParent->removeCellWidgets(); - deletedCellsParent->addCellWidgets(); - - // delete groupcell - //(document()->getCursor())->moveAfter( (*c_iter) ); - //(document()->getCursor())->deleteCurrentCell(); - delete (*c_iter); - - // update document - document()->setChanged( true ); - } - } - } - } - catch( exception &e ) - { - string str = string("UngroupCellCommand(), Exception: ") + e.what(); - throw runtime_error( str.c_str() ); - } - } + else + { + child->setNext( deletedCellsNext ); + if( !child->hasNext() ) + { + // update last value on all cells + Cell* current = child; + while( current != 0 ) + { + current->setLast( child ); + current = current->previous(); + } + } + else + deletedCellsNext->setPrevious( child ); + + break; + } + } + + (*c_iter)->setChild( 0 ); + (*c_iter)->hide(); + + // must update groupcells parents layout + deletedCellsParent->removeCellWidgets(); + deletedCellsParent->addCellWidgets(); + + // delete groupcell + //(document()->getCursor())->moveAfter( (*c_iter) ); + //(document()->getCursor())->deleteCurrentCell(); + delete (*c_iter); + + // update document + document()->setChanged( true ); + } + } + } + } + catch( exception &e ) + { + string str = string("UngroupCellCommand(), Exception: ") + e.what(); + throw runtime_error( str.c_str() ); + } + } /*! * \class SplitCellCommand @@ -687,59 +687,59 @@ namespace IAEX * * \brief Split the cell */ - void SplitCellCommand::execute() - { - try - { - if( document()->getCursor()->currentCell() ) - { - if( typeid( *document()->getCursor()->currentCell() ) == typeid( TextCell ) || - typeid( *document()->getCursor()->currentCell() ) == typeid( InputCell ) ) - { - // extraxt text - QTextEdit* editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - { - QTextCursor cursor = editor->textCursor(); - cursor.movePosition( QTextCursor::End, QTextCursor::KeepAnchor ); - QTextDocumentFragment text = cursor.selection(); - cursor.removeSelectedText(); - - // add new cell - if( typeid( *document()->getCursor()->currentCell() ) == typeid( TextCell ) ) - { - AddCellCommand addcellCommand; - addcellCommand.setApplication( application() ); - addcellCommand.setDocument( document() ); - addcellCommand.execute(); - } - else - { - // inputcell - CreateNewCellCommand newcellCommand( "Input" ); - newcellCommand.setApplication( application() ); - newcellCommand.setDocument( document() ); - newcellCommand.execute(); - } - - // add text to new cell - QTextEdit* newEditor = document()->getCursor()->currentCell()->textEdit(); - QTextCursor newCursor = newEditor->textCursor(); - newCursor.insertFragment( text ); - newCursor.movePosition( QTextCursor::Start ); - newEditor->setTextCursor( newCursor ); - - // update document - document()->setChanged( true ); - } - } - } - } - catch( exception &e ) - { - string str = string("SplitCellCommand(), Exception: ") + e.what(); - throw runtime_error( str.c_str() ); - } - } + void SplitCellCommand::execute() + { + try + { + if( document()->getCursor()->currentCell() ) + { + if( typeid( *document()->getCursor()->currentCell() ) == typeid( TextCell ) || + typeid( *document()->getCursor()->currentCell() ) == typeid( InputCell ) ) + { + // extraxt text + QTextEdit* editor = document()->getCursor()->currentCell()->textEdit(); + if( editor ) + { + QTextCursor cursor = editor->textCursor(); + cursor.movePosition( QTextCursor::End, QTextCursor::KeepAnchor ); + QTextDocumentFragment text = cursor.selection(); + cursor.removeSelectedText(); + + // add new cell + if( typeid( *document()->getCursor()->currentCell() ) == typeid( TextCell ) ) + { + AddCellCommand addcellCommand; + addcellCommand.setApplication( application() ); + addcellCommand.setDocument( document() ); + addcellCommand.execute(); + } + else + { + // inputcell + CreateNewCellCommand newcellCommand( "Input" ); + newcellCommand.setApplication( application() ); + newcellCommand.setDocument( document() ); + newcellCommand.execute(); + } + + // add text to new cell + QTextEdit* newEditor = document()->getCursor()->currentCell()->textEdit(); + QTextCursor newCursor = newEditor->textCursor(); + newCursor.insertFragment( text ); + newCursor.movePosition( QTextCursor::Start ); + newEditor->setTextCursor( newCursor ); + + // update document + document()->setChanged( true ); + } + } + } + } + catch( exception &e ) + { + string str = string("SplitCellCommand(), Exception: ") + e.what(); + throw runtime_error( str.c_str() ); + } + } }; diff --git a/OMNotebook/OMNotebookQT4/cellcommands.h b/OMNotebook/OMNotebookQT4/cellcommands.h index 89fe853bd97..3372d5f4b2a 100644 --- a/OMNotebook/OMNotebookQT4/cellcommands.h +++ b/OMNotebook/OMNotebookQT4/cellcommands.h @@ -55,131 +55,131 @@ using namespace std; namespace IAEX { - class AddCellCommand : public Command - { - public: - AddCellCommand(){} - virtual ~AddCellCommand(){} - virtual QString commandName(){ return QString("AddCellCommand");} - void execute(); - }; - - - class CreateNewCellCommand : public Command - { - public: - CreateNewCellCommand(const QString &style) : style_(style){} - virtual ~CreateNewCellCommand(){} - virtual QString commandName(){ return QString("CreateNewCellCommand");} - void execute(); - private: - QString style_; - }; - - - //\todo rename to cut command instead.o - class DeleteCurrentCellCommand : public Command - { - public: - DeleteCurrentCellCommand(){} - virtual ~DeleteCurrentCellCommand(){} - void execute(); - virtual QString commandName(){ return QString("DeleteCurrentCellCommand");} - }; - - - class PasteCellsCommand : public Command - { - public: - PasteCellsCommand(){} - virtual ~PasteCellsCommand(){} - void execute(); - QString commandName(){return QString("PasteCellsCommand");} - private: - void pasteCell( Cell *cell, CellGroup *groupcell = 0 ); - }; - - - class CopySelectedCellsCommand : public Command - { - public: - CopySelectedCellsCommand(){} - virtual ~CopySelectedCellsCommand(){} - void execute(); - QString commandName(){return QString("CopySelectedCellsCommand");} - private: - }; - - - class DeleteSelectedCellsCommand : public Command - { - public: - DeleteSelectedCellsCommand(){} - virtual ~DeleteSelectedCellsCommand(){} - void execute(); - virtual QString commandName(){ return QString("DeleteSelectedCellsCommand");} - }; - - - // Made changes to this class, see cellcommands.cpp /AF - class ChangeStyleOnSelectedCellsCommand : public Command - { - public: - ChangeStyleOnSelectedCellsCommand(CellStyle style):style_(style){} - virtual ~ChangeStyleOnSelectedCellsCommand(){} - void execute(); - virtual QString commandName(){ return QString("ChangeStyleOnSelectedCellsCommand");} - private: - CellStyle style_; - }; - - class ChangeStyleOnCurrentCellCommand : public Command - { - public: - ChangeStyleOnCurrentCellCommand(const QString &style):style_(style){} - virtual ~ChangeStyleOnCurrentCellCommand(){} - void execute(); - virtual QString commandName(){ return QString("ChangeStyleOnCurrentCellCommand");} - private: - QString style_; - }; - - /*! Makes a groupcell of current cell. Just move the cell down. - * - * \todo Create a command for converting selected cells into a - * groupcell.(Ingemar Axelsson) - * - * \todo Create commands for moving a cell.(Ingemar Axelsson) - * - * \todo Implement DRAG and DROP with cells.(Ingemar Axelsson) - */ - class MakeGroupCellCommand : public Command - { - public: - MakeGroupCellCommand(){} - virtual ~MakeGroupCellCommand(){} - void execute(); - }; - - // 2006-04-26 AF, UNGROUP - class UngroupCellCommand : public Command - { - public: - UngroupCellCommand(){} - virtual ~UngroupCellCommand(){} - virtual QString commandName(){ return QString("UngroupCellCommand");} - void execute(); - }; - - // 2006-04-26 AF, SPLIT CELL - class SplitCellCommand : public Command - { - public: - SplitCellCommand(){} - virtual ~SplitCellCommand(){} - virtual QString commandName(){ return QString("SplitCellCommand");} - void execute(); - }; + class AddCellCommand : public Command + { + public: + AddCellCommand(){} + virtual ~AddCellCommand(){} + virtual QString commandName(){ return QString("AddCellCommand");} + void execute(); + }; + + + class CreateNewCellCommand : public Command + { + public: + CreateNewCellCommand(const QString &style) : style_(style){} + virtual ~CreateNewCellCommand(){} + virtual QString commandName(){ return QString("CreateNewCellCommand");} + void execute(); + private: + QString style_; + }; + + + //\todo rename to cut command instead.o + class DeleteCurrentCellCommand : public Command + { + public: + DeleteCurrentCellCommand(){} + virtual ~DeleteCurrentCellCommand(){} + void execute(); + virtual QString commandName(){ return QString("DeleteCurrentCellCommand");} + }; + + + class PasteCellsCommand : public Command + { + public: + PasteCellsCommand(){} + virtual ~PasteCellsCommand(){} + void execute(); + QString commandName(){return QString("PasteCellsCommand");} + private: + void pasteCell( Cell *cell, CellGroup *groupcell = 0 ); + }; + + + class CopySelectedCellsCommand : public Command + { + public: + CopySelectedCellsCommand(){} + virtual ~CopySelectedCellsCommand(){} + void execute(); + QString commandName(){return QString("CopySelectedCellsCommand");} + private: + }; + + + class DeleteSelectedCellsCommand : public Command + { + public: + DeleteSelectedCellsCommand(){} + virtual ~DeleteSelectedCellsCommand(){} + void execute(); + virtual QString commandName(){ return QString("DeleteSelectedCellsCommand");} + }; + + + // Made changes to this class, see cellcommands.cpp /AF + class ChangeStyleOnSelectedCellsCommand : public Command + { + public: + ChangeStyleOnSelectedCellsCommand(CellStyle style):style_(style){} + virtual ~ChangeStyleOnSelectedCellsCommand(){} + void execute(); + virtual QString commandName(){ return QString("ChangeStyleOnSelectedCellsCommand");} + private: + CellStyle style_; + }; + + class ChangeStyleOnCurrentCellCommand : public Command + { + public: + ChangeStyleOnCurrentCellCommand(const QString &style):style_(style){} + virtual ~ChangeStyleOnCurrentCellCommand(){} + void execute(); + virtual QString commandName(){ return QString("ChangeStyleOnCurrentCellCommand");} + private: + QString style_; + }; + + /*! Makes a groupcell of current cell. Just move the cell down. + * + * \todo Create a command for converting selected cells into a + * groupcell.(Ingemar Axelsson) + * + * \todo Create commands for moving a cell.(Ingemar Axelsson) + * + * \todo Implement DRAG and DROP with cells.(Ingemar Axelsson) + */ + class MakeGroupCellCommand : public Command + { + public: + MakeGroupCellCommand(){} + virtual ~MakeGroupCellCommand(){} + void execute(); + }; + + // 2006-04-26 AF, UNGROUP + class UngroupCellCommand : public Command + { + public: + UngroupCellCommand(){} + virtual ~UngroupCellCommand(){} + virtual QString commandName(){ return QString("UngroupCellCommand");} + void execute(); + }; + + // 2006-04-26 AF, SPLIT CELL + class SplitCellCommand : public Command + { + public: + SplitCellCommand(){} + virtual ~SplitCellCommand(){} + virtual QString commandName(){ return QString("SplitCellCommand");} + void execute(); + }; }; #endif diff --git a/OMNotebook/OMNotebookQT4/cellcursor.cpp b/OMNotebook/OMNotebookQT4/cellcursor.cpp index c8d83b45a78..c4ee86d65b5 100644 --- a/OMNotebook/OMNotebookQT4/cellcursor.cpp +++ b/OMNotebook/OMNotebookQT4/cellcursor.cpp @@ -55,545 +55,545 @@ namespace IAEX { - /*! - * \class CellCursor - * - * \brief Implements a special type of cell that - * is used as a cursor within the document. - * - * The cellcursor class acts like a ordinary cell. It extends a - * cell with the functionality to move around in the celltree. See - * moveUp and moveDown members. - * - * This class should be inherited with a lot of precaution. It has - * a lot of responsibility and dependency within the - * application. So change it with caution. - * - * To change the cursors look reimplement the CursorWidget to have - * the desired look. - * - */ - - - /*! - * \author Ingemar Axelsson - * - * \brief The class constructor - */ - CellCursor::CellCursor(QWidget *parent) - : Cell(parent), - clickedOn_( false ) - { - setHeight(3); - QWidget *content = new CursorWidget(this); - - setMainWidget(content); - hideTreeView(true); - // PORT >> setBackgroundMode(Qt::PaletteBase); - setBackgroundRole( QPalette::Base ); - setBackgroundColor(QColor(100,100,100)); - - // 2006-04-27 AF, set cursor shape for cell cursor - QCursor mousecursor = cursor(); - mousecursor.setShape( Qt::SizeHorCursor ); - setCursor( mousecursor ); - } - - /*! - * \author Ingemar Axelsson - * - * \brief The class destructor - */ - CellCursor::~CellCursor() - { - - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Function for telling if the user is allowed to change - * the text settings for the text inside the cell. User isn't - * allowed to change the text settings for cellcursor so this - * function always return false. - * - * \return False - */ - bool CellCursor::isEditable() - { - return false; - } - - /*! - * \author Anders Fernström - * \date 2006-04-27 - * - * \brief Return state of the clickedOn_ property. - */ - bool CellCursor::isClickedOn() - { - return clickedOn_; - } - - /*! - * \author Anders Fernström - * \date 2006-04-27 - * - * \brief Reimplemenation of the mousePressEvent function - */ - void CellCursor::mousePressEvent(QMouseEvent *event) - { - clickedOn_ = true; - } - - /*! - * \author Anders Fernström - * \date 2006-04-27 - * - * \brief Function that should be called everytime the cursor - * is about to be moved. - */ - void CellCursor::cursorIsMoved() - { - clickedOn_ = false; - } - - - // *************************************************************** - - - - /*! - * \bug This does not work correctly. - */ - void CellCursor::accept(Visitor &v) - { - //Does not have any childs! - v.visitCellCursorNodeBefore(this); - v.visitCellCursorNodeAfter(this); - - if(hasNext()) - next()->accept(v); - } - - - void CellCursor::addBefore(Cell *newCell) - { - // 2006-04-27 AF, - cursorIsMoved(); - - if(parentCell()->child() == this) - { //first in line. - newCell->setParentCell(parentCell()); - newCell->setNext(this); - newCell->setPrevious(0); - parentCell()->setChild(newCell); - setPrevious(newCell); - } - else - { - newCell->setParentCell(parentCell()); - newCell->setPrevious(previous()); - previous()->setNext(newCell); - setPrevious(newCell); - newCell->setNext(this); - } - - parentCell()->addCellWidget(newCell); - - // TMP EMIT - emit changedPosition(); - } - - /*! \brief Replaces current cell with a new cell. - * - * \todo create a cellcopy operation. - * \todo test! - * - */ - void CellCursor::replaceCurrentWith(Cell *newCell) - { - // newCell->setParent(currentCell()->parentCell()); - // newCell->setChild(currentCell()->child()); - // newCell->setLast(currentCell()->last()); - // newCell->setPrevious(currentCell()->previous()); - // newCell->setNext(currentCell()->next()); - qDebug("replaceWithCurrent"); - - newCell->setText(currentCell()->text()); - - //Replace cell. - deleteCurrentCell(); - addBefore(newCell); - qDebug("End replaceWithCurrent"); - } - - void CellCursor::removeFromCurrentPosition() - { - //remove all widgets from parents layout. - Cell *par = parentCell(); - par->removeCellWidgets(); - - if(parentCell()->child() == this) - parentCell()->setChild(next()); - - if(parentCell()->last() == this) - parentCell()->setLast(previous()); - - if(hasNext()) - next()->setPrevious(previous()); - - if(hasPrevious()) - previous()->setNext(next()); - - //Insert all widgets again. - par->addCellWidgets(); - } - - /*! - * Removes a cell and all its subcells from the tree. - * - * This should work for all cells. But it will leave an empty - * cellgroup if last cell is deleted in cellgroup. - * - * This does not delete the cell, it just removes the cell from the - * celltree. - */ - void CellCursor::removeCurrentCell() - { - if(hasPrevious()) //If cursor has previous - { - // 2006-04-27 AF, - cursorIsMoved(); - - Cell *current = previous(); - - removeFromCurrentPosition(); - - if(current->hasPrevious()) - current->previous()->setNext(this); - else - parentCell()->setChild(this); - - setPrevious(current->previous()); - - current->setParentCell(0); - current->setPrevious(0); - current->setNext(0); - current->setChild(0); - current->setLast(0); - - current->hide(); - parentCell()->addCellWidgets(); - } - } - - /*! \bug Segfault in cellgroups. Probably a parent, child or last. - * \bug Deletion of last cell in cellgroup should be taken care of. - */ - void CellCursor::deleteCurrentCell() - { - if(hasPrevious()) //If cursor has previous - { - // 2006-04-27 AF, - cursorIsMoved(); - - //removeCurrentCell(); - - //OLD CODE - //Remove currentCell. - Cell *current = previous(); //Save a pointer to the cell being deleted. - - removeCurrentCell(); - // removeFromCurrentPosition(); - - // if(current->hasPrevious()) - // current->previous()->setNext(this); - // else - // parentCell()->setChild(this); - - // setPrevious(current->previous()); - - // current->setParentCell(0); - // current->setPrevious(0); - // current->setNext(0); - // current->setChild(0); - // current->setLast(0); - - //Segfault on delete. - delete current; - - //parentCell()->addCellWidgets(); - } - // TMP EMIT - emit changedPosition(); - } - - /*! Returns current cell. - */ - Cell *CellCursor::currentCell() - { - if(!hasPrevious()) //First in group. - return parentCell(); //Will always work. - else - return previous(); - } - - // 2006-08-24 AF, changed so the function returns a boolean value, true if - // the cursor is moved. - bool CellCursor::moveUp() - { - // 2006-08-24 AF, + /*! + * \class CellCursor + * + * \brief Implements a special type of cell that + * is used as a cursor within the document. + * + * The cellcursor class acts like a ordinary cell. It extends a + * cell with the functionality to move around in the celltree. See + * moveUp and moveDown members. + * + * This class should be inherited with a lot of precaution. It has + * a lot of responsibility and dependency within the + * application. So change it with caution. + * + * To change the cursors look reimplement the CursorWidget to have + * the desired look. + * + */ + + + /*! + * \author Ingemar Axelsson + * + * \brief The class constructor + */ + CellCursor::CellCursor(QWidget *parent) + : Cell(parent), + clickedOn_( false ) + { + setHeight(3); + QWidget *content = new CursorWidget(this); + + setMainWidget(content); + hideTreeView(true); + // PORT >> setBackgroundMode(Qt::PaletteBase); + setBackgroundRole( QPalette::Base ); + setBackgroundColor(QColor(100,100,100)); + + // 2006-04-27 AF, set cursor shape for cell cursor + QCursor mousecursor = cursor(); + mousecursor.setShape( Qt::SizeHorCursor ); + setCursor( mousecursor ); + } + + /*! + * \author Ingemar Axelsson + * + * \brief The class destructor + */ + CellCursor::~CellCursor() + { + + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Function for telling if the user is allowed to change + * the text settings for the text inside the cell. User isn't + * allowed to change the text settings for cellcursor so this + * function always return false. + * + * \return False + */ + bool CellCursor::isEditable() + { + return false; + } + + /*! + * \author Anders Fernström + * \date 2006-04-27 + * + * \brief Return state of the clickedOn_ property. + */ + bool CellCursor::isClickedOn() + { + return clickedOn_; + } + + /*! + * \author Anders Fernström + * \date 2006-04-27 + * + * \brief Reimplemenation of the mousePressEvent function + */ + void CellCursor::mousePressEvent(QMouseEvent *event) + { + clickedOn_ = true; + } + + /*! + * \author Anders Fernström + * \date 2006-04-27 + * + * \brief Function that should be called everytime the cursor + * is about to be moved. + */ + void CellCursor::cursorIsMoved() + { + clickedOn_ = false; + } + + + // *************************************************************** + + + + /*! + * \bug This does not work correctly. + */ + void CellCursor::accept(Visitor &v) + { + //Does not have any childs! + v.visitCellCursorNodeBefore(this); + v.visitCellCursorNodeAfter(this); + + if(hasNext()) + next()->accept(v); + } + + + void CellCursor::addBefore(Cell *newCell) + { + // 2006-04-27 AF, + cursorIsMoved(); + + if(parentCell()->child() == this) + { //first in line. + newCell->setParentCell(parentCell()); + newCell->setNext(this); + newCell->setPrevious(0); + parentCell()->setChild(newCell); + setPrevious(newCell); + } + else + { + newCell->setParentCell(parentCell()); + newCell->setPrevious(previous()); + previous()->setNext(newCell); + setPrevious(newCell); + newCell->setNext(this); + } + + parentCell()->addCellWidget(newCell); + + // TMP EMIT + emit changedPosition(); + } + + /*! \brief Replaces current cell with a new cell. + * + * \todo create a cellcopy operation. + * \todo test! + * + */ + void CellCursor::replaceCurrentWith(Cell *newCell) + { + // newCell->setParent(currentCell()->parentCell()); + // newCell->setChild(currentCell()->child()); + // newCell->setLast(currentCell()->last()); + // newCell->setPrevious(currentCell()->previous()); + // newCell->setNext(currentCell()->next()); + qDebug("replaceWithCurrent"); + + newCell->setText(currentCell()->text()); + + //Replace cell. + deleteCurrentCell(); + addBefore(newCell); + qDebug("End replaceWithCurrent"); + } + + void CellCursor::removeFromCurrentPosition() + { + //remove all widgets from parents layout. + Cell *par = parentCell(); + par->removeCellWidgets(); + + if(parentCell()->child() == this) + parentCell()->setChild(next()); + + if(parentCell()->last() == this) + parentCell()->setLast(previous()); + + if(hasNext()) + next()->setPrevious(previous()); + + if(hasPrevious()) + previous()->setNext(next()); + + //Insert all widgets again. + par->addCellWidgets(); + } + + /*! + * Removes a cell and all its subcells from the tree. + * + * This should work for all cells. But it will leave an empty + * cellgroup if last cell is deleted in cellgroup. + * + * This does not delete the cell, it just removes the cell from the + * celltree. + */ + void CellCursor::removeCurrentCell() + { + if(hasPrevious()) //If cursor has previous + { + // 2006-04-27 AF, + cursorIsMoved(); + + Cell *current = previous(); + + removeFromCurrentPosition(); + + if(current->hasPrevious()) + current->previous()->setNext(this); + else + parentCell()->setChild(this); + + setPrevious(current->previous()); + + current->setParentCell(0); + current->setPrevious(0); + current->setNext(0); + current->setChild(0); + current->setLast(0); + + current->hide(); + parentCell()->addCellWidgets(); + } + } + + /*! \bug Segfault in cellgroups. Probably a parent, child or last. + * \bug Deletion of last cell in cellgroup should be taken care of. + */ + void CellCursor::deleteCurrentCell() + { + if(hasPrevious()) //If cursor has previous + { + // 2006-04-27 AF, + cursorIsMoved(); + + //removeCurrentCell(); + + //OLD CODE + //Remove currentCell. + Cell *current = previous(); //Save a pointer to the cell being deleted. + + removeCurrentCell(); + // removeFromCurrentPosition(); + + // if(current->hasPrevious()) + // current->previous()->setNext(this); + // else + // parentCell()->setChild(this); + + // setPrevious(current->previous()); + + // current->setParentCell(0); + // current->setPrevious(0); + // current->setNext(0); + // current->setChild(0); + // current->setLast(0); + + //Segfault on delete. + delete current; + + //parentCell()->addCellWidgets(); + } + // TMP EMIT + emit changedPosition(); + } + + /*! Returns current cell. + */ + Cell *CellCursor::currentCell() + { + if(!hasPrevious()) //First in group. + return parentCell(); //Will always work. + else + return previous(); + } + + // 2006-08-24 AF, changed so the function returns a boolean value, true if + // the cursor is moved. + bool CellCursor::moveUp() + { + // 2006-08-24 AF, bool moved( false ); - // 2006-04-27 AF, - cursorIsMoved(); - - if( !hasPrevious() ) - { - if( parentCell()->hasParentCell() ) - { - moveBefore( parentCell() ); - moved = true; - } - } - else - { - //previous() exists. - if(previous()->hasChilds()) - { - if(!previous()->isClosed()) - { - moveToLastChild(previous()); - moved = true; - } - else - { - moveBefore(previous()); - moved = true; - } - } - else - { - moveBefore(previous()); - moved = true; - } - } - emit positionChanged(x(), y(), 5,5); - - // TMP EMIT - emit changedPosition(); - return moved; - } - - /*! - * \bug Segmentationfault when last cell. - * - * \todo It is better that Commands take care of how to change - * state of cells.(Ingemar Axelsson) - * - * 2006-08-24 AF, changed so the function returns a boolean value, true if - * the cursor is moved. - */ - bool CellCursor::moveDown() - { - // 2006-08-24 AF, + // 2006-04-27 AF, + cursorIsMoved(); + + if( !hasPrevious() ) + { + if( parentCell()->hasParentCell() ) + { + moveBefore( parentCell() ); + moved = true; + } + } + else + { + //previous() exists. + if(previous()->hasChilds()) + { + if(!previous()->isClosed()) + { + moveToLastChild(previous()); + moved = true; + } + else + { + moveBefore(previous()); + moved = true; + } + } + else + { + moveBefore(previous()); + moved = true; + } + } + emit positionChanged(x(), y(), 5,5); + + // TMP EMIT + emit changedPosition(); + return moved; + } + + /*! + * \bug Segmentationfault when last cell. + * + * \todo It is better that Commands take care of how to change + * state of cells.(Ingemar Axelsson) + * + * 2006-08-24 AF, changed so the function returns a boolean value, true if + * the cursor is moved. + */ + bool CellCursor::moveDown() + { + // 2006-08-24 AF, bool moved( false ); - // 2006-04-27 AF, - cursorIsMoved(); - - if( !hasNext() ) - { - if( parentCell()->hasParentCell() ) - { - moveAfter( parentCell() ); - moved = true; - } - } - else //Has next. - { - if(next()->hasChilds()) - { - if(!next()->isClosed()) - { - moveToFirstChild(next()); - moved = true; - } - else - { - moveAfter(next()); - moved = true; - } - } - else - { - moveAfter(next()); - moved = true; - } - } - // TMP EMIT - emit changedPosition(); - emit positionChanged(x(), y(), 5,5); - return moved; - } - - /*! Insert this cell as first child of parent. - * - * \bug This does not seem to work correctly. - */ - void CellCursor::moveToFirstChild(Cell *parent) - { - // 2006-04-27 AF, - cursorIsMoved(); - - if(parent->hasChilds()) - { - parent->removeCellWidgets(); - moveBefore(parent->child()); - parent->addCellWidgets(); - } - else //No child. - { - //Become first child. - parent->removeCellWidgets(); - parent->setChild(this); - parent->setLast(this); - parent->addCellWidgets(); - } - - // TMP EMIT - emit changedPosition(); - } - - /*! - * \bug This does not seem to work correctly. - */ - void CellCursor::moveToLastChild(Cell *parent) - { - // 2006-04-27 AF, - cursorIsMoved(); - - if(parent->hasChilds()) - { - parent->removeCellWidgets(); - moveAfter(parent->last()); - parent->addCellWidgets(); - } - else - { - throw runtime_error("LAST CHILD: Tried to move to a child that did not exist."); - } - - // TMP EMIT - emit changedPosition(); - } - - /*! - * \bug Fel vid flytt så cursor hamnar som sista barn. - */ - void CellCursor::moveAfter(Cell *current) - { - // 2006-04-27 AF, - cursorIsMoved(); - - removeFromCurrentPosition(); - - //if(!current->hasParentCell()) - // throw runtime_error("Could not insert after root"); - - if(current->hasParentCell()) - { - current->parentCell()->removeCellWidgets(); - - if(current->hasNext() == 0) - { - current->parentCell()->setLast(this); - } - else - current->next()->setPrevious(this); - - setParentCell(current->parentCell()); - setNext(current->next()); - current->setNext(this); - setPrevious(current); - - //insert widgets to parents layout. - parentCell()->addCellWidgets(); - } - else - { - //If current does not have a parent. That is current is not - //in the celltree at all or that current is the root of the - //tree. It should not be possible to move after the root of - //the tree. Do nothing! - } - - // TMP EMIT - emit changedPosition(); - // emit positionChanged(x(), y(), 5,5); - } - - - /* - * \bug fel om vi flyttas till att vara första barn.. - */ - void CellCursor::moveBefore(Cell *current) - { - // 2006-04-27 AF, - cursorIsMoved(); - - removeFromCurrentPosition(); - - //Remove all widgets from currents parent. - current->parentCell()->removeCellWidgets(); - - //Move to new position. - if(current->hasParentCell()) - { - setParentCell(current->parentCell()); - if(!current->hasPrevious()) - current->parentCell()->setChild(this); - else - current->previous()->setNext(this); - - } - else - throw runtime_error("Could not insert before root"); - - setPrevious(current->previous()); - current->setPrevious(this); - setNext(current); - - //Insert widgets to parents layout. - parentCell()->addCellWidgets(); - - // TMP EMIT - emit changedPosition(); - // emit positionChanged(x(), y(), 5, 5); - } - - - /*! \class CursorWidget - * - * \brief CursorWidget describes how the cursor should be painted. - */ - void CursorWidget::paintEvent(QPaintEvent *event) - { - QPainter painter(this); - - QPalette palette; - palette.setColor(this->backgroundRole(), QColor(0,0,0)); - this->setPalette(palette); - - // changed from 1 to 3, don\t know way, but something must have - // changed between qt 4 and qt 4.1 - painter.setPen(QPen(black,3, SolidLine)); - - - - painter.drawRect(0, 0, width(), height()); - QWidget::paintEvent(event); - } + // 2006-04-27 AF, + cursorIsMoved(); + + if( !hasNext() ) + { + if( parentCell()->hasParentCell() ) + { + moveAfter( parentCell() ); + moved = true; + } + } + else //Has next. + { + if(next()->hasChilds()) + { + if(!next()->isClosed()) + { + moveToFirstChild(next()); + moved = true; + } + else + { + moveAfter(next()); + moved = true; + } + } + else + { + moveAfter(next()); + moved = true; + } + } + // TMP EMIT + emit changedPosition(); + emit positionChanged(x(), y(), 5,5); + return moved; + } + + /*! Insert this cell as first child of parent. + * + * \bug This does not seem to work correctly. + */ + void CellCursor::moveToFirstChild(Cell *parent) + { + // 2006-04-27 AF, + cursorIsMoved(); + + if(parent->hasChilds()) + { + parent->removeCellWidgets(); + moveBefore(parent->child()); + parent->addCellWidgets(); + } + else //No child. + { + //Become first child. + parent->removeCellWidgets(); + parent->setChild(this); + parent->setLast(this); + parent->addCellWidgets(); + } + + // TMP EMIT + emit changedPosition(); + } + + /*! + * \bug This does not seem to work correctly. + */ + void CellCursor::moveToLastChild(Cell *parent) + { + // 2006-04-27 AF, + cursorIsMoved(); + + if(parent->hasChilds()) + { + parent->removeCellWidgets(); + moveAfter(parent->last()); + parent->addCellWidgets(); + } + else + { + throw runtime_error("LAST CHILD: Tried to move to a child that did not exist."); + } + + // TMP EMIT + emit changedPosition(); + } + + /*! + * \bug Fel vid flytt så cursor hamnar som sista barn. + */ + void CellCursor::moveAfter(Cell *current) + { + // 2006-04-27 AF, + cursorIsMoved(); + + removeFromCurrentPosition(); + + //if(!current->hasParentCell()) + // throw runtime_error("Could not insert after root"); + + if(current->hasParentCell()) + { + current->parentCell()->removeCellWidgets(); + + if(current->hasNext() == 0) + { + current->parentCell()->setLast(this); + } + else + current->next()->setPrevious(this); + + setParentCell(current->parentCell()); + setNext(current->next()); + current->setNext(this); + setPrevious(current); + + //insert widgets to parents layout. + parentCell()->addCellWidgets(); + } + else + { + //If current does not have a parent. That is current is not + //in the celltree at all or that current is the root of the + //tree. It should not be possible to move after the root of + //the tree. Do nothing! + } + + // TMP EMIT + emit changedPosition(); + // emit positionChanged(x(), y(), 5,5); + } + + + /* + * \bug fel om vi flyttas till att vara första barn.. + */ + void CellCursor::moveBefore(Cell *current) + { + // 2006-04-27 AF, + cursorIsMoved(); + + removeFromCurrentPosition(); + + //Remove all widgets from currents parent. + current->parentCell()->removeCellWidgets(); + + //Move to new position. + if(current->hasParentCell()) + { + setParentCell(current->parentCell()); + if(!current->hasPrevious()) + current->parentCell()->setChild(this); + else + current->previous()->setNext(this); + + } + else + throw runtime_error("Could not insert before root"); + + setPrevious(current->previous()); + current->setPrevious(this); + setNext(current); + + //Insert widgets to parents layout. + parentCell()->addCellWidgets(); + + // TMP EMIT + emit changedPosition(); + // emit positionChanged(x(), y(), 5, 5); + } + + + /*! \class CursorWidget + * + * \brief CursorWidget describes how the cursor should be painted. + */ + void CursorWidget::paintEvent(QPaintEvent *event) + { + QPainter painter(this); + + QPalette palette; + palette.setColor(this->backgroundRole(), QColor(0,0,0)); + this->setPalette(palette); + + // changed from 1 to 3, don\t know way, but something must have + // changed between qt 4 and qt 4.1 + painter.setPen(QPen(black,3, SolidLine)); + + + + painter.drawRect(0, 0, width(), height()); + QWidget::paintEvent(event); + } } diff --git a/OMNotebook/OMNotebookQT4/cellcursor.h b/OMNotebook/OMNotebookQT4/cellcursor.h index 9e56e2a06b4..cb12083ad99 100644 --- a/OMNotebook/OMNotebookQT4/cellcursor.h +++ b/OMNotebook/OMNotebookQT4/cellcursor.h @@ -49,67 +49,67 @@ class QPaintEvent; namespace IAEX { - class CellCursor : public Cell - { - Q_OBJECT + class CellCursor : public Cell + { + Q_OBJECT - public: - CellCursor(QWidget *parent=0); - virtual ~CellCursor(); + public: + CellCursor(QWidget *parent=0); + virtual ~CellCursor(); - //Insertion - void addBefore(Cell *newCell); - void deleteCurrentCell(); - void removeCurrentCell(); - void replaceCurrentWith(Cell *newCell); + //Insertion + void addBefore(Cell *newCell); + void deleteCurrentCell(); + void removeCurrentCell(); + void replaceCurrentWith(Cell *newCell); - Cell *currentCell(); + Cell *currentCell(); - //Movment - bool moveUp(); // Changed 2006-08-24 AF - bool moveDown(); // Changed 2006-08-24 AF + //Movment + bool moveUp(); // Changed 2006-08-24 AF + bool moveDown(); // Changed 2006-08-24 AF - void moveToFirstChild(Cell *parent); - void moveToLastChild(Cell *parent); - void moveBefore(Cell *current); - void moveAfter(Cell *current); + void moveToFirstChild(Cell *parent); + void moveToLastChild(Cell *parent); + void moveBefore(Cell *current); + void moveAfter(Cell *current); - virtual void accept(Visitor &v); - virtual QString text(){return QString::null;} + virtual void accept(Visitor &v); + virtual QString text(){return QString::null;} - //Flag - bool isEditable(); // Added 2005-10-28 AF - bool isClickedOn(); // Added 2006-04-27 AF + //Flag + bool isEditable(); // Added 2005-10-28 AF + bool isClickedOn(); // Added 2006-04-27 AF - public slots: - virtual void setFocus(const bool){} + public slots: + virtual void setFocus(const bool){} - signals: - void changedPosition(); - void positionChanged(int x, int y, int xm, int ym); + signals: + void changedPosition(); + void positionChanged(int x, int y, int xm, int ym); - protected: - void mousePressEvent(QMouseEvent *event); // Added 2006-04-27 AF + protected: + void mousePressEvent(QMouseEvent *event); // Added 2006-04-27 AF - private: - void cursorIsMoved(); // Added 2006-04-27 AF - void removeFromCurrentPosition(); + private: + void cursorIsMoved(); // Added 2006-04-27 AF + void removeFromCurrentPosition(); - private: - bool clickedOn_; + private: + bool clickedOn_; - }; + }; - class CursorWidget : public QWidget - { - public: - CursorWidget(QWidget *parent=0) - :QWidget(parent){} - virtual ~CursorWidget(){} + class CursorWidget : public QWidget + { + public: + CursorWidget(QWidget *parent=0) + :QWidget(parent){} + virtual ~CursorWidget(){} - protected: - void paintEvent(QPaintEvent *event); - }; + protected: + void paintEvent(QPaintEvent *event); + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/celldocument.cpp b/OMNotebook/OMNotebookQT4/celldocument.cpp index d455c231d21..a27a99434ac 100644 --- a/OMNotebook/OMNotebookQT4/celldocument.cpp +++ b/OMNotebook/OMNotebookQT4/celldocument.cpp @@ -73,1360 +73,1360 @@ namespace IAEX { - /*! - * \class CellDocument - * \author Ingemar Axelsson and Anders Fernström - * - * \brief Main widget for the cell workspace. - * - * This class represents the mainwidget for the application. It has - * functionality to open files and create cells from them. It also - * knows which cells that are selected. - * - * CellDocument acts like a mediator between the application and all - * cells. It knows how to do stuff with cells. - * - * The CellDocument does not have any menu. So to use menus for - * doing stuff with the application look at the slots that exists in - * this class. - * - * For more information about how to use this widget in an application - * look at the documentation for every signal and slot in this class. - * - * - * \todo Implement an interface for applications. Also sort the - * includes in a better way. So developers does not have to include a - * lot of strange headerfiles. Just one headerfile should be enough.(Ingemar Axelsson) - * - * \todo Implement functionality for dragging cells around.(Ingemar Axelsson) - * - * \todo Make it possible to change celltype. From textcell to - * inputcell for example. Inputcell should only be a decorator of a - * textcell.(Ingemar Axelsson) - * - * - * \bug When opening a second file, some connections is missing. - * - * \bug Closing a document does not work correctly. - */ - - - /*! - * \author Ingemar Axelsson (and Anders Fernström) - * \date 2005-11-28 (update) - * - * \brief Constructor, initialize a CellGroup as maincontent. - * - * 2005-11-28 AF, added connection between 'cursorChanged()' - * and 'updateScrollArea()' - * - * \todo Remove the dependency of QFrame from document.(Ingemar Axelsson) - */ - CellDocument::CellDocument( CellApplication *a, const QString filename, - int readmode ) - : changed_(false), - open_(false), - saved_(false), - app_(a), - currentImageNo_(0), - lastClickedCell_(0) - { + /*! + * \class CellDocument + * \author Ingemar Axelsson and Anders Fernström + * + * \brief Main widget for the cell workspace. + * + * This class represents the mainwidget for the application. It has + * functionality to open files and create cells from them. It also + * knows which cells that are selected. + * + * CellDocument acts like a mediator between the application and all + * cells. It knows how to do stuff with cells. + * + * The CellDocument does not have any menu. So to use menus for + * doing stuff with the application look at the slots that exists in + * this class. + * + * For more information about how to use this widget in an application + * look at the documentation for every signal and slot in this class. + * + * + * \todo Implement an interface for applications. Also sort the + * includes in a better way. So developers does not have to include a + * lot of strange headerfiles. Just one headerfile should be enough.(Ingemar Axelsson) + * + * \todo Implement functionality for dragging cells around.(Ingemar Axelsson) + * + * \todo Make it possible to change celltype. From textcell to + * inputcell for example. Inputcell should only be a decorator of a + * textcell.(Ingemar Axelsson) + * + * + * \bug When opening a second file, some connections is missing. + * + * \bug Closing a document does not work correctly. + */ + + + /*! + * \author Ingemar Axelsson (and Anders Fernström) + * \date 2005-11-28 (update) + * + * \brief Constructor, initialize a CellGroup as maincontent. + * + * 2005-11-28 AF, added connection between 'cursorChanged()' + * and 'updateScrollArea()' + * + * \todo Remove the dependency of QFrame from document.(Ingemar Axelsson) + */ + CellDocument::CellDocument( CellApplication *a, const QString filename, + int readmode ) + : changed_(false), + open_(false), + saved_(false), + app_(a), + currentImageNo_(0), + lastClickedCell_(0) + { filename_ = filename; //Initialize SoQT mainFrame_ = new QFrame(a->getMainWindow()); - mainFrame_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Expanding)); - - mainLayout_ = new QGridLayout(mainFrame_); - mainLayout_->setMargin(0); - mainLayout_->setSpacing(0); - - //Initialize workspace. - factory_ = new CellFactory(this); - setWorkspace(factory_->createCell("cellgroup")); - - // 2005-11-28 AF - connect( this, SIGNAL( cursorChanged() ), - this, SLOT( updateScrollArea() )); - - // 2005-12-01 AF, Added try-catch - try - { - if(filename_ != QString::null) - open( filename_, readmode ); - } - catch( exception &e ) - { - throw e; - } - - -// open_ = true; // 2005-09-26 AF, not sure if this should be here //070903 HE, probably not - } - - /*! - * \author Ingemar Axelsson - * - * \brief The class destructor - */ - CellDocument::~CellDocument() - { - delete scroll_; - delete mainLayout_; - //delete workspace_; - delete mainFrame_; - delete factory_; - - // 2006-01-16 AF (update), remove all images in memory and add - // the temporary images to removelist in the main applicaiton - QHash::iterator i_iter = images_.begin(); - while( i_iter != images_.end() ) - { - // add temporary images to removelist - application()->removeTempFiles( i_iter.key() ); - - // delete image - delete i_iter.value(); - ++i_iter; - } - } - - - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-12-01 (update) - * - * \brief Open an file and parse the content - * - * 2005-09-22 AF, Added open_ variable - * 2005-10-02 AF, Added saved_ variable - * 2005-12-01 AF, Added try-catch - */ - void CellDocument::open( const QString filename, int readmode ) - { - filename_ = filename; - - ParserFactory *parserFactory = new CellParserFactory(); - NBParser *parser = parserFactory->createParser(filename_, factory_, this, readmode); - - // 2005-12-01 AF, Added try-catch - try - { - Cell *cell = parser->parse(); - setWorkspace( cell ); - } - catch( exception e ) - { - delete parserFactory; - delete parser; - throw e; - } - - - //Delete the parser after it is used. - delete parserFactory; - delete parser; - - // 2005-09-22 AF, Added this... - open_ = true; - - // 2005-11-02 AF, set saved_ to true if the loaded file is .onb - if( 0 < filename_.indexOf( ".onb", 0, Qt::CaseInsensitive ) ) - saved_ = true; - else - saved_ = false; - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-10-28 (update) - * - * \brief Change the style of the selected cell/cells - */ - void CellDocument::cursorChangeStyle(CellStyle style) - { - //Invoke style changes to all selected cells. - executeCommand(new ChangeStyleOnSelectedCellsCommand(style)); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-11-01 (update) - * - * \brief Attach a CellGroup to be the main workspace for cells. - * - * Connects a cellgroup to the scrollview. Does some reparent stuff - * also so all subcells will be drawn. This must be done every time - * this member is changed. - * - * 2005-11-01 AF, replaced the old Q3ScrollView with the new - * QScrollArea and needed to change/update some thing in this - * function; - * - * \param newWorkspace A pointer to the CellGroup that will be seen as - * the main cellworkspace in the application. - * - * - * \todo The old workspace must be deleted!(Ingemar Axelsson) - */ - void CellDocument::setWorkspace(Cell *newWorkspace) - { - scroll_ = new QScrollArea( mainFrame_ ); - scroll_->setWidgetResizable( true ); - scroll_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - scroll_->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded ); - - mainLayout_->addWidget(scroll_, 1, 1); - - workspace_ = newWorkspace; - - // PORT >> workspace_->reparent(scroll_->viewport(), QPoint(0,0), true); - //workspace_->setParent( scroll_->viewport() ); - //workspace_->move( QPoint(0,0) ); - //workspace_->show(); - - scroll_->setWidget( workspace_ ); - - //?? Should this be done by the factory? - current_ = dynamic_cast(factory_->createCell("cursor", workspace_)); - - - //Make the cursor visible at all time. - //QObject::connect(current_, SIGNAL(positionChanged(int, int, int, int)), - // vp_, SLOT(ensureVisible(int, int, int, int))); - - workspace_->addChild( current_ ); - - //To hide the outhermost treeview. - workspace_->hideTreeView( true ); - workspace_->show(); - } - - /*! - * \author Ingemar Axelsson - */ - void CellDocument::cursorStepUp() - { - executeCommand(new CursorMoveUpCommand()); - emit cursorChanged(); - } - - /*! - * \author Ingemar Axelsson - */ - void CellDocument::cursorStepDown() - { - executeCommand(new CursorMoveDownCommand()); - emit cursorChanged(); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-10-03 (update) - * - * 2005-10-03 AF, addad the try-catch expression - */ - void CellDocument::cursorAddCell() - { - try - { - executeCommand(new AddCellCommand()); - open_ = true; - emit cursorChanged(); - } - catch( exception &e ) - { - throw e; - } - } - - /*! - * \author Anders Fernström - * \date 2006-04-26 - * - * \brief Ungroup all selected groupcells - */ - void CellDocument::cursorUngroupCell() - { - try - { - executeCommand( new UngroupCellCommand() ); - emit cursorChanged(); - } - catch( exception &e ) - { - throw e; - } - } - - /*! - * \author Anders Fernström - * \date 2006-04-26 - * - * \brief Split current cell - */ - void CellDocument::cursorSplitCell() - { - try - { - executeCommand( new SplitCellCommand() ); - emit cursorChanged(); - } - catch( exception &e ) - { - throw e; - } - } - - /*! - * \author Ingemar Axelsson - */ - void CellDocument::cursorDeleteCell() - { - executeCommand(new DeleteSelectedCellsCommand()); - qDebug("cursorDeleteCell"); - - //emit cursorChanged(); //This causes an untracable segfault. - - qDebug("Finished"); - } - - /*! - * \author Ingemar Axelsson - * - * \bug Notice that it does not work on selected cells. - */ - void CellDocument::cursorCutCell() - { - executeCommand(new DeleteCurrentCellCommand()); - } - - /*! - * \author Ingemar Axelsson - */ - void CellDocument::cursorCopyCell() - { - executeCommand(new CopySelectedCellsCommand()); - } - - /*! - * \author Ingemar Axelsson - */ - void CellDocument::cursorPasteCell() - { - executeCommand(new PasteCellsCommand()); - } - - /*! - * \author Ingemar Axelsson - */ - void CellDocument::cursorMoveAfter(Cell *aCell, const bool open) - { - //if(!open) - executeCommand(new CursorMoveAfterCommand(aCell)); - // else - // { - // if(aCell->hasChilds()) - // executeCommand(new CursorMoveAfterCommand(aCell->child())); - // else - // executeCommand(new CursorMoveAfterCommand(aCell)); - // } - - emit cursorChanged(); - } - - /*! - * \author Anders Fernström - * \date 2006-02-07 - * - * \brief Cut text - */ - void CellDocument::textcursorCutText() - { - executeCommand( new TextCursorCutText() ); - } - - /*! - * \author Anders Fernström - * \date 2006-02-07 - * - * \brief Copy text - */ - void CellDocument::textcursorCopyText() - { - executeCommand( new TextCursorCopyText() ); - } - - /*! - * \author Anders Fernström - * \date 2006-02-07 - * - * \brief Paste text - */ - void CellDocument::textcursorPasteText() - { - executeCommand( new TextCursorPasteText() ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the font family on the selected text, if - * no text selected the current font family will be changed. - * - * \param family The new font family - */ - void CellDocument::textcursorChangeFontFamily(QString family) - { - executeCommand( new TextCursorChangeFontFamily(family) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the font weight on the selected text, if - * no text selected the current font weight will be changed. - * - * \param weight The new font weight - */ - void CellDocument::textcursorChangeFontFace(int face) - { - executeCommand( new TextCursorChangeFontFace(face) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the font size on the selected text, if - * no text selected the current font size will be changed. - * - * \param size The new font size - */ - void CellDocument::textcursorChangeFontSize(int size) - { - executeCommand( new TextCursorChangeFontSize(size) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the font stretch on the selected text, if - * no text selected the current font stretch will be changed. - * - * \param stretch The new font stretch - */ - void CellDocument::textcursorChangeFontStretch(int stretch) - { - executeCommand( new TextCursorChangeFontStretch(stretch) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the font color on the selected text, if - * no text selected the current font color will be changed. - * - * \param color The new font color - */ - void CellDocument::textcursorChangeFontColor(QColor color) - { - executeCommand( new TextCursorChangeFontColor(color) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the text alignment on the text inside the cell - * - * \param alignment The new text alignment - */ - void CellDocument::textcursorChangeTextAlignment(int alignment) - { - executeCommand( new TextCursorChangeTextAlignment(alignment) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the vertical alignment on the selected text, if - * no text selected the current vertical alignment will be changed. - * - * \param color The new vertical alignment - */ - void CellDocument::textcursorChangeVerticalAlignment(int alignment) - { - executeCommand( new TextCursorChangeVerticalAlignment(alignment) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the margin of the cell - * - * \param margin The new maring - */ - void CellDocument::textcursorChangeMargin(int margin) - { - executeCommand( new TextCursorChangeMargin(margin) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the padding of the cell - * - * \param padding The new padding - */ - void CellDocument::textcursorChangePadding(int padding) - { - executeCommand( new TextCursorChangePadding(padding) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Change the border of the cell - * - * \param border The new border - */ - void CellDocument::textcursorChangeBorder(int border) - { - executeCommand( new TextCursorChangeBorder(border) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-18 - * - * \brief Insert a image into the selected cell - * - * \param filepath The path to the image - */ - void CellDocument::textcursorInsertImage(QString filepath, QSize size) - { - executeCommand( new TextCursorInsertImage(filepath, size) ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-18 - * \date 2006-02-13 (update) - * - * \brief Add image to the document - * - * The function first check for an availible name for the image, - * then saves the image temporary to the harddirve and returns - * the name of the file. - * - * 2005-12-12 AF, Added 'file:///(path)/' to very image name - * 2006-02-13 AF, All images are added in the sub dir - * 'OMNotebook_tempfiles'. - * - * \param image A pointer to the images that should be added - * \return the filename of the saved image - */ - QString CellDocument::addImage(QImage *image) - { - // first find a correct temp filename - QDir dir; - - // 2006-02-13 AF, store images in temp dir - dir.setPath( dir.absolutePath() + "/OMNotebook_tempfiles" ); - - QString name; - while( true ) - { - currentImageNo_++; - name.setNum( currentImageNo_ ); - name += ".png"; - if( !dir.exists( name )) - break; - } - - name = dir.absolutePath() + "/" + name; - - // save the image temporary to the harddrive - QImageWriter writer( name, "png" ); - writer.setDescription( "Temporary OMNotebook image" ); - writer.setQuality( 100 ); - writer.write( *image ); - - images_[ name ] = image; - - // 2005-12-12 AF, Add file:/// to filename - name = QString("file:///") + name; - - // return the imagename - return name; - } - - /*! - * \author Anders Fernström - * \date 2005-11-20 - * \date 2005-12-12 (update) - * - * \brief Returns the image with the specified name - * - * 2005-12-12 AF, remove 'file:///' from name - * - * \param name Name of the image - * \return a pointer to the image - */ - QImage *CellDocument::getImage(QString name) - { - name.remove( "file:///" ); - - QImage *image; - - if( images_.contains( name )) - image = images_[name]; - else - { - cout << "Could not find image: " << name.toStdString() << endl; - image = new QImage(); - } - - return image; - } - - /*! - * \author Anders Fernström - * \date 2005-12-05 - * - * \brief Insert a link to the selected text - * - * \param filepath The linkpath to another docuement - */ - void CellDocument::textcursorInsertLink( QString filepath, QTextCursor& cursor ) - { - executeCommand( new TextCursorInsertLink( filepath, cursor )); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - */ - bool CellDocument::hasChanged() const - { - return changed_; - } - - /*! - * \author Ingemar Axelsson - */ - bool CellDocument::isOpen() const - { - return open_; - } - - /*! - * \author Anders Fernström - */ - bool CellDocument::isSaved() const - { - return saved_; - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Return true if the document is empty, otherwise false - */ - bool CellDocument::isEmpty() const - { - bool empty( false ); - if( workspace_ ) - { - if( workspace_->hasChilds() ) - { - Cell* cell = workspace_->child(); - if( cell ) - { - if( !cell->hasNext() ) - if( typeid( (*cell) ) == typeid( CellCursor )) - empty = true; - } - else - empty = true; - } - else - empty = true; - } - else - empty = true; - - return empty; - } - - /*! - * \author Anders Fernström - * \date 2005-11-29 - * \date 2006-03-03 (update) - * - * \brief Update the scrollarea so the correct area is displayed - * - * 2005-12-08 AF, remade function becuase the earlier version hade - * some large bugs. Didn't calculate cells position correct, becuase - * qt:s layout system reset position to 0 in every groupcell and - * layout are probobly not set correctly. - * 2006-03-03 AF, ignore move if the cursor it at the end of the - * document - */ - void CellDocument::updateScrollArea() - { - if( scroll_->verticalScrollBar()->isVisible() ) - { - CellCursor *cursor = getCursor(); - if( cursor ) - { - // ignore, if selected cell is a groupcell - if( typeid( *cursor->currentCell() ) != typeid( CellGroup ) ) - { - // calculate the position of the cursor, by adding the height - // of all the cells before the cellcursor, using a visitor - CursorPosVisitor visitor; - runVisitor( visitor ); - int pos = visitor.position(); - - // size of scrollarea - int scrollTop = scroll_->widget()->visibleRegion().boundingRect().top(); - int scrollBottom = scroll_->widget()->visibleRegion().boundingRect().bottom(); - - // cell height - int height = cursor->currentCell()->height(); + mainFrame_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, + QSizePolicy::Expanding)); + + mainLayout_ = new QGridLayout(mainFrame_); + mainLayout_->setMargin(0); + mainLayout_->setSpacing(0); + + //Initialize workspace. + factory_ = new CellFactory(this); + setWorkspace(factory_->createCell("cellgroup")); + + // 2005-11-28 AF + connect( this, SIGNAL( cursorChanged() ), + this, SLOT( updateScrollArea() )); + + // 2005-12-01 AF, Added try-catch + try + { + if(filename_ != QString::null) + open( filename_, readmode ); + } + catch( exception &e ) + { + throw e; + } + + +// open_ = true; // 2005-09-26 AF, not sure if this should be here //070903 HE, probably not + } + + /*! + * \author Ingemar Axelsson + * + * \brief The class destructor + */ + CellDocument::~CellDocument() + { + delete scroll_; + delete mainLayout_; + //delete workspace_; + delete mainFrame_; + delete factory_; + + // 2006-01-16 AF (update), remove all images in memory and add + // the temporary images to removelist in the main applicaiton + QHash::iterator i_iter = images_.begin(); + while( i_iter != images_.end() ) + { + // add temporary images to removelist + application()->removeTempFiles( i_iter.key() ); + + // delete image + delete i_iter.value(); + ++i_iter; + } + } + + + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-12-01 (update) + * + * \brief Open an file and parse the content + * + * 2005-09-22 AF, Added open_ variable + * 2005-10-02 AF, Added saved_ variable + * 2005-12-01 AF, Added try-catch + */ + void CellDocument::open( const QString filename, int readmode ) + { + filename_ = filename; + + ParserFactory *parserFactory = new CellParserFactory(); + NBParser *parser = parserFactory->createParser(filename_, factory_, this, readmode); + + // 2005-12-01 AF, Added try-catch + try + { + Cell *cell = parser->parse(); + setWorkspace( cell ); + } + catch( exception e ) + { + delete parserFactory; + delete parser; + throw e; + } + + + //Delete the parser after it is used. + delete parserFactory; + delete parser; + + // 2005-09-22 AF, Added this... + open_ = true; + + // 2005-11-02 AF, set saved_ to true if the loaded file is .onb + if( 0 < filename_.indexOf( ".onb", 0, Qt::CaseInsensitive ) ) + saved_ = true; + else + saved_ = false; + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-10-28 (update) + * + * \brief Change the style of the selected cell/cells + */ + void CellDocument::cursorChangeStyle(CellStyle style) + { + //Invoke style changes to all selected cells. + executeCommand(new ChangeStyleOnSelectedCellsCommand(style)); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-11-01 (update) + * + * \brief Attach a CellGroup to be the main workspace for cells. + * + * Connects a cellgroup to the scrollview. Does some reparent stuff + * also so all subcells will be drawn. This must be done every time + * this member is changed. + * + * 2005-11-01 AF, replaced the old Q3ScrollView with the new + * QScrollArea and needed to change/update some thing in this + * function; + * + * \param newWorkspace A pointer to the CellGroup that will be seen as + * the main cellworkspace in the application. + * + * + * \todo The old workspace must be deleted!(Ingemar Axelsson) + */ + void CellDocument::setWorkspace(Cell *newWorkspace) + { + scroll_ = new QScrollArea( mainFrame_ ); + scroll_->setWidgetResizable( true ); + scroll_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + scroll_->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded ); + + mainLayout_->addWidget(scroll_, 1, 1); + + workspace_ = newWorkspace; + + // PORT >> workspace_->reparent(scroll_->viewport(), QPoint(0,0), true); + //workspace_->setParent( scroll_->viewport() ); + //workspace_->move( QPoint(0,0) ); + //workspace_->show(); + + scroll_->setWidget( workspace_ ); + + //?? Should this be done by the factory? + current_ = dynamic_cast(factory_->createCell("cursor", workspace_)); + + + //Make the cursor visible at all time. + //QObject::connect(current_, SIGNAL(positionChanged(int, int, int, int)), + // vp_, SLOT(ensureVisible(int, int, int, int))); + + workspace_->addChild( current_ ); + + //To hide the outhermost treeview. + workspace_->hideTreeView( true ); + workspace_->show(); + } + + /*! + * \author Ingemar Axelsson + */ + void CellDocument::cursorStepUp() + { + executeCommand(new CursorMoveUpCommand()); + emit cursorChanged(); + } + + /*! + * \author Ingemar Axelsson + */ + void CellDocument::cursorStepDown() + { + executeCommand(new CursorMoveDownCommand()); + emit cursorChanged(); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-10-03 (update) + * + * 2005-10-03 AF, addad the try-catch expression + */ + void CellDocument::cursorAddCell() + { + try + { + executeCommand(new AddCellCommand()); + open_ = true; + emit cursorChanged(); + } + catch( exception &e ) + { + throw e; + } + } + + /*! + * \author Anders Fernström + * \date 2006-04-26 + * + * \brief Ungroup all selected groupcells + */ + void CellDocument::cursorUngroupCell() + { + try + { + executeCommand( new UngroupCellCommand() ); + emit cursorChanged(); + } + catch( exception &e ) + { + throw e; + } + } + + /*! + * \author Anders Fernström + * \date 2006-04-26 + * + * \brief Split current cell + */ + void CellDocument::cursorSplitCell() + { + try + { + executeCommand( new SplitCellCommand() ); + emit cursorChanged(); + } + catch( exception &e ) + { + throw e; + } + } + + /*! + * \author Ingemar Axelsson + */ + void CellDocument::cursorDeleteCell() + { + executeCommand(new DeleteSelectedCellsCommand()); + qDebug("cursorDeleteCell"); + + //emit cursorChanged(); //This causes an untracable segfault. + + qDebug("Finished"); + } + + /*! + * \author Ingemar Axelsson + * + * \bug Notice that it does not work on selected cells. + */ + void CellDocument::cursorCutCell() + { + executeCommand(new DeleteCurrentCellCommand()); + } + + /*! + * \author Ingemar Axelsson + */ + void CellDocument::cursorCopyCell() + { + executeCommand(new CopySelectedCellsCommand()); + } + + /*! + * \author Ingemar Axelsson + */ + void CellDocument::cursorPasteCell() + { + executeCommand(new PasteCellsCommand()); + } + + /*! + * \author Ingemar Axelsson + */ + void CellDocument::cursorMoveAfter(Cell *aCell, const bool open) + { + //if(!open) + executeCommand(new CursorMoveAfterCommand(aCell)); + // else + // { + // if(aCell->hasChilds()) + // executeCommand(new CursorMoveAfterCommand(aCell->child())); + // else + // executeCommand(new CursorMoveAfterCommand(aCell)); + // } + + emit cursorChanged(); + } + + /*! + * \author Anders Fernström + * \date 2006-02-07 + * + * \brief Cut text + */ + void CellDocument::textcursorCutText() + { + executeCommand( new TextCursorCutText() ); + } + + /*! + * \author Anders Fernström + * \date 2006-02-07 + * + * \brief Copy text + */ + void CellDocument::textcursorCopyText() + { + executeCommand( new TextCursorCopyText() ); + } + + /*! + * \author Anders Fernström + * \date 2006-02-07 + * + * \brief Paste text + */ + void CellDocument::textcursorPasteText() + { + executeCommand( new TextCursorPasteText() ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the font family on the selected text, if + * no text selected the current font family will be changed. + * + * \param family The new font family + */ + void CellDocument::textcursorChangeFontFamily(QString family) + { + executeCommand( new TextCursorChangeFontFamily(family) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the font weight on the selected text, if + * no text selected the current font weight will be changed. + * + * \param weight The new font weight + */ + void CellDocument::textcursorChangeFontFace(int face) + { + executeCommand( new TextCursorChangeFontFace(face) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the font size on the selected text, if + * no text selected the current font size will be changed. + * + * \param size The new font size + */ + void CellDocument::textcursorChangeFontSize(int size) + { + executeCommand( new TextCursorChangeFontSize(size) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the font stretch on the selected text, if + * no text selected the current font stretch will be changed. + * + * \param stretch The new font stretch + */ + void CellDocument::textcursorChangeFontStretch(int stretch) + { + executeCommand( new TextCursorChangeFontStretch(stretch) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the font color on the selected text, if + * no text selected the current font color will be changed. + * + * \param color The new font color + */ + void CellDocument::textcursorChangeFontColor(QColor color) + { + executeCommand( new TextCursorChangeFontColor(color) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the text alignment on the text inside the cell + * + * \param alignment The new text alignment + */ + void CellDocument::textcursorChangeTextAlignment(int alignment) + { + executeCommand( new TextCursorChangeTextAlignment(alignment) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the vertical alignment on the selected text, if + * no text selected the current vertical alignment will be changed. + * + * \param color The new vertical alignment + */ + void CellDocument::textcursorChangeVerticalAlignment(int alignment) + { + executeCommand( new TextCursorChangeVerticalAlignment(alignment) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the margin of the cell + * + * \param margin The new maring + */ + void CellDocument::textcursorChangeMargin(int margin) + { + executeCommand( new TextCursorChangeMargin(margin) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the padding of the cell + * + * \param padding The new padding + */ + void CellDocument::textcursorChangePadding(int padding) + { + executeCommand( new TextCursorChangePadding(padding) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Change the border of the cell + * + * \param border The new border + */ + void CellDocument::textcursorChangeBorder(int border) + { + executeCommand( new TextCursorChangeBorder(border) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-18 + * + * \brief Insert a image into the selected cell + * + * \param filepath The path to the image + */ + void CellDocument::textcursorInsertImage(QString filepath, QSize size) + { + executeCommand( new TextCursorInsertImage(filepath, size) ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-18 + * \date 2006-02-13 (update) + * + * \brief Add image to the document + * + * The function first check for an availible name for the image, + * then saves the image temporary to the harddirve and returns + * the name of the file. + * + * 2005-12-12 AF, Added 'file:///(path)/' to very image name + * 2006-02-13 AF, All images are added in the sub dir + * 'OMNotebook_tempfiles'. + * + * \param image A pointer to the images that should be added + * \return the filename of the saved image + */ + QString CellDocument::addImage(QImage *image) + { + // first find a correct temp filename + QDir dir; + + // 2006-02-13 AF, store images in temp dir + dir.setPath( dir.absolutePath() + "/OMNotebook_tempfiles" ); + + QString name; + while( true ) + { + currentImageNo_++; + name.setNum( currentImageNo_ ); + name += ".png"; + if( !dir.exists( name )) + break; + } + + name = dir.absolutePath() + "/" + name; + + // save the image temporary to the harddrive + QImageWriter writer( name, "png" ); + writer.setDescription( "Temporary OMNotebook image" ); + writer.setQuality( 100 ); + writer.write( *image ); + + images_[ name ] = image; + + // 2005-12-12 AF, Add file:/// to filename + name = QString("file:///") + name; + + // return the imagename + return name; + } + + /*! + * \author Anders Fernström + * \date 2005-11-20 + * \date 2005-12-12 (update) + * + * \brief Returns the image with the specified name + * + * 2005-12-12 AF, remove 'file:///' from name + * + * \param name Name of the image + * \return a pointer to the image + */ + QImage *CellDocument::getImage(QString name) + { + name.remove( "file:///" ); + + QImage *image; + + if( images_.contains( name )) + image = images_[name]; + else + { + cout << "Could not find image: " << name.toStdString() << endl; + image = new QImage(); + } + + return image; + } + + /*! + * \author Anders Fernström + * \date 2005-12-05 + * + * \brief Insert a link to the selected text + * + * \param filepath The linkpath to another docuement + */ + void CellDocument::textcursorInsertLink( QString filepath, QTextCursor& cursor ) + { + executeCommand( new TextCursorInsertLink( filepath, cursor )); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + */ + bool CellDocument::hasChanged() const + { + return changed_; + } + + /*! + * \author Ingemar Axelsson + */ + bool CellDocument::isOpen() const + { + return open_; + } + + /*! + * \author Anders Fernström + */ + bool CellDocument::isSaved() const + { + return saved_; + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Return true if the document is empty, otherwise false + */ + bool CellDocument::isEmpty() const + { + bool empty( false ); + if( workspace_ ) + { + if( workspace_->hasChilds() ) + { + Cell* cell = workspace_->child(); + if( cell ) + { + if( !cell->hasNext() ) + if( typeid( (*cell) ) == typeid( CellCursor )) + empty = true; + } + else + empty = true; + } + else + empty = true; + } + else + empty = true; + + return empty; + } + + /*! + * \author Anders Fernström + * \date 2005-11-29 + * \date 2006-03-03 (update) + * + * \brief Update the scrollarea so the correct area is displayed + * + * 2005-12-08 AF, remade function becuase the earlier version hade + * some large bugs. Didn't calculate cells position correct, becuase + * qt:s layout system reset position to 0 in every groupcell and + * layout are probobly not set correctly. + * 2006-03-03 AF, ignore move if the cursor it at the end of the + * document + */ + void CellDocument::updateScrollArea() + { + if( scroll_->verticalScrollBar()->isVisible() ) + { + CellCursor *cursor = getCursor(); + if( cursor ) + { + // ignore, if selected cell is a groupcell + if( typeid( *cursor->currentCell() ) != typeid( CellGroup ) ) + { + // calculate the position of the cursor, by adding the height + // of all the cells before the cellcursor, using a visitor + CursorPosVisitor visitor; + runVisitor( visitor ); + int pos = visitor.position(); + + // size of scrollarea + int scrollTop = scroll_->widget()->visibleRegion().boundingRect().top(); + int scrollBottom = scroll_->widget()->visibleRegion().boundingRect().bottom(); + + // cell height + int height = cursor->currentCell()->height(); #ifndef QT_NO_DEBUG_OUTPUT - cout << "*********************************************" << endl; - cout << "SCROLL TOP: " << scrollTop << endl; - cout << "SCROLL BOTTOM: " << scrollBottom << endl; - cout << "CELL CURSOR: " << pos << endl; - cout << "CELL HEIGHT: " << height << endl; + cout << "*********************************************" << endl; + cout << "SCROLL TOP: " << scrollTop << endl; + cout << "SCROLL BOTTOM: " << scrollBottom << endl; + cout << "CELL CURSOR: " << pos << endl; + cout << "CELL HEIGHT: " << height << endl; #endif - // TO BIG - if( height > (scrollBottom-scrollTop) ) - { - qDebug( "TO BIG" ); - // cell so big that it span over entire viewarea - return; - } - // END OF DOCUMENT - else if( pos > (scroll_->widget()->height() - 2 ) && - scrollBottom > (scroll_->widget()->height() - 2 ) ) - { + // TO BIG + if( height > (scrollBottom-scrollTop) ) + { + qDebug( "TO BIG" ); + // cell so big that it span over entire viewarea + return; + } + // END OF DOCUMENT + else if( pos > (scroll_->widget()->height() - 2 ) && + scrollBottom > (scroll_->widget()->height() - 2 ) ) + { #ifndef QT_NO_DEBUG_OUTPUT - cout << "END OF DOCUMENT, widget height(" << scroll_->widget()->height() << ")" << endl; + cout << "END OF DOCUMENT, widget height(" << scroll_->widget()->height() << ")" << endl; #endif - // 2006-03-03 AF, ignore if cursor at end of document - return; - } - // UP - else if( (pos - height) < scrollTop ) - { - // cursor have moved above the viewarea of the - // scrollbar, move up the scrollbar - - // remove cell height + a little extra - pos -= (height + 10); - if( pos < 0 ) - pos = 0; - - // set new scrollvalue - cout << "UP: old(" << scroll_->verticalScrollBar()->value() << "), new(" << pos << ")" << endl; - scroll_->verticalScrollBar()->setValue( pos ); - } - // DOWN - else if( pos > (scrollBottom - 10) ) - { - // cursor have moved below the viewarea of the - // scrollbar, move down the scrollbar - - // add cell height + a little extra to scrollbar - //pos = height + 20 + scroll_->verticalScrollBar()->value(); - - // add differens between cell cursor position och scroll bottom - // to the scroll value - pos = scroll_->verticalScrollBar()->value() + (pos - (scrollBottom - 10)); - - if( pos >= scroll_->verticalScrollBar()->maximum() ) - { + // 2006-03-03 AF, ignore if cursor at end of document + return; + } + // UP + else if( (pos - height) < scrollTop ) + { + // cursor have moved above the viewarea of the + // scrollbar, move up the scrollbar + + // remove cell height + a little extra + pos -= (height + 10); + if( pos < 0 ) + pos = 0; + + // set new scrollvalue + cout << "UP: old(" << scroll_->verticalScrollBar()->value() << "), new(" << pos << ")" << endl; + scroll_->verticalScrollBar()->setValue( pos ); + } + // DOWN + else if( pos > (scrollBottom - 10) ) + { + // cursor have moved below the viewarea of the + // scrollbar, move down the scrollbar + + // add cell height + a little extra to scrollbar + //pos = height + 20 + scroll_->verticalScrollBar()->value(); + + // add differens between cell cursor position och scroll bottom + // to the scroll value + pos = scroll_->verticalScrollBar()->value() + (pos - (scrollBottom - 10)); + + if( pos >= scroll_->verticalScrollBar()->maximum() ) + { #ifndef QT_NO_DEBUG_OUTPUT - cout << "more then max!" << endl; + cout << "more then max!" << endl; #endif - scroll_->verticalScrollBar()->triggerAction( QAbstractSlider::SliderToMaximum ); - //pos = scroll_->verticalScrollBar()->maximum(); - - // a little extra to the max value of the scrollbar - //scroll_->verticalScrollBar()->setMaximum( 5 + - // scroll_->verticalScrollBar()->maximum() ); - } - else - { - // set new scrollvalue + scroll_->verticalScrollBar()->triggerAction( QAbstractSlider::SliderToMaximum ); + //pos = scroll_->verticalScrollBar()->maximum(); + + // a little extra to the max value of the scrollbar + //scroll_->verticalScrollBar()->setMaximum( 5 + + // scroll_->verticalScrollBar()->maximum() ); + } + else + { + // set new scrollvalue #ifndef QT_NO_DEBUG_OUTPUT - cout << "DOWN: old(" << scroll_->verticalScrollBar()->value() << "), new(" << pos << ")" << endl; + cout << "DOWN: old(" << scroll_->verticalScrollBar()->value() << "), new(" << pos << ")" << endl; #endif - scroll_->verticalScrollBar()->setValue( pos ); - } - } - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-17 - * - * \brief set the change variable - */ - void CellDocument::setChanged( bool changed ) - { - changed_ = changed; - emit contentChanged(); - } - - /*! - * \author Anders Fernström - * \date 2006-02-10 - */ - void CellDocument::hoverOverUrl( const QUrl &link ) - { - QString filelink = link.path(); - - if( !link.fragment().isEmpty() ) - filelink += QString("#") + link.fragment(); - - if( !filelink.isEmpty() && !link.path().isEmpty() ) - { - if( filename_.isEmpty() || filename_.isEmpty() ) - { - // replace '\' with '/' in the link path - filelink.replace( "\\", "/" ); - - QDir dir; - filelink = dir.absolutePath() + "/" + filelink; - } - else - { - // replace '\' with '/' in the link path - filelink.replace( "\\", "/" ); - filelink = QFileInfo(filename_).absolutePath() + "/" + filelink; - } - } + scroll_->verticalScrollBar()->setValue( pos ); + } + } + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-17 + * + * \brief set the change variable + */ + void CellDocument::setChanged( bool changed ) + { + changed_ = changed; + emit contentChanged(); + } + + /*! + * \author Anders Fernström + * \date 2006-02-10 + */ + void CellDocument::hoverOverUrl( const QUrl &link ) + { + QString filelink = link.path(); + + if( !link.fragment().isEmpty() ) + filelink += QString("#") + link.fragment(); + + if( !filelink.isEmpty() && !link.path().isEmpty() ) + { + if( filename_.isEmpty() || filename_.isEmpty() ) + { + // replace '\' with '/' in the link path + filelink.replace( "\\", "/" ); + + QDir dir; + filelink = dir.absolutePath() + "/" + filelink; + } + else + { + // replace '\' with '/' in the link path + filelink.replace( "\\", "/" ); + filelink = QFileInfo(filename_).absolutePath() + "/" + filelink; + } + } emit hoverOverFile( filelink ); - } - - /*! - * \author Ingemar Axelsson - */ - void CellDocument::mouseClickedOnCell(Cell *clickedCell) - { - // 2006-04-25, AF - if( lastClickedCell_ == clickedCell ) - return; - else - lastClickedCell_ = clickedCell; - - - //Deselect all selection - clearSelection(); - - //Remove focus from old cell. - if(getCursor()->currentCell()->isClosed()) - { - getCursor()->currentCell()->child()->setReadOnly(true); - getCursor()->currentCell()->child()->setFocus(false); - } - else - { - getCursor()->currentCell()->setReadOnly(true); - } - - //Add focus to the cell clicked on. - if(clickedCell->parentCell()->isClosed()) - { - getCursor()->moveAfter(clickedCell->parentCell()); - } - else - { - getCursor()->moveAfter(clickedCell); //Results in bus error why? - } - - clickedCell->setReadOnly(false); - clickedCell->setFocus(true); - - emit cursorChanged(); - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * - * \brief set focus on output part in inputcell - */ - void CellDocument::mouseClickedOnCellOutput(Cell *clickedCell) - { - clearSelection(); - - //Remove focus from old cell. - if(getCursor()->currentCell()->isClosed()) - { - getCursor()->currentCell()->child()->setReadOnly(true); - getCursor()->currentCell()->child()->setFocus(false); - } - else - { - getCursor()->currentCell()->setReadOnly(true); - } - - //Add focus to the cell clicked on. - if(clickedCell->parentCell()->isClosed()) - { - getCursor()->moveAfter(clickedCell->parentCell()); - } - else - { - getCursor()->moveAfter(clickedCell); //Results in bus error why? - } - - if( typeid(InputCell) == typeid(*clickedCell)) - { - InputCell *inputcell = dynamic_cast(clickedCell); - inputcell->setReadOnly(false); - inputcell->setFocusOutput(true); - } - else if(typeid(GraphCell) == typeid(*clickedCell)) - { - GraphCell *graphcell = dynamic_cast(clickedCell); - graphcell->setReadOnly(false); - graphcell->setFocusOutput(true); - } - - else - { - clickedCell->setReadOnly(false); - clickedCell->setFocus(true); - } - - emit cursorChanged(); - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2006-02-10 (update) - * - * \brief open a new document - * - * 2005-12-05 AF, check if filename exists, otherwise use work dir - * 2006-02-10 AF, check if link path and fragment exists - */ - void CellDocument::linkClicked(const QUrl *link) -// void CellDocument::anchorClicked(const QUrl *link) - { - // 2006-02-10 AF, check if path is empty + } + + /*! + * \author Ingemar Axelsson + */ + void CellDocument::mouseClickedOnCell(Cell *clickedCell) + { + // 2006-04-25, AF + if( lastClickedCell_ == clickedCell ) + return; + else + lastClickedCell_ = clickedCell; + + + //Deselect all selection + clearSelection(); + + //Remove focus from old cell. + if(getCursor()->currentCell()->isClosed()) + { + getCursor()->currentCell()->child()->setReadOnly(true); + getCursor()->currentCell()->child()->setFocus(false); + } + else + { + getCursor()->currentCell()->setReadOnly(true); + } + + //Add focus to the cell clicked on. + if(clickedCell->parentCell()->isClosed()) + { + getCursor()->moveAfter(clickedCell->parentCell()); + } + else + { + getCursor()->moveAfter(clickedCell); //Results in bus error why? + } + + clickedCell->setReadOnly(false); + clickedCell->setFocus(true); + + emit cursorChanged(); + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * + * \brief set focus on output part in inputcell + */ + void CellDocument::mouseClickedOnCellOutput(Cell *clickedCell) + { + clearSelection(); + + //Remove focus from old cell. + if(getCursor()->currentCell()->isClosed()) + { + getCursor()->currentCell()->child()->setReadOnly(true); + getCursor()->currentCell()->child()->setFocus(false); + } + else + { + getCursor()->currentCell()->setReadOnly(true); + } + + //Add focus to the cell clicked on. + if(clickedCell->parentCell()->isClosed()) + { + getCursor()->moveAfter(clickedCell->parentCell()); + } + else + { + getCursor()->moveAfter(clickedCell); //Results in bus error why? + } + + if( typeid(InputCell) == typeid(*clickedCell)) + { + InputCell *inputcell = dynamic_cast(clickedCell); + inputcell->setReadOnly(false); + inputcell->setFocusOutput(true); + } + else if(typeid(GraphCell) == typeid(*clickedCell)) + { + GraphCell *graphcell = dynamic_cast(clickedCell); + graphcell->setReadOnly(false); + graphcell->setFocusOutput(true); + } + + else + { + clickedCell->setReadOnly(false); + clickedCell->setFocus(true); + } + + emit cursorChanged(); + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2006-02-10 (update) + * + * \brief open a new document + * + * 2005-12-05 AF, check if filename exists, otherwise use work dir + * 2006-02-10 AF, check if link path and fragment exists + */ + void CellDocument::linkClicked(const QUrl *link) +// void CellDocument::anchorClicked(const QUrl *link) + { + // 2006-02-10 AF, check if path is empty fprintf(stderr, "received link: %s\n", link->toString().toStdString().c_str()); fflush(stderr); fflush(stdout); - if( !link->path().isEmpty() ) - { - // 2005-12-05 AF, check if filename exists, otherwise use work dir - if( filename_.isEmpty() ) - { - // replace '\' with '/' in the link path + if( !link->path().isEmpty() ) + { + // 2005-12-05 AF, check if filename exists, otherwise use work dir + if( filename_.isEmpty() ) + { + // replace '\' with '/' in the link path QString linkpath = link->toLocalFile(); - linkpath.replace( "\\", "/" ); + linkpath.replace( "\\", "/" ); - QDir dir; + QDir dir; executeCommand(new OpenFileCommand( dir.absolutePath() + '/' + linkpath )); - } - else - { - // replace '\' with '/' in the link path - QString linkpath = link->toLocalFile(); - linkpath.replace( "\\", "/" ); + } + else + { + // replace '\' with '/' in the link path + QString linkpath = link->toLocalFile(); + linkpath.replace( "\\", "/" ); executeCommand(new OpenFileCommand( QFileInfo(filename_).absolutePath() + '/' + linkpath )); - } - } + } + } - // 2006-02-10 AF, check if there is a link fragment - if( !link->fragment().isEmpty() ) - { - //should handel internal document links in some way + // 2006-02-10 AF, check if there is a link fragment + if( !link->fragment().isEmpty() ) + { + //should handel internal document links in some way - } - } - - - - - // *************************************************************** - - - - - - - - /*! - * Problem with the eventfilter. Should be listening to the - mainwidget of the cell also. Not only to the workspace. - */ - bool CellDocument::eventFilter(QObject *o, QEvent *e) - { - if(o == workspace_) - { - if(e->type() == QEvent::MouseButtonPress) - { - qDebug("Clicked"); - } - } - - return QObject::eventFilter(o,e); - } - - CellCursor *CellDocument::getCursor() - { - return current_; - } - - /*! - * \todo Save all commands. Also implement undo. Where should the - * undo be set? Global in application or local in document? Or - * should different commands be stored in different places.(Ingemar Axelsson) - * - * \todo implement a commandCenter interface that takes care of - * this. A problem with this conversion is the commands dependency - * for the document reference.(Ingemar Axelsson) - */ - void CellDocument::executeCommand(Command *cmd) - { - cmd->setDocument(this); - application()->commandCenter()->executeCommand(cmd); - } - - /*! - * \todo Check if factory is instantiated. (Ingemar Axelsson) - */ - Factory *CellDocument::cellFactory() - { - return factory_; - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief get the main cell - */ - Cell* CellDocument::getMainCell() - { - return workspace_; - } - - QString CellDocument::getFilename() - { - return filename_; - } - - void CellDocument::setFilename( QString filename ) - { - filename_ = filename; - } - - void CellDocument::setSaved( bool saved ) - { - saved_ = saved; - } - - - - /*! Hmmm check this later. - */ - void CellDocument::close() - { - //workspace_->close(true); //Close widget - //mainLayout_->deleteLater(); - workspace_->close(); - - setWorkspace(factory_->createCell("cellgroup")); - workspace_->hide(); - open_ = false; - } - - /*! \brief Toggles the main workspace treeview. - * - * Shows or hides the outermost treeview. This is just used for - * testing. Should not be used by anyone else. - * - * \deprecated - */ - void CellDocument::toggleMainTreeView() - { - workspace_->hideTreeView(!workspace_->isTreeViewVisible()); - } - - - //Ever used? - void CellDocument::cursorChangedPosition() - { - // emit cursorChanged(); - } - - /*! - * \todo Check if ever used. It does seem to be deprecated.(Ingemar Axelsson) - */ - void CellDocument::setEditable(bool editable) - { - if(current_->hasPrevious()) - { - current_->previous()->setReadOnly(!editable); - } - } - - /*! \brief Runs a visitor on the cellstructure. - * - * Traverses the tree in preorder. For more usage information \see visitor. - * - * \param v Visitor to run on the treestructure. - */ - void CellDocument::runVisitor(Visitor &v) - { - //For all workspace_ child! Not ws itself. - workspace_->accept(v); - } - - ////SELECTION HANDLING///////////////////////// - - /*! - * \author Anders Fernström - * \date 2006-04-18 - * - * \brief Help function for selection handling - */ - void CellDocument::addSelectedCell( Cell* cell ) - { - if( cell ) - { - cell->setSelected( true ); - selectedCells_.push_back( cell ); - } - } - - /*! - * \author Anders Fernström - * \date 2006-04-18 - * - * \brief Help function for selection handling - */ - void CellDocument::removeSelectedCell( Cell* cell ) - { - if( cell ) - { - vector::iterator found = std::find( selectedCells_.begin(), - selectedCells_.end(), cell ); - - if( found != selectedCells_.end() ) - { - (*found)->setSelected( false ); - selectedCells_.erase( found ); - } - } - } - - void CellDocument::clearSelection() - { - vector::iterator i = selectedCells_.begin(); - - for(;i!= selectedCells_.end();++i) - (*i)->setSelected(false); - - selectedCells_.clear(); - } - - // 2006-04-18 AF, Reimplemented the function. Also added support - // for selecting several cells by holding SHIFT down - void CellDocument::selectedACell( Cell *selected, Qt::KeyboardModifiers state ) - { - if( selected ) - { - // if SHIFT is pressed, select all cells from last cell - if( state == Qt::ShiftModifier && - selected->isSelected() && - selectedCells_.size() > 0 ) - { - // if last selected cell and this selected cell aren't - // int the same groupcell this funciton can't be used. - Cell *lastCell = selectedCells_[ selectedCells_.size() - 1 ]; - if( selected->parentCell() == lastCell->parentCell() ) - { - // check which cell is first in list - int count(0); - int cellCount(0); - int lastCellCound(0); - - Cell *current = selected->next(); - while( current ) - { - // don't count cursor - if( typeid(CellCursor) != typeid(*current) ) - ++cellCount; - - current = current->next(); - } - - current = lastCell->next(); - while( current ) - { - // don't count cursor - if( typeid(CellCursor) != typeid(*current) ) - ++lastCellCound; - - current = current->next(); - } - - // LASTCELL, last in list - if( cellCount > lastCellCound ) - { - count = ( cellCount - lastCellCound ) + 1; // also add last cell - removeSelectedCell( lastCell ); - - current = selected; - for( int i = 0; i < count; ++i ) - { - // don't add cursor - if( typeid(CellCursor) != typeid(*current) ) - addSelectedCell( current ); - else - ++count; - - current = current->next(); - } - } - // LASTCELL, first in list - else - { - count = ( lastCellCound - cellCount ); - - current = lastCell->next(); - for( int i = 0; i < count; ++i ) - { - // don't add cursor - if( typeid(CellCursor) != typeid(*current) ) - addSelectedCell( current ); - else - ++count; - - current = current->next(); - } - } - } - else - { - selected->setSelected( false ); - return; - } - } - // if CTRL is pressed, keep existing selections - else if( state == Qt::ControlModifier ) - { - if( selected->isSelected() ) - addSelectedCell( selected ); - else - removeSelectedCell( selected ); - } - else - { - bool flag = ( selectedCells_.size() > 1 ); - clearSelection(); - - if( flag || selected->isSelected() ) - addSelectedCell( selected ); - else - removeSelectedCell( selected ); - } - - // move cell cursor to cell - //cursorMoveAfter( selected, false ); - } - } - - vector CellDocument::getSelection() - { - return selectedCells_; - } - - /////OBSERVER IMPLEMENTATION////////////// - - void CellDocument::attach(DocumentView *d) - { - observers_.push_back(d); - NotebookWindow *w = dynamic_cast(d); - connect(this, SIGNAL(copyAvailable(bool)), w->copyAction, SLOT(setEnabled(bool))); - connect(this, SIGNAL(copyAvailable(bool)), w->cutAction, SLOT(setEnabled(bool))); - connect(this, SIGNAL(undoAvailable(bool)), w->undoAction, SLOT(setEnabled(bool))); - connect(this, SIGNAL(redoAvailable(bool)), w->redoAction, SLOT(setEnabled(bool))); - - - } - - void CellDocument::detach(DocumentView *d) - { - observers_t::iterator found = find(observers_.begin(), - observers_.end(), - d); - if(found != observers_.end()) - observers_.erase(found); - } - - void CellDocument::notify() - { - observers_t::iterator i = observers_.begin(); - for(;i != observers_.end(); ++i) - { - (*i)->update(); - } - } - - ///////CURSOR METHODS/////////////////////////////// - - QFrame *CellDocument::getState() - { - return mainFrame_; - } - - - - void CellDocument::showHTML(bool b) - { - getCursor()->currentCell()->viewExpression(b); - - } - - - void CellDocument::setAutoIndent2(bool b) - { - emit setAutoIndent(b); - autoIndent = b; - } + } + } + + + + + // *************************************************************** + + + + + + + + /*! + * Problem with the eventfilter. Should be listening to the + mainwidget of the cell also. Not only to the workspace. + */ + bool CellDocument::eventFilter(QObject *o, QEvent *e) + { + if(o == workspace_) + { + if(e->type() == QEvent::MouseButtonPress) + { + qDebug("Clicked"); + } + } + + return QObject::eventFilter(o,e); + } + + CellCursor *CellDocument::getCursor() + { + return current_; + } + + /*! + * \todo Save all commands. Also implement undo. Where should the + * undo be set? Global in application or local in document? Or + * should different commands be stored in different places.(Ingemar Axelsson) + * + * \todo implement a commandCenter interface that takes care of + * this. A problem with this conversion is the commands dependency + * for the document reference.(Ingemar Axelsson) + */ + void CellDocument::executeCommand(Command *cmd) + { + cmd->setDocument(this); + application()->commandCenter()->executeCommand(cmd); + } + + /*! + * \todo Check if factory is instantiated. (Ingemar Axelsson) + */ + Factory *CellDocument::cellFactory() + { + return factory_; + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief get the main cell + */ + Cell* CellDocument::getMainCell() + { + return workspace_; + } + + QString CellDocument::getFilename() + { + return filename_; + } + + void CellDocument::setFilename( QString filename ) + { + filename_ = filename; + } + + void CellDocument::setSaved( bool saved ) + { + saved_ = saved; + } + + + + /*! Hmmm check this later. + */ + void CellDocument::close() + { + //workspace_->close(true); //Close widget + //mainLayout_->deleteLater(); + workspace_->close(); + + setWorkspace(factory_->createCell("cellgroup")); + workspace_->hide(); + open_ = false; + } + + /*! \brief Toggles the main workspace treeview. + * + * Shows or hides the outermost treeview. This is just used for + * testing. Should not be used by anyone else. + * + * \deprecated + */ + void CellDocument::toggleMainTreeView() + { + workspace_->hideTreeView(!workspace_->isTreeViewVisible()); + } + + + //Ever used? + void CellDocument::cursorChangedPosition() + { + // emit cursorChanged(); + } + + /*! + * \todo Check if ever used. It does seem to be deprecated.(Ingemar Axelsson) + */ + void CellDocument::setEditable(bool editable) + { + if(current_->hasPrevious()) + { + current_->previous()->setReadOnly(!editable); + } + } + + /*! \brief Runs a visitor on the cellstructure. + * + * Traverses the tree in preorder. For more usage information \see visitor. + * + * \param v Visitor to run on the treestructure. + */ + void CellDocument::runVisitor(Visitor &v) + { + //For all workspace_ child! Not ws itself. + workspace_->accept(v); + } + + ////SELECTION HANDLING///////////////////////// + + /*! + * \author Anders Fernström + * \date 2006-04-18 + * + * \brief Help function for selection handling + */ + void CellDocument::addSelectedCell( Cell* cell ) + { + if( cell ) + { + cell->setSelected( true ); + selectedCells_.push_back( cell ); + } + } + + /*! + * \author Anders Fernström + * \date 2006-04-18 + * + * \brief Help function for selection handling + */ + void CellDocument::removeSelectedCell( Cell* cell ) + { + if( cell ) + { + vector::iterator found = std::find( selectedCells_.begin(), + selectedCells_.end(), cell ); + + if( found != selectedCells_.end() ) + { + (*found)->setSelected( false ); + selectedCells_.erase( found ); + } + } + } + + void CellDocument::clearSelection() + { + vector::iterator i = selectedCells_.begin(); + + for(;i!= selectedCells_.end();++i) + (*i)->setSelected(false); + + selectedCells_.clear(); + } + + // 2006-04-18 AF, Reimplemented the function. Also added support + // for selecting several cells by holding SHIFT down + void CellDocument::selectedACell( Cell *selected, Qt::KeyboardModifiers state ) + { + if( selected ) + { + // if SHIFT is pressed, select all cells from last cell + if( state == Qt::ShiftModifier && + selected->isSelected() && + selectedCells_.size() > 0 ) + { + // if last selected cell and this selected cell aren't + // int the same groupcell this funciton can't be used. + Cell *lastCell = selectedCells_[ selectedCells_.size() - 1 ]; + if( selected->parentCell() == lastCell->parentCell() ) + { + // check which cell is first in list + int count(0); + int cellCount(0); + int lastCellCound(0); + + Cell *current = selected->next(); + while( current ) + { + // don't count cursor + if( typeid(CellCursor) != typeid(*current) ) + ++cellCount; + + current = current->next(); + } + + current = lastCell->next(); + while( current ) + { + // don't count cursor + if( typeid(CellCursor) != typeid(*current) ) + ++lastCellCound; + + current = current->next(); + } + + // LASTCELL, last in list + if( cellCount > lastCellCound ) + { + count = ( cellCount - lastCellCound ) + 1; // also add last cell + removeSelectedCell( lastCell ); + + current = selected; + for( int i = 0; i < count; ++i ) + { + // don't add cursor + if( typeid(CellCursor) != typeid(*current) ) + addSelectedCell( current ); + else + ++count; + + current = current->next(); + } + } + // LASTCELL, first in list + else + { + count = ( lastCellCound - cellCount ); + + current = lastCell->next(); + for( int i = 0; i < count; ++i ) + { + // don't add cursor + if( typeid(CellCursor) != typeid(*current) ) + addSelectedCell( current ); + else + ++count; + + current = current->next(); + } + } + } + else + { + selected->setSelected( false ); + return; + } + } + // if CTRL is pressed, keep existing selections + else if( state == Qt::ControlModifier ) + { + if( selected->isSelected() ) + addSelectedCell( selected ); + else + removeSelectedCell( selected ); + } + else + { + bool flag = ( selectedCells_.size() > 1 ); + clearSelection(); + + if( flag || selected->isSelected() ) + addSelectedCell( selected ); + else + removeSelectedCell( selected ); + } + + // move cell cursor to cell + //cursorMoveAfter( selected, false ); + } + } + + vector CellDocument::getSelection() + { + return selectedCells_; + } + + /////OBSERVER IMPLEMENTATION////////////// + + void CellDocument::attach(DocumentView *d) + { + observers_.push_back(d); + NotebookWindow *w = dynamic_cast(d); + connect(this, SIGNAL(copyAvailable(bool)), w->copyAction, SLOT(setEnabled(bool))); + connect(this, SIGNAL(copyAvailable(bool)), w->cutAction, SLOT(setEnabled(bool))); + connect(this, SIGNAL(undoAvailable(bool)), w->undoAction, SLOT(setEnabled(bool))); + connect(this, SIGNAL(redoAvailable(bool)), w->redoAction, SLOT(setEnabled(bool))); + + + } + + void CellDocument::detach(DocumentView *d) + { + observers_t::iterator found = find(observers_.begin(), + observers_.end(), + d); + if(found != observers_.end()) + observers_.erase(found); + } + + void CellDocument::notify() + { + observers_t::iterator i = observers_.begin(); + for(;i != observers_.end(); ++i) + { + (*i)->update(); + } + } + + ///////CURSOR METHODS/////////////////////////////// + + QFrame *CellDocument::getState() + { + return mainFrame_; + } + + + + void CellDocument::showHTML(bool b) + { + getCursor()->currentCell()->viewExpression(b); + + } + + + void CellDocument::setAutoIndent2(bool b) + { + emit setAutoIndent(b); + autoIndent = b; + } }; diff --git a/OMNotebook/OMNotebookQT4/celldocument.h b/OMNotebook/OMNotebookQT4/celldocument.h index aaaf6cc4bb2..c1762e85340 100644 --- a/OMNotebook/OMNotebookQT4/celldocument.h +++ b/OMNotebook/OMNotebookQT4/celldocument.h @@ -62,160 +62,160 @@ class QUrl; namespace IAEX { - class CellDocument : public Document - { - Q_OBJECT - - public: - typedef vector observers_t; - - CellDocument(CellApplication *a, const QString filename, int readmode = READMODE_NORMAL); - virtual ~CellDocument(); - - void setApplication(CellApplication *app){app_ = app;} - CellApplication *application(){ return app_;} - - //Document implementations - virtual void open( const QString filename, int readmode = READMODE_NORMAL ); - virtual void close(); - virtual QString getFilename(); - virtual void setFilename( QString filename ); //AF - virtual void setSaved( bool saved ); //AF - - virtual void attach(DocumentView *d); - virtual void detach(DocumentView *d); - virtual void notify(); - - //Cursor methods - virtual void cursorStepUp(); - virtual void cursorStepDown(); - virtual void cursorAddCell(); - virtual void cursorUngroupCell(); // Added 2006-04-26 AF - virtual void cursorSplitCell(); // Added 2006-04-26 AF - virtual void cursorDeleteCell(); - virtual void cursorCutCell(); - virtual void cursorCopyCell(); - virtual void cursorPasteCell(); - virtual void cursorChangeStyle(CellStyle style); // Changed 2005-10-28 AF - - //TextCursor operations, added 2006-02-07 AF - virtual void textcursorCutText(); - virtual void textcursorCopyText(); - virtual void textcursorPasteText(); - //TextCursor operations, added 2005-11-03 AF - virtual void textcursorChangeFontFamily( QString family ); - virtual void textcursorChangeFontFace( int face ); - virtual void textcursorChangeFontSize( int size ); - virtual void textcursorChangeFontStretch( int stretch ); - virtual void textcursorChangeFontColor( QColor color ); - virtual void textcursorChangeTextAlignment( int alignment ); - virtual void textcursorChangeVerticalAlignment( int alignment ); - virtual void textcursorChangeMargin( int margin ); - virtual void textcursorChangePadding( int padding ); - virtual void textcursorChangeBorder( int border ); - - // Added 2005-11-18 AF, Image operations - virtual void textcursorInsertImage( QString filepath, QSize size ); - virtual QString addImage( QImage *image ); - virtual QImage *getImage( QString name ); - - // Added 2005-12-05 AF, Link operations - virtual void textcursorInsertLink( QString filepath, QTextCursor& cursor); - - //State operations - virtual bool hasChanged() const; - bool isOpen() const; - bool isSaved() const; - bool isEmpty() const; // Added 2006-08-24 AF - - //Cursor operations - CellCursor *getCursor(); - Factory *cellFactory(); - Cell* getMainCell(); // Added 2006-08-24 AF - vector getSelection(); - - //Command - void executeCommand(Command *cmd); - - //Traversals. - void runVisitor(Visitor &v); - - virtual void setAutoIndent2(bool); - - //observer - QFrame *getState(); - - public slots: - void toggleMainTreeView(); - void setEditable(bool editable); - void cursorChangedPosition(); - void updateScrollArea(); // Added 2005-11-29 AF - void setChanged( bool changed ); // Added 2006-01-17 AF - void hoverOverUrl( const QUrl &link ); // Added 2006-02-10 AF - void selectedACell(Cell *selected, Qt::KeyboardModifiers); - void clearSelection(); - void mouseClickedOnCell(Cell *clickedCell); - void mouseClickedOnCellOutput(Cell *clickedCell); //Added 2006-02-03 - void linkClicked(const QUrl *url); -// void anchorClicked(const QUrl *url); - virtual void cursorMoveAfter(Cell *aCell, const bool open); - void showHTML(bool b); - - - signals: - virtual void copyAvailable(bool); - virtual void undoAvailable(bool); - virtual void redoAvailable(bool); - virtual void setAutoIndent(bool); - - void updatePos(int, int); - void newState(QString); - void setStatusMenu(QList); - void widthChanged(const int); - void cursorChanged(); - void viewExpression(const bool); - void contentChanged(); // Added 2005-11-29 AF - void hoverOverFile( QString ); // Added 2006-02-10 AF - void forwardAction( int ); // Added 2006-04-27 AF - - - protected: - void setWorkspace(Cell *newWorkspace); - bool eventFilter(QObject *o, QEvent *e); - - private: - void addSelectedCell( Cell* cell ); - void removeSelectedCell( Cell* cell ); - - - private: - bool changed_; // Added 2006-01-17 AF - bool open_; - bool saved_; - - CellApplication *app_; - QString filename_; - - Cell *workspace_; //This should alwas be a cellgroup. - Cell *lastClickedCell_; // Added 2006-04-25 AF - QFrame *mainFrame_; - - - QScrollArea *scroll_; // Added 2005-11-01 AF - QGridLayout *mainLayout_; - - CellCursor *current_; - Factory *factory_; - - vector selectedCells_; - - public: - observers_t observers_; - bool autoIndent; - private: - QHash images_; // Added 2005-11-19 AF - int currentImageNo_; // Added 2005-11-19 AF - }; + class CellDocument : public Document + { + Q_OBJECT + + public: + typedef vector observers_t; + + CellDocument(CellApplication *a, const QString filename, int readmode = READMODE_NORMAL); + virtual ~CellDocument(); + + void setApplication(CellApplication *app){app_ = app;} + CellApplication *application(){ return app_;} + + //Document implementations + virtual void open( const QString filename, int readmode = READMODE_NORMAL ); + virtual void close(); + virtual QString getFilename(); + virtual void setFilename( QString filename ); //AF + virtual void setSaved( bool saved ); //AF + + virtual void attach(DocumentView *d); + virtual void detach(DocumentView *d); + virtual void notify(); + + //Cursor methods + virtual void cursorStepUp(); + virtual void cursorStepDown(); + virtual void cursorAddCell(); + virtual void cursorUngroupCell(); // Added 2006-04-26 AF + virtual void cursorSplitCell(); // Added 2006-04-26 AF + virtual void cursorDeleteCell(); + virtual void cursorCutCell(); + virtual void cursorCopyCell(); + virtual void cursorPasteCell(); + virtual void cursorChangeStyle(CellStyle style); // Changed 2005-10-28 AF + + //TextCursor operations, added 2006-02-07 AF + virtual void textcursorCutText(); + virtual void textcursorCopyText(); + virtual void textcursorPasteText(); + //TextCursor operations, added 2005-11-03 AF + virtual void textcursorChangeFontFamily( QString family ); + virtual void textcursorChangeFontFace( int face ); + virtual void textcursorChangeFontSize( int size ); + virtual void textcursorChangeFontStretch( int stretch ); + virtual void textcursorChangeFontColor( QColor color ); + virtual void textcursorChangeTextAlignment( int alignment ); + virtual void textcursorChangeVerticalAlignment( int alignment ); + virtual void textcursorChangeMargin( int margin ); + virtual void textcursorChangePadding( int padding ); + virtual void textcursorChangeBorder( int border ); + + // Added 2005-11-18 AF, Image operations + virtual void textcursorInsertImage( QString filepath, QSize size ); + virtual QString addImage( QImage *image ); + virtual QImage *getImage( QString name ); + + // Added 2005-12-05 AF, Link operations + virtual void textcursorInsertLink( QString filepath, QTextCursor& cursor); + + //State operations + virtual bool hasChanged() const; + bool isOpen() const; + bool isSaved() const; + bool isEmpty() const; // Added 2006-08-24 AF + + //Cursor operations + CellCursor *getCursor(); + Factory *cellFactory(); + Cell* getMainCell(); // Added 2006-08-24 AF + vector getSelection(); + + //Command + void executeCommand(Command *cmd); + + //Traversals. + void runVisitor(Visitor &v); + + virtual void setAutoIndent2(bool); + + //observer + QFrame *getState(); + + public slots: + void toggleMainTreeView(); + void setEditable(bool editable); + void cursorChangedPosition(); + void updateScrollArea(); // Added 2005-11-29 AF + void setChanged( bool changed ); // Added 2006-01-17 AF + void hoverOverUrl( const QUrl &link ); // Added 2006-02-10 AF + void selectedACell(Cell *selected, Qt::KeyboardModifiers); + void clearSelection(); + void mouseClickedOnCell(Cell *clickedCell); + void mouseClickedOnCellOutput(Cell *clickedCell); //Added 2006-02-03 + void linkClicked(const QUrl *url); +// void anchorClicked(const QUrl *url); + virtual void cursorMoveAfter(Cell *aCell, const bool open); + void showHTML(bool b); + + + signals: + virtual void copyAvailable(bool); + virtual void undoAvailable(bool); + virtual void redoAvailable(bool); + virtual void setAutoIndent(bool); + + void updatePos(int, int); + void newState(QString); + void setStatusMenu(QList); + void widthChanged(const int); + void cursorChanged(); + void viewExpression(const bool); + void contentChanged(); // Added 2005-11-29 AF + void hoverOverFile( QString ); // Added 2006-02-10 AF + void forwardAction( int ); // Added 2006-04-27 AF + + + protected: + void setWorkspace(Cell *newWorkspace); + bool eventFilter(QObject *o, QEvent *e); + + private: + void addSelectedCell( Cell* cell ); + void removeSelectedCell( Cell* cell ); + + + private: + bool changed_; // Added 2006-01-17 AF + bool open_; + bool saved_; + + CellApplication *app_; + QString filename_; + + Cell *workspace_; //This should alwas be a cellgroup. + Cell *lastClickedCell_; // Added 2006-04-25 AF + QFrame *mainFrame_; + + + QScrollArea *scroll_; // Added 2005-11-01 AF + QGridLayout *mainLayout_; + + CellCursor *current_; + Factory *factory_; + + vector selectedCells_; + + public: + observers_t observers_; + bool autoIndent; + private: + QHash images_; // Added 2005-11-19 AF + int currentImageNo_; // Added 2005-11-19 AF + }; } diff --git a/OMNotebook/OMNotebookQT4/celldocumentview.h b/OMNotebook/OMNotebookQT4/celldocumentview.h index c1d16d5b53a..a6a60455d2a 100644 --- a/OMNotebook/OMNotebookQT4/celldocumentview.h +++ b/OMNotebook/OMNotebookQT4/celldocumentview.h @@ -52,22 +52,22 @@ namespace IAEX public: CellDocumentView(Document *subject) : subject_(subject) { - //Connect view to document. + //Connect view to document. - subject_->attach(this); + subject_->attach(this); } virtual ~CellDocumentView(){} void update() { - if(centralWidget()) - { - //remove currentwidget. - } + if(centralWidget()) + { + //remove currentwidget. + } - //Update with new widget. - setCentralWidget(subject_->getState()); + //Update with new widget. + setCentralWidget(subject_->getState()); } private: diff --git a/OMNotebook/OMNotebookQT4/cellfactory.cpp b/OMNotebook/OMNotebookQT4/cellfactory.cpp index 6932ca0efd6..904823967cd 100644 --- a/OMNotebook/OMNotebookQT4/cellfactory.cpp +++ b/OMNotebook/OMNotebookQT4/cellfactory.cpp @@ -137,9 +137,9 @@ namespace IAEX QObject::connect( text, SIGNAL( forwardAction(int) ), doc_, SIGNAL( forwardAction(int) )); - // CellDocument* d = dynamic_cast(doc_); - // DocumentView* d2 = d->observers_[0]; - // NotebookWindow *d3 = dynamic_cast(d2); + // CellDocument* d = dynamic_cast(doc_); + // DocumentView* d2 = d->observers_[0]; + // NotebookWindow *d3 = dynamic_cast(d2); QObject::connect(text->input_, SIGNAL(copyAvailable(bool)), doc_, SIGNAL(copyAvailable(bool))); QObject::connect(text->input_, SIGNAL(undoAvailable(bool)), doc_, SIGNAL(undoAvailable(bool))); QObject::connect(text->input_, SIGNAL(redoAvailable(bool)), doc_, SIGNAL(redoAvailable(bool))); @@ -233,7 +233,7 @@ namespace IAEX QObject::connect(text->input_, SIGNAL(redoAvailable(bool)), doc_, SIGNAL(redoAvailable(bool))); QObject::connect(text->output_, SIGNAL(copyAvailable(bool)), doc_, SIGNAL(copyAvailable(bool))); - // if(CellDocument* d = dynamic_cast(doc_)) + // if(CellDocument* d = dynamic_cast(doc_)) QObject::connect(doc_, SIGNAL(setAutoIndent(bool)), text->input_, SLOT(setAutoIndent(bool))); //QObject::connect(doc_, SIGNAL(evaluate()), text->input_, SIGNAL(eval())); text->input_->setAutoIndent(dynamic_cast(doc_)->autoIndent); @@ -297,7 +297,7 @@ namespace IAEX QObject::connect(text->text_, SIGNAL(copyAvailable(bool)), doc_, SIGNAL(copyAvailable(bool))); QObject::connect(text->text_, SIGNAL(undoAvailable(bool)), doc_, SIGNAL(undoAvailable(bool))); QObject::connect(text->text_, SIGNAL(redoAvailable(bool)), doc_, SIGNAL(redoAvailable(bool))); - // QObject::connect(text->output_, SIGNAL(copyAvailable(bool)), this, SLOT(copyAvailable(bool))); + // QObject::connect(text->output_, SIGNAL(copyAvailable(bool)), this, SLOT(copyAvailable(bool))); /* CellDocument* d = dynamic_cast(doc_); diff --git a/OMNotebook/OMNotebookQT4/cellfactory.h b/OMNotebook/OMNotebookQT4/cellfactory.h index 3813c155970..6c84ecccbe9 100644 --- a/OMNotebook/OMNotebookQT4/cellfactory.h +++ b/OMNotebook/OMNotebookQT4/cellfactory.h @@ -51,19 +51,19 @@ namespace IAEX { - /*! - * \breif Interface for all cellfactories. - */ - class CellFactory : public Factory - { - public: - CellFactory(Document *doc); - virtual ~CellFactory(); + /*! + * \breif Interface for all cellfactories. + */ + class CellFactory : public Factory + { + public: + CellFactory(Document *doc); + virtual ~CellFactory(); - virtual Cell *createCell(const QString &style, Cell *parent=0); + virtual Cell *createCell(const QString &style, Cell *parent=0); - private: - Document *doc_; - }; + private: + Document *doc_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/cellgroup.cpp b/OMNotebook/OMNotebookQT4/cellgroup.cpp index fb4b6a2caa4..a9f3e3efcf7 100644 --- a/OMNotebook/OMNotebookQT4/cellgroup.cpp +++ b/OMNotebook/OMNotebookQT4/cellgroup.cpp @@ -51,443 +51,443 @@ namespace IAEX{ - /*! - * \class CellGroup - * \author Ingemar Axelsson and Anders Fernström - * - * \brief CellGroup implements the functionality to - * be a Cell and contain a lot of subcells. - * - * - * \todo Reimplement as a composite instead. That is much much - * cleaner. Also look at CellWorkspace and rename CellContainer to - * CellDocument. CellWorkspace should dissappear.(Ingemar Axelsson) - * - * \todo Analyse class and find out what is different from the - * Cell class. Is it possible that cell and cellgroup should be - * integrated as one class? - * It should be easy to convert from a cell to a cellgroup. (Ingemar Axelsson) - */ - - - /*! - * \author Ingemar Axelsson - * - * \brief The class constructor - */ - CellGroup::CellGroup(QWidget *parent) - : Cell(parent), - closed_(false), - newIndex_(0) - { - main_ = new QWidget(this); - - layout_ = new QGridLayout(main_); - layout_->setMargin(0); - layout_->setSpacing(0); - - setMainWidget(main_); - - style_.setName( "cellgroup" ); - - - } - - /*! - * \author Ingemar Axelsson - * - * \brief The class destructor - */ - CellGroup::~CellGroup() - { - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-10-28 (update) - * - * \brief Set the cells style. If the cell is closed, set style - * on the first child (the cell thats displayed). - * - * 2005-10-28, changes style from QString to CellStyle /AF - * - * \param style The cell style that is to be applyed to the cell - */ - void CellGroup::setStyle(CellStyle style) - { - if(closed_) - child()->setStyle(style); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-10-28 (update) - * - * \brief Return the cells style. If the cell is closed, style - * is returned from the first child (the cell thats displayed). - * If the cell is opened this function returns a new CellStyle - * with the name 'cellgroup'; - * - * 2005-10-28, changes style from QString to CellStyle /AF - * - * \return The cells style - */ - CellStyle *CellGroup::style() - { - if(closed_) - return child()->style(); - else - { - return &style_; - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-30 - * - * \brief hide() or show() the child cells of the groupcell, - * depending on the state of the groupcell (opened or closed). - * This must be done because otherwise qt layout will compress - * all child and display them in the smaller height set went the - * groupcell is closed. - */ - void CellGroup::closeChildCells() - { - if( closed_ ) - { - Cell *current = child(); - if( current != 0 ) - { - current = current->next(); - while(current != 0) - { - current->hide(); - current = current->next(); - } - } - } - else - { - Cell *current = child(); - if( current != 0 ) - { - current = current->next(); - while(current != 0) - { - current->show(); - current = current->next(); - } - } - } - } - - /*! - * \author Ingemar Axelsson - */ - bool CellGroup::isClosed() const - { - return closed_; - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Function for telling if the user is allowed to change - * the text settings for the text inside the cell. User isn't - * allowed to change the text settings for cellgroups so this - * function always return false. - * - * \return False - */ - bool CellGroup::isEditable() - { - return false; - } - - /*! - * \author Anders Fernström - * \date 2005-08-24 - * - * \brief Returns the first childs text editor, if the cell is closed. If - * the cell isn't closed, return 0. - * - * \return False - */ - QTextEdit* CellGroup::textEdit() - { - if( isClosed() && hasChilds() ) - return child()->textEdit(); - else - return 0; - } - - /*! - * \author Ingemar Axelsson - * - * \brief This function hides/shows the content of a groupcell. - * - * This member hides/shows the content of a cellgroup. The height of - * the cellgroup is calculated depending on wich case it is. - * - * \param closed tells if the cells should be visible or hidden. - * - * - * \todo Add some signals when this happens. It can be possible that - * someone will do some fun stuff when a cell is closing.(Ingemar Axelsson) - * - * \todo reimplement with removing and adding to the layout instead.(Ingemar Axelsson) - * - * - * \bug This function could create a segmentation fault in some - * special cases. Try to find them. - */ - void CellGroup::setClosed(const bool closed, bool update) - { - closed_ = closed; - - if( hasChilds() ) - child()->hideTreeView( closed ); - - treeView()->setClosed( closed ); - setHeight( height() ); //Sends a signal - - - - if( update ) - emit cellOpened(this, closed_); - } - - /*! - * \author Ingemar Axelsson - * - * \brief calculates the height of the cellgroup. - * - * Calculates the height of the cellgroup. The calculated height - * depends on the state of the group. Is the group closed then the - * height is just the first cell otherwise the height is a sum of - * the height of all cells. - * - * \returns height of cellgroup. - * - * - * \bug HeightVisitor does not return correct height value. I do - * not know why, so I implemented another way to traverse subcells - * and asking for heights. - */ - int CellGroup::height() - { - int height = 0; - - if( closed_ ) - { - //Height of the first cell. - height = child()->height(); - } - else - { - Cell *current = child(); - int h = 0; - while(current != 0) - { - h += current->height(); - current = current->next(); - } - - height = h; - } - - return height; - } - - /*! - * \author Ingemar Axelsson (and Anders Fernström) - * \date 2005-11-30 (update) - * - * \brief open and close the groupcell when double click on the - * treeview - * - * 2005-11-30 AF, added the call to 'closeChildCells()' - * - * \todo Should this be moved to treeview?(Ingemar Axelsson) - */ - void CellGroup::mouseDoubleClickEvent(QMouseEvent *event) - { - // PORT >>if(treeView()->hasMouse()) - if( treeView()->testAttribute(Qt::WA_UnderMouse) ) - { - closed_ = !closed_; - setClosed(closed_); - setSelected(false); - closeChildCells(); - } - else - { - //Do nothing. - } - } - - /*! - * \author Ingemar Axelsson - */ - void CellGroup::adjustHeight() - { - setHeight( height() ); - } - - // *************************************************************** - - void CellGroup::setFocus(const bool focus) - { - if(hasChilds()) - child()->setFocus(focus); - } - - /*! \brief Decides if a visitor is allowed to visit the object. - * - * Traverses the structure in preorder. - * - * \todo Could the traversing order be decided in the visitor instead - * without to much dirt added to the code class? This is definitly not - * important.(Ingemar Axelsson) - * - * \todo Implement an Iterator for the cell structure. This could be - * nice.(Ingemar Axelsson) - * - */ - void CellGroup::accept(Visitor &v) - { - v.visitCellGroupNodeBefore(this); - - if(hasChilds()) - child()->accept(v); - - v.visitCellGroupNodeAfter(this); - - if(hasNext()) - next()->accept(v); - } - - - /*! - * \todo Try to get rid of the dependency of the doc() member. One - way should be to use the cursor when opening a document. Use the - cursors add functionality. Then this could be removed. The - dependency should only be in the cursor then.(Ingemar Axelsson) - */ - void CellGroup::addChild(Cell *newCell) - { - newCell->setParentCell(this); - - if(hasChilds()) - { - Cell *previous = last(); - - newCell->setPrevious(previous); - newCell->setNext(0); - - previous->setNext(newCell); - setLast(newCell); - } - else - { //First in line. - setChild(newCell); - setLast(newCell); - newCell->setNext(0); - newCell->setPrevious(0); - } - - addCellWidget(newCell); - } - - /*! - * \brief Removes a cell from a cellgroup. But does not delete the cell! - */ - void CellGroup::removeChild(Cell *aCell) - { - - //remove all widgets from parents layout. - Cell *par = aCell->parentCell(); - par->removeCellWidgets(); - - Cell *prev = aCell->previous(); - Cell *next = aCell->next(); - - if(aCell->parentCell()->child() == aCell) - aCell->parentCell()->setChild(aCell->next()); - - if(aCell->parentCell()->last() == aCell) - aCell->parentCell()->setLast(aCell->previous()); - - if(next) - { - if(prev) - next->setPrevious(prev); - } - - if(prev) - { - if(next) - prev->setNext(next); - } - //Insert all widgets again. - par->addCellWidgets(); - } - - //Just add widget. Don´t forget to repaint. - void CellGroup::addCellWidget(Cell *newCell) - { - // PORT >> newCell->reparent(mainWidget(), QPoint(0,0), true); - newCell->setParent( mainWidget() ); - newCell->move( QPoint(0,0) ); - newCell->show(); - - connect(newCell, SIGNAL(heightChanged()), - this, SLOT(adjustHeight())); - - removeCellWidgets(); - addCellWidgets(); - } - - void CellGroup::removeCellWidgets() - { - Cell *current = child(); - - while(current != 0) - { - // PORT >> layout_->remove(current); - layout_->removeWidget(current); - - current = current->next(); - } - } - - void CellGroup::addCellWidgets() - { - Cell *current = child(); - int i = 0; - - while(current != 0) - { - if(current->parentWidget() != mainWidget()) - { - // PORT >> current->reparent(mainWidget(), QPoint(0,0), true); - current->setParent( mainWidget() ); - current->move( QPoint(0,0) ); - current->show(); - - connect(current, SIGNAL(heightChanged()), - this, SLOT(adjustHeight())); - } - - layout_->addWidget(current,i,0); - ++i; - current = current->next(); - } - - adjustHeight(); - } + /*! + * \class CellGroup + * \author Ingemar Axelsson and Anders Fernström + * + * \brief CellGroup implements the functionality to + * be a Cell and contain a lot of subcells. + * + * + * \todo Reimplement as a composite instead. That is much much + * cleaner. Also look at CellWorkspace and rename CellContainer to + * CellDocument. CellWorkspace should dissappear.(Ingemar Axelsson) + * + * \todo Analyse class and find out what is different from the + * Cell class. Is it possible that cell and cellgroup should be + * integrated as one class? + * It should be easy to convert from a cell to a cellgroup. (Ingemar Axelsson) + */ + + + /*! + * \author Ingemar Axelsson + * + * \brief The class constructor + */ + CellGroup::CellGroup(QWidget *parent) + : Cell(parent), + closed_(false), + newIndex_(0) + { + main_ = new QWidget(this); + + layout_ = new QGridLayout(main_); + layout_->setMargin(0); + layout_->setSpacing(0); + + setMainWidget(main_); + + style_.setName( "cellgroup" ); + + + } + + /*! + * \author Ingemar Axelsson + * + * \brief The class destructor + */ + CellGroup::~CellGroup() + { + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-10-28 (update) + * + * \brief Set the cells style. If the cell is closed, set style + * on the first child (the cell thats displayed). + * + * 2005-10-28, changes style from QString to CellStyle /AF + * + * \param style The cell style that is to be applyed to the cell + */ + void CellGroup::setStyle(CellStyle style) + { + if(closed_) + child()->setStyle(style); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-10-28 (update) + * + * \brief Return the cells style. If the cell is closed, style + * is returned from the first child (the cell thats displayed). + * If the cell is opened this function returns a new CellStyle + * with the name 'cellgroup'; + * + * 2005-10-28, changes style from QString to CellStyle /AF + * + * \return The cells style + */ + CellStyle *CellGroup::style() + { + if(closed_) + return child()->style(); + else + { + return &style_; + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-30 + * + * \brief hide() or show() the child cells of the groupcell, + * depending on the state of the groupcell (opened or closed). + * This must be done because otherwise qt layout will compress + * all child and display them in the smaller height set went the + * groupcell is closed. + */ + void CellGroup::closeChildCells() + { + if( closed_ ) + { + Cell *current = child(); + if( current != 0 ) + { + current = current->next(); + while(current != 0) + { + current->hide(); + current = current->next(); + } + } + } + else + { + Cell *current = child(); + if( current != 0 ) + { + current = current->next(); + while(current != 0) + { + current->show(); + current = current->next(); + } + } + } + } + + /*! + * \author Ingemar Axelsson + */ + bool CellGroup::isClosed() const + { + return closed_; + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Function for telling if the user is allowed to change + * the text settings for the text inside the cell. User isn't + * allowed to change the text settings for cellgroups so this + * function always return false. + * + * \return False + */ + bool CellGroup::isEditable() + { + return false; + } + + /*! + * \author Anders Fernström + * \date 2005-08-24 + * + * \brief Returns the first childs text editor, if the cell is closed. If + * the cell isn't closed, return 0. + * + * \return False + */ + QTextEdit* CellGroup::textEdit() + { + if( isClosed() && hasChilds() ) + return child()->textEdit(); + else + return 0; + } + + /*! + * \author Ingemar Axelsson + * + * \brief This function hides/shows the content of a groupcell. + * + * This member hides/shows the content of a cellgroup. The height of + * the cellgroup is calculated depending on wich case it is. + * + * \param closed tells if the cells should be visible or hidden. + * + * + * \todo Add some signals when this happens. It can be possible that + * someone will do some fun stuff when a cell is closing.(Ingemar Axelsson) + * + * \todo reimplement with removing and adding to the layout instead.(Ingemar Axelsson) + * + * + * \bug This function could create a segmentation fault in some + * special cases. Try to find them. + */ + void CellGroup::setClosed(const bool closed, bool update) + { + closed_ = closed; + + if( hasChilds() ) + child()->hideTreeView( closed ); + + treeView()->setClosed( closed ); + setHeight( height() ); //Sends a signal + + + + if( update ) + emit cellOpened(this, closed_); + } + + /*! + * \author Ingemar Axelsson + * + * \brief calculates the height of the cellgroup. + * + * Calculates the height of the cellgroup. The calculated height + * depends on the state of the group. Is the group closed then the + * height is just the first cell otherwise the height is a sum of + * the height of all cells. + * + * \returns height of cellgroup. + * + * + * \bug HeightVisitor does not return correct height value. I do + * not know why, so I implemented another way to traverse subcells + * and asking for heights. + */ + int CellGroup::height() + { + int height = 0; + + if( closed_ ) + { + //Height of the first cell. + height = child()->height(); + } + else + { + Cell *current = child(); + int h = 0; + while(current != 0) + { + h += current->height(); + current = current->next(); + } + + height = h; + } + + return height; + } + + /*! + * \author Ingemar Axelsson (and Anders Fernström) + * \date 2005-11-30 (update) + * + * \brief open and close the groupcell when double click on the + * treeview + * + * 2005-11-30 AF, added the call to 'closeChildCells()' + * + * \todo Should this be moved to treeview?(Ingemar Axelsson) + */ + void CellGroup::mouseDoubleClickEvent(QMouseEvent *event) + { + // PORT >>if(treeView()->hasMouse()) + if( treeView()->testAttribute(Qt::WA_UnderMouse) ) + { + closed_ = !closed_; + setClosed(closed_); + setSelected(false); + closeChildCells(); + } + else + { + //Do nothing. + } + } + + /*! + * \author Ingemar Axelsson + */ + void CellGroup::adjustHeight() + { + setHeight( height() ); + } + + // *************************************************************** + + void CellGroup::setFocus(const bool focus) + { + if(hasChilds()) + child()->setFocus(focus); + } + + /*! \brief Decides if a visitor is allowed to visit the object. + * + * Traverses the structure in preorder. + * + * \todo Could the traversing order be decided in the visitor instead + * without to much dirt added to the code class? This is definitly not + * important.(Ingemar Axelsson) + * + * \todo Implement an Iterator for the cell structure. This could be + * nice.(Ingemar Axelsson) + * + */ + void CellGroup::accept(Visitor &v) + { + v.visitCellGroupNodeBefore(this); + + if(hasChilds()) + child()->accept(v); + + v.visitCellGroupNodeAfter(this); + + if(hasNext()) + next()->accept(v); + } + + + /*! + * \todo Try to get rid of the dependency of the doc() member. One + way should be to use the cursor when opening a document. Use the + cursors add functionality. Then this could be removed. The + dependency should only be in the cursor then.(Ingemar Axelsson) + */ + void CellGroup::addChild(Cell *newCell) + { + newCell->setParentCell(this); + + if(hasChilds()) + { + Cell *previous = last(); + + newCell->setPrevious(previous); + newCell->setNext(0); + + previous->setNext(newCell); + setLast(newCell); + } + else + { //First in line. + setChild(newCell); + setLast(newCell); + newCell->setNext(0); + newCell->setPrevious(0); + } + + addCellWidget(newCell); + } + + /*! + * \brief Removes a cell from a cellgroup. But does not delete the cell! + */ + void CellGroup::removeChild(Cell *aCell) + { + + //remove all widgets from parents layout. + Cell *par = aCell->parentCell(); + par->removeCellWidgets(); + + Cell *prev = aCell->previous(); + Cell *next = aCell->next(); + + if(aCell->parentCell()->child() == aCell) + aCell->parentCell()->setChild(aCell->next()); + + if(aCell->parentCell()->last() == aCell) + aCell->parentCell()->setLast(aCell->previous()); + + if(next) + { + if(prev) + next->setPrevious(prev); + } + + if(prev) + { + if(next) + prev->setNext(next); + } + //Insert all widgets again. + par->addCellWidgets(); + } + + //Just add widget. Don´t forget to repaint. + void CellGroup::addCellWidget(Cell *newCell) + { + // PORT >> newCell->reparent(mainWidget(), QPoint(0,0), true); + newCell->setParent( mainWidget() ); + newCell->move( QPoint(0,0) ); + newCell->show(); + + connect(newCell, SIGNAL(heightChanged()), + this, SLOT(adjustHeight())); + + removeCellWidgets(); + addCellWidgets(); + } + + void CellGroup::removeCellWidgets() + { + Cell *current = child(); + + while(current != 0) + { + // PORT >> layout_->remove(current); + layout_->removeWidget(current); + + current = current->next(); + } + } + + void CellGroup::addCellWidgets() + { + Cell *current = child(); + int i = 0; + + while(current != 0) + { + if(current->parentWidget() != mainWidget()) + { + // PORT >> current->reparent(mainWidget(), QPoint(0,0), true); + current->setParent( mainWidget() ); + current->move( QPoint(0,0) ); + current->show(); + + connect(current, SIGNAL(heightChanged()), + this, SLOT(adjustHeight())); + } + + layout_->addWidget(current,i,0); + ++i; + current = current->next(); + } + + adjustHeight(); + } } diff --git a/OMNotebook/OMNotebookQT4/cellgroup.h b/OMNotebook/OMNotebookQT4/cellgroup.h index 125ad3262f3..66f3e19ff69 100644 --- a/OMNotebook/OMNotebookQT4/cellgroup.h +++ b/OMNotebook/OMNotebookQT4/cellgroup.h @@ -59,57 +59,57 @@ using namespace IAEX; namespace IAEX{ - class CellGroup : public Cell - { - Q_OBJECT + class CellGroup : public Cell + { + Q_OBJECT - public: - CellGroup(QWidget *parent=0); - virtual ~CellGroup(); + public: + CellGroup(QWidget *parent=0); + virtual ~CellGroup(); - virtual void viewExpression(const bool){}; + virtual void viewExpression(const bool){}; - //Traversals implementation - virtual void accept(Visitor &v); + //Traversals implementation + virtual void accept(Visitor &v); - //Datastructure implementation. - virtual void addChild(Cell *newCell); - virtual void removeChild(Cell *aCell); + //Datastructure implementation. + virtual void addChild(Cell *newCell); + virtual void removeChild(Cell *aCell); - virtual void addCellWidget(Cell *newCell); - virtual void addCellWidgets(); - virtual void removeCellWidgets(); + virtual void addCellWidget(Cell *newCell); + virtual void addCellWidgets(); + virtual void removeCellWidgets(); - int height(); - CellStyle *style(); // Changed 2005-10-28 - virtual QString text(){return QString::null;} + int height(); + CellStyle *style(); // Changed 2005-10-28 + virtual QString text(){return QString::null;} - void closeChildCells(); // Added 2005-11-30 AF + void closeChildCells(); // Added 2005-11-30 AF - //Flag - bool isClosed() const; - bool isEditable(); // Added 2005-10-28 AF + //Flag + bool isClosed() const; + bool isEditable(); // Added 2005-10-28 AF - QTextEdit* textEdit(); // Added 2006-08-24 AF + QTextEdit* textEdit(); // Added 2006-08-24 AF - public slots: - virtual void setStyle( CellStyle style ); // Changed 2005-10-28 AF - void setClosed(const bool closed, bool update = true); - virtual void setFocus(const bool focus); + public slots: + virtual void setStyle( CellStyle style ); // Changed 2005-10-28 AF + void setClosed(const bool closed, bool update = true); + virtual void setFocus(const bool focus); - protected: - void mouseDoubleClickEvent(QMouseEvent *event); + protected: + void mouseDoubleClickEvent(QMouseEvent *event); - protected slots: - void adjustHeight(); + protected slots: + void adjustHeight(); - private: - bool closed_; + private: + bool closed_; - QWidget *main_; - QGridLayout *layout_; - unsigned long newIndex_; - }; + QWidget *main_; + QGridLayout *layout_; + unsigned long newIndex_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/cellparserfactory.cpp b/OMNotebook/OMNotebookQT4/cellparserfactory.cpp index 16c8ecff181..ec4d3e57f86 100644 --- a/OMNotebook/OMNotebookQT4/cellparserfactory.cpp +++ b/OMNotebook/OMNotebookQT4/cellparserfactory.cpp @@ -45,9 +45,9 @@ namespace IAEX * This factory class knows how to open different fileformats. If a * new fileformat should be added the code for parsing the new format. * - * Do not forget to delete a parser when it is not used anymore. - * - * + * Do not forget to delete a parser when it is not used anymore. + * + * * \todo Check for whitespaces in filename. Whitespaces at the end * of a file should be taken care of in some way.(Ingemar Axelsson) * @@ -58,7 +58,7 @@ namespace IAEX NBParser *CellParserFactory::createParser(QString filename, Factory *f, Document *document, int readmode) { // PORT >>filename = filename.stripWhiteSpace(); - QString fileName = filename.trimmed(); - return new XMLParser(fileName, f, document, readmode); + QString fileName = filename.trimmed(); + return new XMLParser(fileName, f, document, readmode); } }; diff --git a/OMNotebook/OMNotebookQT4/cellstyle.h b/OMNotebook/OMNotebookQT4/cellstyle.h index 9283b54edec..a0a60f22388 100644 --- a/OMNotebook/OMNotebookQT4/cellstyle.h +++ b/OMNotebook/OMNotebookQT4/cellstyle.h @@ -48,68 +48,68 @@ namespace IAEX { - /*! - * \class CellStyle - * \author Anders Fernström - * \date 2005-10-26 - * \date 2006-03-02 (update) - * - * \brief A class that store the different styleoptions that - * can be changed in a cell. - * - * 2005-11-10 AF, Added some default values in the constructor - * 2005-11-15 AF, Added some more default values - * 2006-03-02 AF, Added a variable and functions that allows the - * style to be hidden from the style menu - * 2006-03-02 AF, Added a variable and functions that holds the - * styles chapter level, if any - */ - class CellStyle - { - public: - CellStyle() - { - textFormat_.setFontFamily( "Times New Roman" ); - textFormat_.setFontItalic( false ); - textFormat_.setFontOverline( false ); - textFormat_.setFontStrikeOut( false ); - textFormat_.setFontUnderline( false ); - textFormat_.setFontWeight( QFont::Normal ); - textFormat_.setFontPointSize( 12 ); + /*! + * \class CellStyle + * \author Anders Fernström + * \date 2005-10-26 + * \date 2006-03-02 (update) + * + * \brief A class that store the different styleoptions that + * can be changed in a cell. + * + * 2005-11-10 AF, Added some default values in the constructor + * 2005-11-15 AF, Added some more default values + * 2006-03-02 AF, Added a variable and functions that allows the + * style to be hidden from the style menu + * 2006-03-02 AF, Added a variable and functions that holds the + * styles chapter level, if any + */ + class CellStyle + { + public: + CellStyle() + { + textFormat_.setFontFamily( "Times New Roman" ); + textFormat_.setFontItalic( false ); + textFormat_.setFontOverline( false ); + textFormat_.setFontStrikeOut( false ); + textFormat_.setFontUnderline( false ); + textFormat_.setFontWeight( QFont::Normal ); + textFormat_.setFontPointSize( 12 ); - textFormat_.setForeground( QBrush( QColor(0,0,0) )); + textFormat_.setForeground( QBrush( QColor(0,0,0) )); - // 2006-03-02 AF, defalut visibliity - visible_ = true; + // 2006-03-02 AF, defalut visibliity + visible_ = true; - // 2006-03-02 AF, defalut chapter level - chapterLevel_ = 0; - } - virtual ~CellStyle(){} + // 2006-03-02 AF, defalut chapter level + chapterLevel_ = 0; + } + virtual ~CellStyle(){} - QString name(){ return name_; } - QTextCharFormat* textCharFormat(){ return &textFormat_; } - QTextFrameFormat* textFrameFormat(){ return &frameFormat_; } - int alignment(){ return alignment_; } - bool visible(){ return visible_; } // Added 2006-03-02 AF - int chapterLevel(){ return chapterLevel_; } // Added 2006-03-02 AF + QString name(){ return name_; } + QTextCharFormat* textCharFormat(){ return &textFormat_; } + QTextFrameFormat* textFrameFormat(){ return &frameFormat_; } + int alignment(){ return alignment_; } + bool visible(){ return visible_; } // Added 2006-03-02 AF + int chapterLevel(){ return chapterLevel_; } // Added 2006-03-02 AF - void setName( QString name ){ name_ = name; } - void setTextCharFormat( QTextCharFormat format ){ textFormat_ = format; } - void setTextFrameFormat( QTextFrameFormat format ){ frameFormat_ = format; } - void setAlignment( int alignment ){ alignment_ = alignment; } - void setVisible( bool visible ){ visible_ = visible; } // Added 2006-03-02 AF - void setChapterLevel( int level ){ chapterLevel_ = level; } // Added 2006-03-02 AF + void setName( QString name ){ name_ = name; } + void setTextCharFormat( QTextCharFormat format ){ textFormat_ = format; } + void setTextFrameFormat( QTextFrameFormat format ){ frameFormat_ = format; } + void setAlignment( int alignment ){ alignment_ = alignment; } + void setVisible( bool visible ){ visible_ = visible; } // Added 2006-03-02 AF + void setChapterLevel( int level ){ chapterLevel_ = level; } // Added 2006-03-02 AF - private: - QString name_; - QTextCharFormat textFormat_; + private: + QString name_; + QTextCharFormat textFormat_; QTextFrameFormat frameFormat_; - int alignment_; + int alignment_; - bool visible_; // Added 2006-03-02 AF - int chapterLevel_; // Added 2006-03-02 AF - }; + bool visible_; // Added 2006-03-02 AF + int chapterLevel_; // Added 2006-03-02 AF + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/chaptercountervisitor.cpp b/OMNotebook/OMNotebookQT4/chaptercountervisitor.cpp index 2c886fbf498..1ade3f50a9c 100644 --- a/OMNotebook/OMNotebookQT4/chaptercountervisitor.cpp +++ b/OMNotebook/OMNotebookQT4/chaptercountervisitor.cpp @@ -49,162 +49,162 @@ namespace IAEX { - /*! - * \class ChapterCounterVisitor - * \date 2006-03-02 - * - * \brief Update the chapter counters in the document - */ - - /*! - * \author Anders Fernström - * - * \brief The class constructor - */ - ChapterCounterVisitor::ChapterCounterVisitor() - { - for( int i = 0; i < COUNTERS; ++i ) - counters_[i] = 0; - } - - /*! - * \author Anders Fernström - * - * \brief The class deconstructor - */ - ChapterCounterVisitor::~ChapterCounterVisitor() - {} - - // CELL - void ChapterCounterVisitor::visitCellNodeBefore(Cell *) - {} - - void ChapterCounterVisitor::visitCellNodeAfter(Cell *) - {} - - // GROUPCELL - void ChapterCounterVisitor::visitCellGroupNodeBefore(CellGroup *node) - {} - - void ChapterCounterVisitor::visitCellGroupNodeAfter(CellGroup *) - {} - - // TEXTCELL - void ChapterCounterVisitor::visitTextCellNodeBefore(TextCell *node) - { - int level = node->style()->chapterLevel(); - if( level > 0 && level <= COUNTERS ) - { - // Add on chapter couner - counters_[ level - 1 ]++; - - QString counter; - QString number; - for( int i = 0; i < level; ++i ) - { - number.setNum( counters_[i] ); - - if( !counter.isEmpty() ) - counter += "."; - - counter += number; - } - - // reset all counters avter counter[level] - for( int i = level; i < COUNTERS; ++i ) - counters_[i] = 0; - - node->setChapterCounter( counter ); - } - else - { - // clear chapter counter - node->setChapterCounter( "" ); - } - } - - void ChapterCounterVisitor::visitTextCellNodeAfter(TextCell *) - {} - - //INPUTCELL - void ChapterCounterVisitor::visitInputCellNodeBefore(InputCell *node) - { - int level = node->style()->chapterLevel(); - if( level > 0 && level <= COUNTERS ) - { - // Add on chapter couner - counters_[ level - 1 ]++; - - QString counter; - QString number; - for( int i = 0; i < level; ++i ) - { - number.setNum( counters_[i] ); - - if( !counter.isEmpty() ) - counter += "."; - - counter += number; - } - - // reset all counters avter counter[level] - for( int i = level; i < COUNTERS; ++i ) - counters_[i] = 0; - - node->setChapterCounter( counter ); - } - else - { - // clear chapter counter - node->setChapterCounter( "" ); - } - } - - void ChapterCounterVisitor::visitInputCellNodeAfter(InputCell *) - {} - - - //GRAPHCELL - - void ChapterCounterVisitor::visitGraphCellNodeBefore(GraphCell *node) - { - int level = node->style()->chapterLevel(); - if( level > 0 && level <= COUNTERS ) - { - // Add on chapter couner - counters_[ level - 1 ]++; - - QString counter; - QString number; - for( int i = 0; i < level; ++i ) - { - number.setNum( counters_[i] ); - - if( !counter.isEmpty() ) - counter += "."; - - counter += number; - } - - // reset all counters avter counter[level] - for( int i = level; i < COUNTERS; ++i ) - counters_[i] = 0; - - node->setChapterCounter( counter ); - } - else - { - // clear chapter counter - node->setChapterCounter( "" ); - } - } - - void ChapterCounterVisitor::visitGraphCellNodeAfter(GraphCell *) - {} - //CELLCURSOR - void ChapterCounterVisitor::visitCellCursorNodeBefore(CellCursor *) - {} - - void ChapterCounterVisitor::visitCellCursorNodeAfter(CellCursor *) - {} + /*! + * \class ChapterCounterVisitor + * \date 2006-03-02 + * + * \brief Update the chapter counters in the document + */ + + /*! + * \author Anders Fernström + * + * \brief The class constructor + */ + ChapterCounterVisitor::ChapterCounterVisitor() + { + for( int i = 0; i < COUNTERS; ++i ) + counters_[i] = 0; + } + + /*! + * \author Anders Fernström + * + * \brief The class deconstructor + */ + ChapterCounterVisitor::~ChapterCounterVisitor() + {} + + // CELL + void ChapterCounterVisitor::visitCellNodeBefore(Cell *) + {} + + void ChapterCounterVisitor::visitCellNodeAfter(Cell *) + {} + + // GROUPCELL + void ChapterCounterVisitor::visitCellGroupNodeBefore(CellGroup *node) + {} + + void ChapterCounterVisitor::visitCellGroupNodeAfter(CellGroup *) + {} + + // TEXTCELL + void ChapterCounterVisitor::visitTextCellNodeBefore(TextCell *node) + { + int level = node->style()->chapterLevel(); + if( level > 0 && level <= COUNTERS ) + { + // Add on chapter couner + counters_[ level - 1 ]++; + + QString counter; + QString number; + for( int i = 0; i < level; ++i ) + { + number.setNum( counters_[i] ); + + if( !counter.isEmpty() ) + counter += "."; + + counter += number; + } + + // reset all counters avter counter[level] + for( int i = level; i < COUNTERS; ++i ) + counters_[i] = 0; + + node->setChapterCounter( counter ); + } + else + { + // clear chapter counter + node->setChapterCounter( "" ); + } + } + + void ChapterCounterVisitor::visitTextCellNodeAfter(TextCell *) + {} + + //INPUTCELL + void ChapterCounterVisitor::visitInputCellNodeBefore(InputCell *node) + { + int level = node->style()->chapterLevel(); + if( level > 0 && level <= COUNTERS ) + { + // Add on chapter couner + counters_[ level - 1 ]++; + + QString counter; + QString number; + for( int i = 0; i < level; ++i ) + { + number.setNum( counters_[i] ); + + if( !counter.isEmpty() ) + counter += "."; + + counter += number; + } + + // reset all counters avter counter[level] + for( int i = level; i < COUNTERS; ++i ) + counters_[i] = 0; + + node->setChapterCounter( counter ); + } + else + { + // clear chapter counter + node->setChapterCounter( "" ); + } + } + + void ChapterCounterVisitor::visitInputCellNodeAfter(InputCell *) + {} + + + //GRAPHCELL + + void ChapterCounterVisitor::visitGraphCellNodeBefore(GraphCell *node) + { + int level = node->style()->chapterLevel(); + if( level > 0 && level <= COUNTERS ) + { + // Add on chapter couner + counters_[ level - 1 ]++; + + QString counter; + QString number; + for( int i = 0; i < level; ++i ) + { + number.setNum( counters_[i] ); + + if( !counter.isEmpty() ) + counter += "."; + + counter += number; + } + + // reset all counters avter counter[level] + for( int i = level; i < COUNTERS; ++i ) + counters_[i] = 0; + + node->setChapterCounter( counter ); + } + else + { + // clear chapter counter + node->setChapterCounter( "" ); + } + } + + void ChapterCounterVisitor::visitGraphCellNodeAfter(GraphCell *) + {} + //CELLCURSOR + void ChapterCounterVisitor::visitCellCursorNodeBefore(CellCursor *) + {} + + void ChapterCounterVisitor::visitCellCursorNodeAfter(CellCursor *) + {} } diff --git a/OMNotebook/OMNotebookQT4/chaptercountervisitor.h b/OMNotebook/OMNotebookQT4/chaptercountervisitor.h index 7079e760586..d682fb993a7 100644 --- a/OMNotebook/OMNotebookQT4/chaptercountervisitor.h +++ b/OMNotebook/OMNotebookQT4/chaptercountervisitor.h @@ -38,7 +38,7 @@ #ifndef CHAPTERCOUNTERVISITOR_H #define CHAPTERCOUNTERVISITOR_H -#define COUNTERS 10 // 10 levels should be enough +#define COUNTERS 10 // 10 levels should be enough //IAEX Headers #include "visitor.h" @@ -47,33 +47,33 @@ namespace IAEX { - class ChapterCounterVisitor : public Visitor - { + class ChapterCounterVisitor : public Visitor + { - public: - ChapterCounterVisitor(); - virtual ~ChapterCounterVisitor(); + public: + ChapterCounterVisitor(); + virtual ~ChapterCounterVisitor(); - virtual void visitCellNodeBefore(Cell *node); - virtual void visitCellNodeAfter(Cell *node); + virtual void visitCellNodeBefore(Cell *node); + virtual void visitCellNodeAfter(Cell *node); - virtual void visitCellGroupNodeBefore(CellGroup *node); - virtual void visitCellGroupNodeAfter(CellGroup *node); + virtual void visitCellGroupNodeBefore(CellGroup *node); + virtual void visitCellGroupNodeAfter(CellGroup *node); - virtual void visitTextCellNodeBefore(TextCell *node); - virtual void visitTextCellNodeAfter(TextCell *node); + virtual void visitTextCellNodeBefore(TextCell *node); + virtual void visitTextCellNodeAfter(TextCell *node); - virtual void visitInputCellNodeBefore(InputCell *node); - virtual void visitInputCellNodeAfter(InputCell *node); + virtual void visitInputCellNodeBefore(InputCell *node); + virtual void visitInputCellNodeAfter(InputCell *node); - virtual void visitGraphCellNodeBefore(GraphCell *node); - virtual void visitGraphCellNodeAfter(GraphCell *node); + virtual void visitGraphCellNodeBefore(GraphCell *node); + virtual void visitGraphCellNodeAfter(GraphCell *node); - virtual void visitCellCursorNodeBefore(CellCursor *cursor); - virtual void visitCellCursorNodeAfter(CellCursor *cursor); + virtual void visitCellCursorNodeBefore(CellCursor *cursor); + virtual void visitCellCursorNodeAfter(CellCursor *cursor); - private: - int counters_[COUNTERS]; - }; + private: + int counters_[COUNTERS]; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/command.h b/OMNotebook/OMNotebookQT4/command.h index 098857ba8ca..bbbabf88570 100644 --- a/OMNotebook/OMNotebookQT4/command.h +++ b/OMNotebook/OMNotebookQT4/command.h @@ -104,11 +104,11 @@ namespace IAEX virtual void execute() { - vector::iterator i = commands_.begin(); - for(;i != commands_.end(); ++i) - { - (*i)->execute(); - } + vector::iterator i = commands_.begin(); + for(;i != commands_.end(); ++i) + { + (*i)->execute(); + } } private: diff --git a/OMNotebook/OMNotebookQT4/commandcompletion.cpp b/OMNotebook/OMNotebookQT4/commandcompletion.cpp index 59892485bfc..41395138566 100644 --- a/OMNotebook/OMNotebookQT4/commandcompletion.cpp +++ b/OMNotebook/OMNotebookQT4/commandcompletion.cpp @@ -56,338 +56,338 @@ using namespace std; namespace IAEX { - /*! - * \class CommandCompletion - * \author Anders Fernström - * \date 2005-12-12 - * - * \brief Reads a command file and creates omc command object for - * commandcompetion in inputcells - */ - - /*! - * \author Anders Fernström - * \date 2005-12-12 - * - * \brief The class constructor - * - * \brief Reads a given file and construct a DOM tree from that file. - * If the file is corrupt a exception will be throwed. - * - * \param filename The file that will be read. - */ - CommandCompletion::CommandCompletion( const QString filename ) - : currentCommand_( -1 ), - currentField_( -1 ), - currentList_( 0 ), - commandStartPos_( 0 ), - commandEndPos_( 0 ) - { - //read a command file. - doc_ = new QDomDocument( "OMCCommand" ); - - QFile file( filename ); - if(!file.open(QIODevice::ReadOnly)) - { - string tmp = "Could not open file: " + filename.toStdString(); - throw runtime_error( tmp.c_str() ); - } - - if( !doc_->setContent(&file) ) - { - file.close(); - string tmp = "Could not read content from file: " + - filename.toStdString() + - " Probably some syntax error in the xml file"; - throw runtime_error( tmp.c_str() ); - } - file.close(); - - // initialize all commands in the command file - initializeCommands(); - } - - CommandCompletion *CommandCompletion::instance_ = 0; - - /* - * \author Anders Fernström - * \date 2005-12-12 - * - * \brief Instance the CommandCompetion object. - * - * \param filename The file that will be read. - * \return The CommandCompetion object - */ - CommandCompletion *CommandCompletion::instance( const QString filename ) - { - if( !instance_ ) - instance_ = new CommandCompletion( filename ); - - return instance_; - } - - /* - * \author Anders Fernström - * \date 2005-12-12 - * \date 2005-12-15 (update) - * - * \brief Insert a command into the text, if the text match a command - * - * 2005-12-15 AF, implemented function - * - * \param cursor The text cursor to the text where the command should - * be inserted - * \return TURE if a command is inserted - */ - bool CommandCompletion::insertCommand( QTextCursor &cursor ) - { - // check if cursor is okej - if( !cursor.isNull() ) - { - // first remove any old currentList_ - if( currentList_ ) - { - delete currentList_; - currentList_ = 0; - } - - // reset currentCommand_ && currentField_ - currentCommand_ = -1; - currentField_ = -1; - - // find current word in text - cursor.movePosition( QTextCursor::StartOfWord, QTextCursor::KeepAnchor ); - QString command = cursor.selectedText(); - - if( !command.isNull() && !command.isEmpty() ) - { - // check if any comman match the current word in the text - currentList_ = new QStringList(); - for( int i = 0; i < commandList_.size(); ++i ) - { - if( 0 == commandList_.at(i).indexOf( command, 0, Qt::CaseInsensitive )) - currentList_->append( commandList_.at(i) ); - } - - //cout << "Found commands (" << command.toStdString() << "):" << endl; - //for( int i = 0; i < currentList_->size(); ++i ) - // cout << " >" << currentList_->at(i).toStdString() << endl; - - // found one or more commands that match the word - if( currentList_->size() > 0 ) - { - currentCommand_ = 0; - - commandStartPos_ = cursor.position(); - cursor.insertText( currentList_->at( currentCommand_ )); - commandEndPos_ = cursor.position(); - - // select first field, if any - nextField( cursor ); - - return true; - } - else - { - delete currentList_; - currentList_ = 0; - } - } - } - - return false; - } - - /* - * \author Anders Fernström - * \date 2005-12-12 - * - * \brief Insert the next possible command into the text, that match - * a command - * - * \param cursor The text cursor to the text where the command should - * be inserted - * \return TURE if a command is inserted - */ - bool CommandCompletion::nextCommand( QTextCursor &cursor ) - { - // check if cursor is okej - if( !cursor.isNull() ) - { - // check if currentList_ exists - if( currentCommand_ >= 0 && currentList_ ) - { - // if no more commands existes, restart - if( currentCommand_ >= (currentList_->size()-1) ) - currentCommand_ = -1; - - // reset currentField_ - currentField_ = -1; - - //next command - currentCommand_++; - cursor.setPosition( commandStartPos_ ); - cursor.setPosition( commandEndPos_, QTextCursor::KeepAnchor ); - cursor.insertText( currentList_->at( currentCommand_ )); - commandEndPos_ = cursor.position(); - - // select first field, if any - nextField( cursor ); - - return true; - } - } - - return false; - } - - /* - * \author Anders Fernström - * \date 2005-12-12 - * - * \brief Returns the help text to the current command - * - * \return Helpt text to current command - */ - QString CommandCompletion::helpCommand() - { - if( currentCommand_ >= 0 ) - { - if( currentList_->size() > currentCommand_ ) - { - QString command = currentList_->at( currentCommand_ ); - if( commands_.contains( command )) - return commands_[command]->helptext(); - } - } - - return QString::null; - } - - /* - * \author Anders Fernström - * \date 2005-12-12 - * \date 2005-12-15 (update) - * - * \brief Select next (if any) field in current command - * - * 2005-12-15 AF, implemented function - * - * \return TURE if a field is selected - */ - bool CommandCompletion::nextField( QTextCursor &cursor ) - { - // check if cursor is okej - if( !cursor.isNull() ) - { - if( currentCommand_ >= 0 && currentCommand_ < currentList_->size() ) - { - QString command = currentList_->at( currentCommand_ ); - - if( commands_.contains( command )) - { - if( currentField_ < (commands_[command]->numbersField() - 1) ) - { - //next field - currentField_++; - QString fieldID; - fieldID.setNum( currentField_ ); - fieldID = "$" + fieldID; - QString field = commands_[command]->datafield( fieldID ); - - if( !field.isNull() ) - { - // get text in editor - cursor.setPosition( commandStartPos_ ); - cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor ); - QString text = cursor.selectedText(); - - int pos = text.indexOf( field, 0 ); - if( pos >= 0 ) - { - // select field - cursor.setPosition( commandStartPos_ + pos ); - cursor.setPosition( commandStartPos_ + pos + field.size(), QTextCursor::KeepAnchor ); - return true; - } - } - } - } - } - } - - return false; - } - - /*! - * \example from commands.xml - * - * - * modelname - * <Real> - * <Real> - * <Integer> - * Translates a model and simulates it. Ex: simulate(dcmotor). Ex: simulate(dcmotor,startTime=0, stopTime=10, numberOfIntervals=1000). - * - * - */ - - /* - * \author Anders Fernström - * \date 2005-12-12 - * - * \brief loop through the DOM tree and creates CommandUnit after - * specified commands. - */ - void CommandCompletion::initializeCommands() - { - QDomElement root = doc_->documentElement(); - QDomNode node = root.firstChild(); - - // loop through the DOM tree - while( !node.isNull() ) - { - QDomElement element = node.toElement(); - if( !element.isNull() ) - { - if( element.tagName() == "command" ) - { - CommandUnit *unit = new CommandUnit( element.attribute( "name" )); - QDomNode n = element.firstChild(); - parseCommand( n, unit ); - - commands_.insert( unit->fullName(), unit ); - commandList_.append( unit->fullName() ); - } - } - node = node.nextSibling(); - } - } - - /* - * \author Anders Fernström - * \date 2005-12-12 - * - * \brief parse through a command tag in the DOM tree - */ - void CommandCompletion::parseCommand( QDomNode node, CommandUnit *item ) const - { - if( !item ) - throw runtime_error( "ParseCommand... No ITEM set" ); - - while( !node.isNull() ) - { - QDomElement element = node.toElement(); - - if( element.tagName() == "field" ) - item->addDataField( element.attribute( "name" ), element.text() ); - else if( element.tagName() == "helptext" ) - item->setHelptext( element.text() ); - else - cout << "Tag not known" << element.tagName().toStdString(); - - node = node.nextSibling(); - } - } + /*! + * \class CommandCompletion + * \author Anders Fernström + * \date 2005-12-12 + * + * \brief Reads a command file and creates omc command object for + * commandcompetion in inputcells + */ + + /*! + * \author Anders Fernström + * \date 2005-12-12 + * + * \brief The class constructor + * + * \brief Reads a given file and construct a DOM tree from that file. + * If the file is corrupt a exception will be throwed. + * + * \param filename The file that will be read. + */ + CommandCompletion::CommandCompletion( const QString filename ) + : currentCommand_( -1 ), + currentField_( -1 ), + currentList_( 0 ), + commandStartPos_( 0 ), + commandEndPos_( 0 ) + { + //read a command file. + doc_ = new QDomDocument( "OMCCommand" ); + + QFile file( filename ); + if(!file.open(QIODevice::ReadOnly)) + { + string tmp = "Could not open file: " + filename.toStdString(); + throw runtime_error( tmp.c_str() ); + } + + if( !doc_->setContent(&file) ) + { + file.close(); + string tmp = "Could not read content from file: " + + filename.toStdString() + + " Probably some syntax error in the xml file"; + throw runtime_error( tmp.c_str() ); + } + file.close(); + + // initialize all commands in the command file + initializeCommands(); + } + + CommandCompletion *CommandCompletion::instance_ = 0; + + /* + * \author Anders Fernström + * \date 2005-12-12 + * + * \brief Instance the CommandCompetion object. + * + * \param filename The file that will be read. + * \return The CommandCompetion object + */ + CommandCompletion *CommandCompletion::instance( const QString filename ) + { + if( !instance_ ) + instance_ = new CommandCompletion( filename ); + + return instance_; + } + + /* + * \author Anders Fernström + * \date 2005-12-12 + * \date 2005-12-15 (update) + * + * \brief Insert a command into the text, if the text match a command + * + * 2005-12-15 AF, implemented function + * + * \param cursor The text cursor to the text where the command should + * be inserted + * \return TURE if a command is inserted + */ + bool CommandCompletion::insertCommand( QTextCursor &cursor ) + { + // check if cursor is okej + if( !cursor.isNull() ) + { + // first remove any old currentList_ + if( currentList_ ) + { + delete currentList_; + currentList_ = 0; + } + + // reset currentCommand_ && currentField_ + currentCommand_ = -1; + currentField_ = -1; + + // find current word in text + cursor.movePosition( QTextCursor::StartOfWord, QTextCursor::KeepAnchor ); + QString command = cursor.selectedText(); + + if( !command.isNull() && !command.isEmpty() ) + { + // check if any comman match the current word in the text + currentList_ = new QStringList(); + for( int i = 0; i < commandList_.size(); ++i ) + { + if( 0 == commandList_.at(i).indexOf( command, 0, Qt::CaseInsensitive )) + currentList_->append( commandList_.at(i) ); + } + + //cout << "Found commands (" << command.toStdString() << "):" << endl; + //for( int i = 0; i < currentList_->size(); ++i ) + // cout << " >" << currentList_->at(i).toStdString() << endl; + + // found one or more commands that match the word + if( currentList_->size() > 0 ) + { + currentCommand_ = 0; + + commandStartPos_ = cursor.position(); + cursor.insertText( currentList_->at( currentCommand_ )); + commandEndPos_ = cursor.position(); + + // select first field, if any + nextField( cursor ); + + return true; + } + else + { + delete currentList_; + currentList_ = 0; + } + } + } + + return false; + } + + /* + * \author Anders Fernström + * \date 2005-12-12 + * + * \brief Insert the next possible command into the text, that match + * a command + * + * \param cursor The text cursor to the text where the command should + * be inserted + * \return TURE if a command is inserted + */ + bool CommandCompletion::nextCommand( QTextCursor &cursor ) + { + // check if cursor is okej + if( !cursor.isNull() ) + { + // check if currentList_ exists + if( currentCommand_ >= 0 && currentList_ ) + { + // if no more commands existes, restart + if( currentCommand_ >= (currentList_->size()-1) ) + currentCommand_ = -1; + + // reset currentField_ + currentField_ = -1; + + //next command + currentCommand_++; + cursor.setPosition( commandStartPos_ ); + cursor.setPosition( commandEndPos_, QTextCursor::KeepAnchor ); + cursor.insertText( currentList_->at( currentCommand_ )); + commandEndPos_ = cursor.position(); + + // select first field, if any + nextField( cursor ); + + return true; + } + } + + return false; + } + + /* + * \author Anders Fernström + * \date 2005-12-12 + * + * \brief Returns the help text to the current command + * + * \return Helpt text to current command + */ + QString CommandCompletion::helpCommand() + { + if( currentCommand_ >= 0 ) + { + if( currentList_->size() > currentCommand_ ) + { + QString command = currentList_->at( currentCommand_ ); + if( commands_.contains( command )) + return commands_[command]->helptext(); + } + } + + return QString::null; + } + + /* + * \author Anders Fernström + * \date 2005-12-12 + * \date 2005-12-15 (update) + * + * \brief Select next (if any) field in current command + * + * 2005-12-15 AF, implemented function + * + * \return TURE if a field is selected + */ + bool CommandCompletion::nextField( QTextCursor &cursor ) + { + // check if cursor is okej + if( !cursor.isNull() ) + { + if( currentCommand_ >= 0 && currentCommand_ < currentList_->size() ) + { + QString command = currentList_->at( currentCommand_ ); + + if( commands_.contains( command )) + { + if( currentField_ < (commands_[command]->numbersField() - 1) ) + { + //next field + currentField_++; + QString fieldID; + fieldID.setNum( currentField_ ); + fieldID = "$" + fieldID; + QString field = commands_[command]->datafield( fieldID ); + + if( !field.isNull() ) + { + // get text in editor + cursor.setPosition( commandStartPos_ ); + cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor ); + QString text = cursor.selectedText(); + + int pos = text.indexOf( field, 0 ); + if( pos >= 0 ) + { + // select field + cursor.setPosition( commandStartPos_ + pos ); + cursor.setPosition( commandStartPos_ + pos + field.size(), QTextCursor::KeepAnchor ); + return true; + } + } + } + } + } + } + + return false; + } + + /*! + * \example from commands.xml + * + * + * modelname + * <Real> + * <Real> + * <Integer> + * Translates a model and simulates it. Ex: simulate(dcmotor). Ex: simulate(dcmotor,startTime=0, stopTime=10, numberOfIntervals=1000). + * + * + */ + + /* + * \author Anders Fernström + * \date 2005-12-12 + * + * \brief loop through the DOM tree and creates CommandUnit after + * specified commands. + */ + void CommandCompletion::initializeCommands() + { + QDomElement root = doc_->documentElement(); + QDomNode node = root.firstChild(); + + // loop through the DOM tree + while( !node.isNull() ) + { + QDomElement element = node.toElement(); + if( !element.isNull() ) + { + if( element.tagName() == "command" ) + { + CommandUnit *unit = new CommandUnit( element.attribute( "name" )); + QDomNode n = element.firstChild(); + parseCommand( n, unit ); + + commands_.insert( unit->fullName(), unit ); + commandList_.append( unit->fullName() ); + } + } + node = node.nextSibling(); + } + } + + /* + * \author Anders Fernström + * \date 2005-12-12 + * + * \brief parse through a command tag in the DOM tree + */ + void CommandCompletion::parseCommand( QDomNode node, CommandUnit *item ) const + { + if( !item ) + throw runtime_error( "ParseCommand... No ITEM set" ); + + while( !node.isNull() ) + { + QDomElement element = node.toElement(); + + if( element.tagName() == "field" ) + item->addDataField( element.attribute( "name" ), element.text() ); + else if( element.tagName() == "helptext" ) + item->setHelptext( element.text() ); + else + cout << "Tag not known" << element.tagName().toStdString(); + + node = node.nextSibling(); + } + } } diff --git a/OMNotebook/OMNotebookQT4/commandcompletion.h b/OMNotebook/OMNotebookQT4/commandcompletion.h index aeadca045d5..b7a911051ec 100644 --- a/OMNotebook/OMNotebookQT4/commandcompletion.h +++ b/OMNotebook/OMNotebookQT4/commandcompletion.h @@ -54,34 +54,34 @@ namespace IAEX { - class CommandCompletion : public QObject - { - Q_OBJECT + class CommandCompletion : public QObject + { + Q_OBJECT - public: - static CommandCompletion *instance( const QString filename ); - bool insertCommand( QTextCursor &cursor ); - bool nextCommand( QTextCursor &cursor ); - QString helpCommand(); - bool nextField( QTextCursor &cursor ); + public: + static CommandCompletion *instance( const QString filename ); + bool insertCommand( QTextCursor &cursor ); + bool nextCommand( QTextCursor &cursor ); + QString helpCommand(); + bool nextField( QTextCursor &cursor ); - private: - void initializeCommands(); - void parseCommand(QDomNode node, CommandUnit *item) const; - CommandCompletion( const QString filename ); + private: + void initializeCommands(); + void parseCommand(QDomNode node, CommandUnit *item) const; + CommandCompletion( const QString filename ); - static CommandCompletion *instance_; - QDomDocument *doc_; + static CommandCompletion *instance_; + QDomDocument *doc_; - int currentCommand_; - int currentField_; - int commandStartPos_; - int commandEndPos_; + int currentCommand_; + int currentField_; + int commandStartPos_; + int commandEndPos_; - QStringList *currentList_; - QStringList commandList_; + QStringList *currentList_; + QStringList commandList_; QHash commands_; - }; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/commandunit.h b/OMNotebook/OMNotebookQT4/commandunit.h index 46aee20db91..f3454212156 100644 --- a/OMNotebook/OMNotebookQT4/commandunit.h +++ b/OMNotebook/OMNotebookQT4/commandunit.h @@ -47,54 +47,54 @@ namespace IAEX { - /*! - * \class CommandUnit - * \author Anders Fernström - * \date 2005-12-12 - * - * \brief A class that store an omc command - */ - class CommandUnit - { - public: - CommandUnit( QString name ) : name_(name){} - virtual ~CommandUnit(){} + /*! + * \class CommandUnit + * \author Anders Fernström + * \date 2005-12-12 + * + * \brief A class that store an omc command + */ + class CommandUnit + { + public: + CommandUnit( QString name ) : name_(name){} + virtual ~CommandUnit(){} - QString name(){ return name_; } - QString fullName() - { - QString tmp = name_; - QHash::iterator d_iter = datafields_.begin(); - while( d_iter != datafields_.end() ) - { - tmp.replace( d_iter.key(), d_iter.value() ); - ++d_iter; - } + QString name(){ return name_; } + QString fullName() + { + QString tmp = name_; + QHash::iterator d_iter = datafields_.begin(); + while( d_iter != datafields_.end() ) + { + tmp.replace( d_iter.key(), d_iter.value() ); + ++d_iter; + } - return tmp; - } - QString helptext(){ return helptext_; } + return tmp; + } + QString helptext(){ return helptext_; } - int numbersField(){ return datafields_.size(); } - QString datafield( QString fieldID ) - { - if( datafields_.contains( fieldID )) - return datafields_[fieldID]; - else - return QString::null; - } - void addDataField( QString fieldID, QString data ) - { - datafields_[fieldID] = data; - } + int numbersField(){ return datafields_.size(); } + QString datafield( QString fieldID ) + { + if( datafields_.contains( fieldID )) + return datafields_[fieldID]; + else + return QString::null; + } + void addDataField( QString fieldID, QString data ) + { + datafields_[fieldID] = data; + } - void setHelptext( QString text ){ helptext_ = text; } + void setHelptext( QString text ){ helptext_ = text; } - private: - QString name_; - QHash datafields_; - QString helptext_; - }; + private: + QString name_; + QHash datafields_; + QString helptext_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/cursorcommands.h b/OMNotebook/OMNotebookQT4/cursorcommands.h index c01cfa2b5ea..6d5a3436c34 100644 --- a/OMNotebook/OMNotebookQT4/cursorcommands.h +++ b/OMNotebook/OMNotebookQT4/cursorcommands.h @@ -46,169 +46,169 @@ using namespace std; namespace IAEX { - /*! \class CursorMoveUpCommand - * - * \brief Moves the cursor up one step. - */ - class CursorMoveUpCommand : public Command - { - public: - CursorMoveUpCommand(){} - virtual ~CursorMoveUpCommand(){} - void execute() - { - try - { - CellCursor *cursor = document()->getCursor(); - - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(true); - cursor->currentCell()->child()->setFocus(false); - } - } - else - { - cursor->currentCell()->setReadOnly(true); - cursor->currentCell()->setFocus(false); - } - - cursor->moveUp(); - - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(false); - cursor->currentCell()->child()->setFocus(true); - } - } - else - { - cursor->currentCell()->setReadOnly(false); - cursor->currentCell()->setFocus(true); - } - } - catch(exception &e) - { - // 2006-01-30 AF, add exception - string str = string("CursorMoveUpCommand(), Exception: ") + e.what(); - throw runtime_error( str.c_str() ); - } - } - }; - - /*! \class CursorMoveDownCommand - * - * \brief Moves the cursor down one step. - */ - class CursorMoveDownCommand : public Command - { - public: - CursorMoveDownCommand(){} - virtual ~CursorMoveDownCommand(){} - void execute() - { - try - { - CellCursor *cursor = document()->getCursor(); - - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(true); - cursor->currentCell()->child()->setFocus(false); - } - } - else - { - cursor->currentCell()->setReadOnly(true); - cursor->currentCell()->setFocus(false); - } - - cursor->moveDown(); - - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(false); - cursor->currentCell()->child()->setFocus(true); - } - } - else - { - cursor->currentCell()->setReadOnly(false); - cursor->currentCell()->setFocus(true); - } - } - catch(exception &e) - { - // 2006-01-30 AF, add exception - string str = string("CursorMoveDownCommand(), Exception: ") + e.what(); - throw runtime_error( str.c_str() ); - } - } - }; - - /*! \class CursorMoveAfterCommand - * - * \brief Moves the cursor after a specific cell. - */ - class CursorMoveAfterCommand : public Command - { - public: - CursorMoveAfterCommand(Cell *cell):cell_(cell){} - virtual ~CursorMoveAfterCommand(){} - void execute() - { - try - { - CellCursor *cursor = document()->getCursor(); - - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(true); - cursor->currentCell()->child()->setFocus(false); - } - } - else - { - cursor->currentCell()->setReadOnly(true); - cursor->currentCell()->setFocus(false); - } - - cursor->moveAfter(cell_); - - if(cursor->currentCell()->isClosed()) - { - if(cursor->currentCell()->hasChilds()) - { - cursor->currentCell()->child()->setReadOnly(false); - cursor->currentCell()->child()->setFocus(true); - } - } - else - { - cursor->currentCell()->setReadOnly(false); - cursor->currentCell()->setFocus(true); - } - - } - catch(exception &e) - { - // 2006-01-30 AF, add exception - string str = string("CursorMoveAfterCommand(), Exception: ") + e.what(); - throw runtime_error( str.c_str() ); - } - } - private: - Cell *cell_; - }; + /*! \class CursorMoveUpCommand + * + * \brief Moves the cursor up one step. + */ + class CursorMoveUpCommand : public Command + { + public: + CursorMoveUpCommand(){} + virtual ~CursorMoveUpCommand(){} + void execute() + { + try + { + CellCursor *cursor = document()->getCursor(); + + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(true); + cursor->currentCell()->child()->setFocus(false); + } + } + else + { + cursor->currentCell()->setReadOnly(true); + cursor->currentCell()->setFocus(false); + } + + cursor->moveUp(); + + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(false); + cursor->currentCell()->child()->setFocus(true); + } + } + else + { + cursor->currentCell()->setReadOnly(false); + cursor->currentCell()->setFocus(true); + } + } + catch(exception &e) + { + // 2006-01-30 AF, add exception + string str = string("CursorMoveUpCommand(), Exception: ") + e.what(); + throw runtime_error( str.c_str() ); + } + } + }; + + /*! \class CursorMoveDownCommand + * + * \brief Moves the cursor down one step. + */ + class CursorMoveDownCommand : public Command + { + public: + CursorMoveDownCommand(){} + virtual ~CursorMoveDownCommand(){} + void execute() + { + try + { + CellCursor *cursor = document()->getCursor(); + + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(true); + cursor->currentCell()->child()->setFocus(false); + } + } + else + { + cursor->currentCell()->setReadOnly(true); + cursor->currentCell()->setFocus(false); + } + + cursor->moveDown(); + + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(false); + cursor->currentCell()->child()->setFocus(true); + } + } + else + { + cursor->currentCell()->setReadOnly(false); + cursor->currentCell()->setFocus(true); + } + } + catch(exception &e) + { + // 2006-01-30 AF, add exception + string str = string("CursorMoveDownCommand(), Exception: ") + e.what(); + throw runtime_error( str.c_str() ); + } + } + }; + + /*! \class CursorMoveAfterCommand + * + * \brief Moves the cursor after a specific cell. + */ + class CursorMoveAfterCommand : public Command + { + public: + CursorMoveAfterCommand(Cell *cell):cell_(cell){} + virtual ~CursorMoveAfterCommand(){} + void execute() + { + try + { + CellCursor *cursor = document()->getCursor(); + + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(true); + cursor->currentCell()->child()->setFocus(false); + } + } + else + { + cursor->currentCell()->setReadOnly(true); + cursor->currentCell()->setFocus(false); + } + + cursor->moveAfter(cell_); + + if(cursor->currentCell()->isClosed()) + { + if(cursor->currentCell()->hasChilds()) + { + cursor->currentCell()->child()->setReadOnly(false); + cursor->currentCell()->child()->setFocus(true); + } + } + else + { + cursor->currentCell()->setReadOnly(false); + cursor->currentCell()->setFocus(true); + } + + } + catch(exception &e) + { + // 2006-01-30 AF, add exception + string str = string("CursorMoveAfterCommand(), Exception: ") + e.what(); + throw runtime_error( str.c_str() ); + } + } + private: + Cell *cell_; + }; }; #endif diff --git a/OMNotebook/OMNotebookQT4/cursorposvisitor.h b/OMNotebook/OMNotebookQT4/cursorposvisitor.h index ffec0cb6982..b5d88219efc 100644 --- a/OMNotebook/OMNotebookQT4/cursorposvisitor.h +++ b/OMNotebook/OMNotebookQT4/cursorposvisitor.h @@ -51,76 +51,76 @@ using namespace std; namespace IAEX { - class CursorPosVisitor : public Visitor - { + class CursorPosVisitor : public Visitor + { - public: - CursorPosVisitor() - : count_(true), closed_(false), position_(0), closedCell_(0) - {} - virtual ~CursorPosVisitor(){} - virtual int position(){ return position_; } + public: + CursorPosVisitor() + : count_(true), closed_(false), position_(0), closedCell_(0) + {} + virtual ~CursorPosVisitor(){} + virtual int position(){ return position_; } - virtual void visitCellNodeBefore(Cell *node){} - virtual void visitCellNodeAfter(Cell *node){} + virtual void visitCellNodeBefore(Cell *node){} + virtual void visitCellNodeAfter(Cell *node){} - virtual void visitCellGroupNodeBefore(CellGroup *node) - { - if( count_ ) - if( node->isClosed() ) - { - closed_ = true; - closedCell_ = node; - } - } - virtual void visitCellGroupNodeAfter(CellGroup *node) - { - if( count_ ) - { - if( closed_ && closedCell_ == node ) - { - position_ += node->height(); - closed_ = false; - closedCell_ = 0; - } - } - } + virtual void visitCellGroupNodeBefore(CellGroup *node) + { + if( count_ ) + if( node->isClosed() ) + { + closed_ = true; + closedCell_ = node; + } + } + virtual void visitCellGroupNodeAfter(CellGroup *node) + { + if( count_ ) + { + if( closed_ && closedCell_ == node ) + { + position_ += node->height(); + closed_ = false; + closedCell_ = 0; + } + } + } - virtual void visitTextCellNodeBefore(TextCell *node){} - virtual void visitTextCellNodeAfter(TextCell *node) - { - if( count_ && !closed_ ) - position_ += node->height(); - } + virtual void visitTextCellNodeBefore(TextCell *node){} + virtual void visitTextCellNodeAfter(TextCell *node) + { + if( count_ && !closed_ ) + position_ += node->height(); + } - virtual void visitGraphCellNodeBefore(GraphCell *node) {} - virtual void visitGraphCellNodeAfter(GraphCell *node) - { - if( count_ && !closed_ ) - position_ += node->height(); - } + virtual void visitGraphCellNodeBefore(GraphCell *node) {} + virtual void visitGraphCellNodeAfter(GraphCell *node) + { + if( count_ && !closed_ ) + position_ += node->height(); + } - virtual void visitInputCellNodeBefore(InputCell *node){} - virtual void visitInputCellNodeAfter(InputCell *node) - { - if( count_ && !closed_ ) - position_ += node->height(); - } + virtual void visitInputCellNodeBefore(InputCell *node){} + virtual void visitInputCellNodeAfter(InputCell *node) + { + if( count_ && !closed_ ) + position_ += node->height(); + } - virtual void visitCellCursorNodeBefore(CellCursor *cursor){} - virtual void visitCellCursorNodeAfter(CellCursor *cursor) - { - if( count_ && !closed_ ) - position_ += cursor->height(); + virtual void visitCellCursorNodeBefore(CellCursor *cursor){} + virtual void visitCellCursorNodeAfter(CellCursor *cursor) + { + if( count_ && !closed_ ) + position_ += cursor->height(); - count_ = false; - } + count_ = false; + } - private: - bool count_; - bool closed_; - int position_; - CellGroup *closedCell_; - }; + private: + bool count_; + bool closed_; + int position_; + CellGroup *closedCell_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/document.h b/OMNotebook/OMNotebookQT4/document.h index eea9684ee3b..32ee64fce12 100644 --- a/OMNotebook/OMNotebookQT4/document.h +++ b/OMNotebook/OMNotebookQT4/document.h @@ -63,117 +63,117 @@ using namespace std; namespace IAEX { - //Forward declaration - class CellApplication; - class Cell; - class Command; - class DocumentView; - class Factory; - class Visitor; - - /*! - *\interface Document - * - * \brief Describes all operations that is needed by a document. - * - * The Document interface describes all methods that must be - * implemented by a concrete document class. - */ - class Document : public QObject - { - Q_OBJECT - - public: - //Application - virtual CellApplication *application() = 0; - - //State - virtual bool hasChanged() const = 0; - virtual bool isOpen() const = 0; - virtual bool isSaved() const = 0; // AF - virtual bool isEmpty() const = 0; // Added 2006-08-24 AF - - //File operations - virtual void open( const QString filename, int readmode ) = 0; - virtual void close() = 0; - virtual QString getFilename() = 0; - virtual void setFilename( QString filename ) = 0; //AF - virtual void setSaved( bool saved ) = 0; //AF - virtual void setChanged( bool changed ) = 0; // Added 2006-01-17 AF - virtual void hoverOverUrl( const QUrl &link ) = 0; // Added 2006-02-10 AF - - //Cursor operations - virtual CellCursor *getCursor() = 0; - virtual void cursorStepUp() = 0; - virtual void cursorStepDown() = 0; - virtual void cursorMoveAfter(Cell *aCell, const bool open) = 0; - virtual void cursorUngroupCell() = 0; // Added 2006-04-26 AF - virtual void cursorSplitCell() = 0; // Added 2006-04-26 AF - virtual void cursorAddCell() = 0; - virtual void cursorDeleteCell() = 0; - virtual void cursorCutCell() = 0; - virtual void cursorCopyCell() = 0; - virtual void cursorPasteCell() = 0; - virtual void cursorChangeStyle(CellStyle style) = 0; // Changed 2005-10-28 AF - - //TextCursor operations, added 2006-02-07 AF - virtual void textcursorCutText() = 0; - virtual void textcursorCopyText() = 0; - virtual void textcursorPasteText() = 0; - //TextCursor operations, added 2005-11-03 AF - virtual void textcursorChangeFontFamily( QString family ) = 0; - virtual void textcursorChangeFontFace( int face ) = 0; - virtual void textcursorChangeFontSize( int size ) = 0; - virtual void textcursorChangeFontStretch( int stretch ) = 0; - virtual void textcursorChangeFontColor( QColor color ) = 0; - virtual void textcursorChangeTextAlignment( int alignment ) = 0; - virtual void textcursorChangeVerticalAlignment( int alignment ) = 0; - virtual void textcursorChangeMargin( int margin ) = 0; - virtual void textcursorChangePadding( int padding ) = 0; - virtual void textcursorChangeBorder( int border ) = 0; - - // Added 2005-11-17 AF, Image operations - virtual void textcursorInsertImage( QString filepath, QSize size ) = 0; - virtual QString addImage( QImage *image ) = 0; - virtual QImage *getImage( QString name ) = 0; - - // Added 2005-12-05 AF, Link operations - virtual void textcursorInsertLink( QString filepath, QTextCursor& cursor ) = 0; - - //Utility operations - virtual Factory *cellFactory() = 0; - virtual Cell* getMainCell() = 0; // Added 2006-08-24 AF - virtual vector getSelection() = 0; - virtual void clearSelection() = 0; - - //command operations - virtual void executeCommand(Command *cmd) = 0; - - //Observer interface - virtual void attach(DocumentView *d) = 0; - virtual void detach(DocumentView *d) = 0; - virtual void notify() = 0; - virtual QFrame *getState() = 0; - - //Visitor Initializations - virtual void runVisitor(Visitor &v) = 0; - - virtual void setAutoIndent2(bool) = 0; - - public slots: - virtual void updateScrollArea() = 0; // Added 2005-11-28 AF + //Forward declaration + class CellApplication; + class Cell; + class Command; + class DocumentView; + class Factory; + class Visitor; + + /*! + *\interface Document + * + * \brief Describes all operations that is needed by a document. + * + * The Document interface describes all methods that must be + * implemented by a concrete document class. + */ + class Document : public QObject + { + Q_OBJECT + + public: + //Application + virtual CellApplication *application() = 0; + + //State + virtual bool hasChanged() const = 0; + virtual bool isOpen() const = 0; + virtual bool isSaved() const = 0; // AF + virtual bool isEmpty() const = 0; // Added 2006-08-24 AF + + //File operations + virtual void open( const QString filename, int readmode ) = 0; + virtual void close() = 0; + virtual QString getFilename() = 0; + virtual void setFilename( QString filename ) = 0; //AF + virtual void setSaved( bool saved ) = 0; //AF + virtual void setChanged( bool changed ) = 0; // Added 2006-01-17 AF + virtual void hoverOverUrl( const QUrl &link ) = 0; // Added 2006-02-10 AF + + //Cursor operations + virtual CellCursor *getCursor() = 0; + virtual void cursorStepUp() = 0; + virtual void cursorStepDown() = 0; + virtual void cursorMoveAfter(Cell *aCell, const bool open) = 0; + virtual void cursorUngroupCell() = 0; // Added 2006-04-26 AF + virtual void cursorSplitCell() = 0; // Added 2006-04-26 AF + virtual void cursorAddCell() = 0; + virtual void cursorDeleteCell() = 0; + virtual void cursorCutCell() = 0; + virtual void cursorCopyCell() = 0; + virtual void cursorPasteCell() = 0; + virtual void cursorChangeStyle(CellStyle style) = 0; // Changed 2005-10-28 AF + + //TextCursor operations, added 2006-02-07 AF + virtual void textcursorCutText() = 0; + virtual void textcursorCopyText() = 0; + virtual void textcursorPasteText() = 0; + //TextCursor operations, added 2005-11-03 AF + virtual void textcursorChangeFontFamily( QString family ) = 0; + virtual void textcursorChangeFontFace( int face ) = 0; + virtual void textcursorChangeFontSize( int size ) = 0; + virtual void textcursorChangeFontStretch( int stretch ) = 0; + virtual void textcursorChangeFontColor( QColor color ) = 0; + virtual void textcursorChangeTextAlignment( int alignment ) = 0; + virtual void textcursorChangeVerticalAlignment( int alignment ) = 0; + virtual void textcursorChangeMargin( int margin ) = 0; + virtual void textcursorChangePadding( int padding ) = 0; + virtual void textcursorChangeBorder( int border ) = 0; + + // Added 2005-11-17 AF, Image operations + virtual void textcursorInsertImage( QString filepath, QSize size ) = 0; + virtual QString addImage( QImage *image ) = 0; + virtual QImage *getImage( QString name ) = 0; + + // Added 2005-12-05 AF, Link operations + virtual void textcursorInsertLink( QString filepath, QTextCursor& cursor ) = 0; + + //Utility operations + virtual Factory *cellFactory() = 0; + virtual Cell* getMainCell() = 0; // Added 2006-08-24 AF + virtual vector getSelection() = 0; + virtual void clearSelection() = 0; + + //command operations + virtual void executeCommand(Command *cmd) = 0; + + //Observer interface + virtual void attach(DocumentView *d) = 0; + virtual void detach(DocumentView *d) = 0; + virtual void notify() = 0; + virtual QFrame *getState() = 0; + + //Visitor Initializations + virtual void runVisitor(Visitor &v) = 0; + + virtual void setAutoIndent2(bool) = 0; + + public slots: + virtual void updateScrollArea() = 0; // Added 2005-11-28 AF signals: - virtual void copyAvailable(bool) = 0; - virtual void undoAvailable(bool) = 0; - virtual void redoAvailable(bool) = 0; + virtual void copyAvailable(bool) = 0; + virtual void undoAvailable(bool) = 0; + virtual void redoAvailable(bool) = 0; - virtual void updatePos(int, int) = 0; - virtual void newState(QString) = 0; - virtual void setStatusMenu(QList) = 0; + virtual void updatePos(int, int) = 0; + virtual void newState(QString) = 0; + virtual void setStatusMenu(QList) = 0; - }; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/documentview.h b/OMNotebook/OMNotebookQT4/documentview.h index cc82c560b48..f2479efe1ad 100644 --- a/OMNotebook/OMNotebookQT4/documentview.h +++ b/OMNotebook/OMNotebookQT4/documentview.h @@ -50,20 +50,20 @@ namespace IAEX * * Base interface for document views. * - * 2005-10-11 AF, Porting, changed from q3mainwindow to mainwindow - * 2005-11-02 AF, Porting, changed Qt::WDestructiveClose in QMainWindow() - * to setAttribute(Qt::WA_DeleteOnClose); inside QMainWindow(). + * 2005-10-11 AF, Porting, changed from q3mainwindow to mainwindow + * 2005-11-02 AF, Porting, changed Qt::WDestructiveClose in QMainWindow() + * to setAttribute(Qt::WA_DeleteOnClose); inside QMainWindow(). */ class DocumentView : public QMainWindow { Q_OBJECT public: DocumentView(QWidget *parent=0) - : QMainWindow(parent){ setAttribute(Qt::WA_DeleteOnClose); } + : QMainWindow(parent){ setAttribute(Qt::WA_DeleteOnClose); } virtual ~DocumentView(){} virtual void update() = 0; - virtual Document* document() = 0; + virtual Document* document() = 0; }; }; diff --git a/OMNotebook/OMNotebookQT4/evalthread.cpp b/OMNotebook/OMNotebookQT4/evalthread.cpp index 21c202d5062..73d65316de8 100644 --- a/OMNotebook/OMNotebookQT4/evalthread.cpp +++ b/OMNotebook/OMNotebookQT4/evalthread.cpp @@ -50,43 +50,43 @@ EvalThread::~EvalThread() void EvalThread::exceptionInEval(exception &e) { - // 2006-0-09 AF, try to reconnect to OMC first. - try - { - delegate_->closeConnection(); - delegate_->reconnect(); - run(); - } - catch( exception &e ) - { - // unable to reconnect, ask if user want to restart omc. - QString msg = QString( e.what() ) + "\n\nUnable to reconnect with OMC. Do you want to restart OMC?"; - int result = QMessageBox::critical( 0, tr("Communication Error with OMC"), - msg, - QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No ); + // 2006-0-09 AF, try to reconnect to OMC first. + try + { + delegate_->closeConnection(); + delegate_->reconnect(); + run(); + } + catch( exception &e ) + { + // unable to reconnect, ask if user want to restart omc. + QString msg = QString( e.what() ) + "\n\nUnable to reconnect with OMC. Do you want to restart OMC?"; + int result = QMessageBox::critical( 0, tr("Communication Error with OMC"), + msg, + QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No ); - if( result == QMessageBox::Yes ) - { - delegate_->closeConnection(); - if( delegate_->startDelegate() ) - { - // 2006-03-14 AF, wait before trying to reconnect, - // give OMC time to start up - msleep(1000); - try - { - delegate_->reconnect(); - run(); - } - catch( exception &e ) - { + if( result == QMessageBox::Yes ) + { + delegate_->closeConnection(); + if( delegate_->startDelegate() ) + { + // 2006-03-14 AF, wait before trying to reconnect, + // give OMC time to start up + msleep(1000); + try + { + delegate_->reconnect(); + run(); + } + catch( exception &e ) + { e.what(); - QMessageBox::critical( 0, tr("Communication Error"), tr("Unable to communication correctlly with OMC.") ); - } - } - } - } + QMessageBox::critical( 0, tr("Communication Error"), tr("Unable to communication correctlly with OMC.") ); + } + } + } + } } QMutex evalMutex; // adrpo 2009-01-19 @@ -94,14 +94,14 @@ QMutex evalMutex; // adrpo 2009-01-19 void EvalThread::run() { evalMutex.lock(); // lock so NO other threads can enter this part! - try - { - delegate_->evalExpression(expr); - } - catch( exception &e ) - { - exceptionInEval(e); - } + try + { + delegate_->evalExpression(expr); + } + catch( exception &e ) + { + exceptionInEval(e); + } res = delegate_->getResult(); error = delegate_->getError(); evalMutex.unlock(); // unlock so other threads can enter this part! diff --git a/OMNotebook/OMNotebookQT4/evalthread.h b/OMNotebook/OMNotebookQT4/evalthread.h index 97da0802b54..225f1657697 100644 --- a/OMNotebook/OMNotebookQT4/evalthread.h +++ b/OMNotebook/OMNotebookQT4/evalthread.h @@ -44,16 +44,16 @@ extern QMutex evalMutex; // adrpo 2009-01-19 class EvalThread: public QThread { public: - EvalThread(InputCellDelegate* delegate_, QString expr, QObject * parent = 0); - ~EvalThread(); - void run(); - void exceptionInEval(exception &e); + EvalThread(InputCellDelegate* delegate_, QString expr, QObject * parent = 0); + ~EvalThread(); + void run(); + void exceptionInEval(exception &e); QString getResult() { return res; } QString getError() { return error; } private: - InputCellDelegate* delegate_; - QString expr; + InputCellDelegate* delegate_; + QString expr; QString res; QString error; }; diff --git a/OMNotebook/OMNotebookQT4/factory.h b/OMNotebook/OMNotebookQT4/factory.h index 4de0a07c56b..5030a783bd7 100644 --- a/OMNotebook/OMNotebookQT4/factory.h +++ b/OMNotebook/OMNotebookQT4/factory.h @@ -50,9 +50,9 @@ namespace IAEX virtual Cell *createCell(const QString &style, Cell *parent=0) = 0; - //Fulhack to compile on VC++ - // virtual Cell *createCell(const std::string &style, Cell *parent=0) - // { createCell(QString(style.c_str()), parent);} + //Fulhack to compile on VC++ + // virtual Cell *createCell(const std::string &style, Cell *parent=0) + // { createCell(QString(style.c_str()), parent);} }; /*! \class NullFactory diff --git a/OMNotebook/OMNotebookQT4/graphcell.cpp b/OMNotebook/OMNotebookQT4/graphcell.cpp index e0be8082c71..93a5c867320 100644 --- a/OMNotebook/OMNotebookQT4/graphcell.cpp +++ b/OMNotebook/OMNotebookQT4/graphcell.cpp @@ -298,8 +298,8 @@ namespace IAEX { stopHighlighter = false; indentText(); event->ignore(); - // QTextBrowser::keyPressEvent( event ); - // update(); + // QTextBrowser::keyPressEvent( event ); + // update(); } @@ -609,7 +609,7 @@ namespace IAEX { input_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); input_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - // input_->setContextMenuPolicy( Qt::NoContextMenu ); + // input_->setContextMenuPolicy( Qt::NoContextMenu ); QPalette palette; palette.setColor(input_->backgroundRole(), QColor(200,200,255)); @@ -717,7 +717,7 @@ namespace IAEX { QRegExp newLineEnd("^end\\b"); - // return s.count(e1) - includeNegative?(s.count(e2) + s.count(e1b)):0; + // return s.count(e1) - includeNegative?(s.count(e2) + s.count(e1b)):0; if(includeNegative) return s.count(e1) - s.count(e2) - s.count(e1b);// - s.count(lessIndented); else @@ -1046,7 +1046,7 @@ namespace IAEX { input_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); input_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); // unselect the text - QTextCursor cursor( input_->textCursor() ); + QTextCursor cursor( input_->textCursor() ); cursor.clearSelection(); input_->setTextCursor( cursor ); // 2006-03-02 AF, set chapter counter style @@ -1056,7 +1056,7 @@ namespace IAEX { QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); format.setMargin( style_.textFrameFormat()->margin() + style_.textFrameFormat()->border() + - style_.textFrameFormat()->padding() ); + style_.textFrameFormat()->padding() ); chaptercounter_->document()->rootFrame()->setFrameFormat( format ); chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); @@ -1085,7 +1085,7 @@ namespace IAEX { QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); format.setMargin( style_.textFrameFormat()->margin() + style_.textFrameFormat()->border() + - style_.textFrameFormat()->padding() ); + style_.textFrameFormat()->padding() ); chaptercounter_->document()->rootFrame()->setFrameFormat( format ); } @@ -1923,7 +1923,7 @@ namespace IAEX { */ void GraphCell::addToHighlighter() { - // QMessageBox::information(0, "uu3", "addToHighlighter"); + // QMessageBox::information(0, "uu3", "addToHighlighter"); emit textChanged(true); if( input_->toPlainText().isEmpty() ) return; @@ -1934,7 +1934,7 @@ namespace IAEX { if( dynamic_cast(input_)->isStopingHighlighter() ) return; - // QMessageBox::information(0,"uu3", "add2"); + // QMessageBox::information(0,"uu3", "add2"); HighlighterThread *thread = HighlighterThread::instance(); thread->addEditor( input_ ); diff --git a/OMNotebook/OMNotebookQT4/graphcell.h b/OMNotebook/OMNotebookQT4/graphcell.h index afc9f6738ab..2a0db737c21 100644 --- a/OMNotebook/OMNotebookQT4/graphcell.h +++ b/OMNotebook/OMNotebookQT4/graphcell.h @@ -57,185 +57,185 @@ class IndentationState; namespace IAEX { - enum graphCellStates {FINISHED, EVAL, ERROR, MODIFIED}; - - class MyTextEdit2; - class GraphCell : public Cell - { - Q_OBJECT - - public: - GraphCell(Document *doc, QWidget *parent=0); // Changed 2005-11-23 AF - virtual ~GraphCell(); - - QString text(); - QString textHtml(); // Added 2005-10-27 AF - virtual QString textOutput(); // Added 2005-11-23 AF - virtual QString textOutputHtml(); // Added 2005-11-23 AF - virtual QTextCursor textCursor(); // Added 2005-10-27 AF - virtual QTextEdit* textEdit(); // Added 2006-01-05 AF - virtual QTextEdit* textEditOutput(); // Added 2006-02-03 AF - virtual void viewExpression(const bool){} - - virtual void addCellWidgets(); - virtual void removeCellWidgets(); - -// void setDelegate(GraphCellDelegate *d); - void setDelegate(InputCellDelegate *d); - virtual void accept(Visitor &v); - virtual bool isClosed(); // Added 2006-01-17 AF - virtual bool isEditable(); - virtual bool isEvaluated(); // Added 2005-11-23 AF - virtual bool isJavaPlot(QString text = QString::null); // Added 2005-11-23 AF - virtual bool isQtPlot(QString text = QString::null); - virtual bool isVisualize(QString text = QString::null); - - - signals: - void heightChanged(); - void textChanged(); - void textChanged( bool ); - void clickedOutput( Cell* ); // Added 2006-02-03 AF - void forwardAction( int ); // Added 2006-04-27 AF - void newExpr(QString); - void updatePos(int, int); - void newState(QString); - void setStatusMenu(QList); - - public slots: - void eval(); - void command(); // Added 2005-12-15 AF - void nextCommand(); // Added 2005-12-15 AF - void nextField(); // Added 2005-12-15 AF - void clickEvent(); - void clickEventOutput(); // Added 2006-02-03 AF - void contentChanged(); - void setText(QString text); - void setTextHtml(QString html); // Added 2005-11-01 AF - virtual void setTextOutput(QString output); // Added 2005-11-23 AF - virtual void setTextOutputHtml(QString html); // Added 2005-11-23 AF - void setStyle(const QString &stylename); // Changed 2005-10-28 AF - void setStyle(CellStyle style); // Changed 2005-10-27 AF - void setChapterCounter(QString number); // Added 2006-03-02 AF - QString ChapterCounter(); // Added 2006-03-02 AF - QString ChapterCounterHtml(); // Added 2006-03-03 AF - void setReadOnly(const bool readonly); // Added 2005-11-01 AF - void setEvaluated(const bool evaluated); // Added 2006-01-16 AF - void setClosed(const bool closed, bool update = true); //Changed 2006-08-24 - virtual void setFocus(const bool focus); - virtual void setFocusOutput(const bool focus); // Added 2006-02-03 AF - void setExpr(QString); - void showVariableButton(bool); - - void delegateFinished(); - void setState(int state); - void showGraphics(); - - - protected: - void resizeEvent(QResizeEvent *event); //AF - void mouseDoubleClickEvent(QMouseEvent *); - void clear(); - - bool hasDelegate(); - InputCellDelegate *getDelegate(); - - private slots: - void addToHighlighter(); // Added 2005-12-29 AF - void charFormatChanged(const QTextCharFormat &); // Added 2006-01-17 AF - - private: - void createGraphCell(); - void createOutputCell(); - - void createCompoundWidget(); - void createChapterCounter(); - void exceptionInEval(exception &e); // Added 2006-02-02 AF - void setOutputStyle(); // Added 2006-04-21 AF - - private: - bool evaluated_; - bool closed_; - static int numEvals_; - int oldHeight_; // Added 2006-04-10 AF - - public: - MyTextEdit2* input_; - QTextBrowser *output_; - private: - QTextBrowser *chaptercounter_; - InputCellDelegate *delegate_; - QGridLayout *layout_; - Document *document_; - - public: - CompoundWidget* compoundwidget; - bool showGraph; - QPushButton* variableButton; - QTemporaryFile* imageFile; - }; - - - //*************************************************** - // 2005-12-13 AF, changed from QTextEdit to QTextBrowser (browser better when working with images) - class MyTextEdit2 : public QTextBrowser - { - Q_OBJECT - - public: - MyTextEdit2(QWidget *parent=0); - virtual ~MyTextEdit2(); - - bool isStopingHighlighter(); // Added 2006-01-16 AF - int state; - - public slots: - void goToPos(const QUrl&); - void updatePosition(); - void setModified(); - void indentText(); - bool lessIndented(QString); - void setAutoIndent(bool); - - signals: - void clickOnCell(); // Added 2005-11-01 AF - void wheelMove( QWheelEvent* ); // Added 2005-11-28 AF - void command(); // Added 2005-12-15 AF - void nextCommand(); // Added 2005-12-15 AF - void nextField(); // Added 2005-12-15 AF - void eval(); // Added 2005-12-15 AF - void forwardAction( int ); // Added 2006-04-27 AF - void updatePos(int, int); - void setState(int); - void showVariableButton(bool); - - protected: - void mousePressEvent(QMouseEvent *event); // Added 2005-11-01 AF - void wheelEvent(QWheelEvent *event); // Added 2005-11-28 AF - void keyPressEvent(QKeyEvent *event ); // Added 2005-12-15 AF - void insertFromMimeData(const QMimeData *source); // Added 2006-01-23 AF - void focusInEvent(QFocusEvent* event); - - private: - bool inCommand; // Added 2005-12-15 AF - bool stopHighlighter; // Added 2006-01-16 AF - int indentationLevel(QString, bool b=true); - bool autoIndent; - QMap indentationStates; - - }; - - class MyAction: public QAction - { - Q_OBJECT - public: - MyAction(const QString& text, QObject* parent); - public slots: - void triggered2(); - signals: - void urlClicked(const QUrl& u); - - }; + enum graphCellStates {FINISHED, EVAL, ERROR, MODIFIED}; + + class MyTextEdit2; + class GraphCell : public Cell + { + Q_OBJECT + + public: + GraphCell(Document *doc, QWidget *parent=0); // Changed 2005-11-23 AF + virtual ~GraphCell(); + + QString text(); + QString textHtml(); // Added 2005-10-27 AF + virtual QString textOutput(); // Added 2005-11-23 AF + virtual QString textOutputHtml(); // Added 2005-11-23 AF + virtual QTextCursor textCursor(); // Added 2005-10-27 AF + virtual QTextEdit* textEdit(); // Added 2006-01-05 AF + virtual QTextEdit* textEditOutput(); // Added 2006-02-03 AF + virtual void viewExpression(const bool){} + + virtual void addCellWidgets(); + virtual void removeCellWidgets(); + +// void setDelegate(GraphCellDelegate *d); + void setDelegate(InputCellDelegate *d); + virtual void accept(Visitor &v); + virtual bool isClosed(); // Added 2006-01-17 AF + virtual bool isEditable(); + virtual bool isEvaluated(); // Added 2005-11-23 AF + virtual bool isJavaPlot(QString text = QString::null); // Added 2005-11-23 AF + virtual bool isQtPlot(QString text = QString::null); + virtual bool isVisualize(QString text = QString::null); + + + signals: + void heightChanged(); + void textChanged(); + void textChanged( bool ); + void clickedOutput( Cell* ); // Added 2006-02-03 AF + void forwardAction( int ); // Added 2006-04-27 AF + void newExpr(QString); + void updatePos(int, int); + void newState(QString); + void setStatusMenu(QList); + + public slots: + void eval(); + void command(); // Added 2005-12-15 AF + void nextCommand(); // Added 2005-12-15 AF + void nextField(); // Added 2005-12-15 AF + void clickEvent(); + void clickEventOutput(); // Added 2006-02-03 AF + void contentChanged(); + void setText(QString text); + void setTextHtml(QString html); // Added 2005-11-01 AF + virtual void setTextOutput(QString output); // Added 2005-11-23 AF + virtual void setTextOutputHtml(QString html); // Added 2005-11-23 AF + void setStyle(const QString &stylename); // Changed 2005-10-28 AF + void setStyle(CellStyle style); // Changed 2005-10-27 AF + void setChapterCounter(QString number); // Added 2006-03-02 AF + QString ChapterCounter(); // Added 2006-03-02 AF + QString ChapterCounterHtml(); // Added 2006-03-03 AF + void setReadOnly(const bool readonly); // Added 2005-11-01 AF + void setEvaluated(const bool evaluated); // Added 2006-01-16 AF + void setClosed(const bool closed, bool update = true); //Changed 2006-08-24 + virtual void setFocus(const bool focus); + virtual void setFocusOutput(const bool focus); // Added 2006-02-03 AF + void setExpr(QString); + void showVariableButton(bool); + + void delegateFinished(); + void setState(int state); + void showGraphics(); + + + protected: + void resizeEvent(QResizeEvent *event); //AF + void mouseDoubleClickEvent(QMouseEvent *); + void clear(); + + bool hasDelegate(); + InputCellDelegate *getDelegate(); + + private slots: + void addToHighlighter(); // Added 2005-12-29 AF + void charFormatChanged(const QTextCharFormat &); // Added 2006-01-17 AF + + private: + void createGraphCell(); + void createOutputCell(); + + void createCompoundWidget(); + void createChapterCounter(); + void exceptionInEval(exception &e); // Added 2006-02-02 AF + void setOutputStyle(); // Added 2006-04-21 AF + + private: + bool evaluated_; + bool closed_; + static int numEvals_; + int oldHeight_; // Added 2006-04-10 AF + + public: + MyTextEdit2* input_; + QTextBrowser *output_; + private: + QTextBrowser *chaptercounter_; + InputCellDelegate *delegate_; + QGridLayout *layout_; + Document *document_; + + public: + CompoundWidget* compoundwidget; + bool showGraph; + QPushButton* variableButton; + QTemporaryFile* imageFile; + }; + + + //*************************************************** + // 2005-12-13 AF, changed from QTextEdit to QTextBrowser (browser better when working with images) + class MyTextEdit2 : public QTextBrowser + { + Q_OBJECT + + public: + MyTextEdit2(QWidget *parent=0); + virtual ~MyTextEdit2(); + + bool isStopingHighlighter(); // Added 2006-01-16 AF + int state; + + public slots: + void goToPos(const QUrl&); + void updatePosition(); + void setModified(); + void indentText(); + bool lessIndented(QString); + void setAutoIndent(bool); + + signals: + void clickOnCell(); // Added 2005-11-01 AF + void wheelMove( QWheelEvent* ); // Added 2005-11-28 AF + void command(); // Added 2005-12-15 AF + void nextCommand(); // Added 2005-12-15 AF + void nextField(); // Added 2005-12-15 AF + void eval(); // Added 2005-12-15 AF + void forwardAction( int ); // Added 2006-04-27 AF + void updatePos(int, int); + void setState(int); + void showVariableButton(bool); + + protected: + void mousePressEvent(QMouseEvent *event); // Added 2005-11-01 AF + void wheelEvent(QWheelEvent *event); // Added 2005-11-28 AF + void keyPressEvent(QKeyEvent *event ); // Added 2005-12-15 AF + void insertFromMimeData(const QMimeData *source); // Added 2006-01-23 AF + void focusInEvent(QFocusEvent* event); + + private: + bool inCommand; // Added 2005-12-15 AF + bool stopHighlighter; // Added 2006-01-16 AF + int indentationLevel(QString, bool b=true); + bool autoIndent; + QMap indentationStates; + + }; + + class MyAction: public QAction + { + Q_OBJECT + public: + MyAction(const QString& text, QObject* parent); + public slots: + void triggered2(); + signals: + void urlClicked(const QUrl& u); + + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/graphcelldelegate.h b/OMNotebook/OMNotebookQT4/graphcelldelegate.h index 764ecfc9f93..0a9ce8b6c25 100644 --- a/OMNotebook/OMNotebookQT4/graphcelldelegate.h +++ b/OMNotebook/OMNotebookQT4/graphcelldelegate.h @@ -54,11 +54,11 @@ namespace IAEX { public: virtual QString getResult() = 0; - virtual QString getError() = 0; // Added 2006-02-02 AF + virtual QString getError() = 0; // Added 2006-02-02 AF virtual void evalExpression(QString &expr) = 0; - virtual void closeConnection() = 0; // Added 2006-02-02 AF - virtual void reconnect() = 0; // Added 2006-02-02 AF - virtual bool startDelegate() = 0; // Added 2006-02-09 AF + virtual void closeConnection() = 0; // Added 2006-02-02 AF + virtual void reconnect() = 0; // Added 2006-02-02 AF + virtual bool startDelegate() = 0; // Added 2006-02-09 AF }; } diff --git a/OMNotebook/OMNotebookQT4/highlighterthread.cpp b/OMNotebook/OMNotebookQT4/highlighterthread.cpp index 3d770e87f41..084b052e66a 100644 --- a/OMNotebook/OMNotebookQT4/highlighterthread.cpp +++ b/OMNotebook/OMNotebookQT4/highlighterthread.cpp @@ -53,219 +53,219 @@ using namespace std; namespace IAEX { - /*! - * \class NullHighlighter - * \author Ingemar Axelsson and Anders Ferström - * \date 2006-01-09 (update) - * - * \brief This class is used if no SyntaxHighlighter is set. - * - * 2005-10-27 AF, Change this class to reflect the changes made - * to the SyntaxHighlighter interface. - * 2006-01-09 AF, Change this class to reflect the changes made - * to the SyntaxHighlighter interface (again). - */ - class NullHighlighter : public SyntaxHighlighter - { - public: - virtual void highlight(QTextDocument *){} - }; - - /*! - * \class HighlighterThread - * \author Anders Fernström - * \date 2005-12-17 - * - * \bried Class for runing the highligher in a seperted thread. - */ - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief The class constructor - */ - HighlighterThread::HighlighterThread( SyntaxHighlighter *highlighter, QObject *parent ) - : QThread( parent ), - highlighter_( highlighter ), - stopHighlighting_( true ) - { - } - - // The instance - HighlighterThread *HighlighterThread::instance_ = 0; - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief returns the instance of the object, if no instance exists - * the functions creates an new instance. - * - * \return the instance - */ - HighlighterThread *HighlighterThread::instance( SyntaxHighlighter *highlighter, QObject *parent ) - { - if( !instance_ ) - { - if( highlighter ) - instance_ = new HighlighterThread( highlighter, parent ); - else - instance_ = new HighlighterThread( new NullHighlighter(), parent ); - } - - return instance_; - } - - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * \date 2006-01-13 (update) - * - * \brief implementation of the virutal run function in QThread - * - * 2006-01-06 AF, added remove queue - * 2006-01-13 AF, stop thread when nothing to do - */ - void HighlighterThread::run() - { - //cout << "Highlight-1" << endl; - - //2005-12-29 - while( true ) - { - //cout << "Highlight-2" << endl; - - if( !stack_.isEmpty() ) - { - QTextEdit *editor = stack_.pop(); - - //if( editor->isVisible() ) - //{ - highlighter_->highlight( editor->document() ); - - - // force text to be updated -// editor->update(); -// QCoreApplication::processEvents(); -// QTextCursor cursor = editor->textCursor(); -// editor->setTextCursor( cursor ); - //} - //else - //{ - // add last - //stack_.push_back( editor ); - //} - } - - // 2006-01-05 AF, check if any editor should be removed - while( !removeQueue_.isEmpty() ) - { - //cout << "Highlight - Remove size: " << removeQueue_.size() << endl; - QTextEdit *editor = removeQueue_.dequeue(); - int index = stack_.indexOf( editor ); - if( index >= 0 ) - stack_.remove( index ); - } - - //cout << "Highlight - Stack size: " << stack_.size() << endl; - - // 2006-01-13 AF, stop thread when nothing to do - if( stack_.isEmpty() ) - { - //cout << "Highlight: Exit thread" << endl; - //this->exit(); - break; - } - - } - - //cout << "Highlight-3" << endl; - } - - /*! - * \author Anders Fernström - * \date 2005-12-29 - * \date 2006-01-13 (update) - * - * \brief add an text editor for highlightning - * - * 2006-01-13 AF, restart thread if it have been stoped - */ - void HighlighterThread::addEditor( QTextEdit *editor ) - { - if( editor ) - { - int index = stack_.indexOf( editor ); - if( index >= 0 ) - { - stack_.remove( index ); - stack_.push( editor ); - } - else - stack_.push( editor ); - - // 2006-01-13 AF, restart the thread - if( !isRunning() && !stopHighlighting_ ) - start( QThread::LowPriority ); - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-05 - * \date 2006-01-13 (update) - * - * \brief add text editor to remove queue - * - * 2006-01-13 AF, restart thread if it have been stoped - */ - void HighlighterThread::removeEditor( QTextEdit *editor ) - { - if( editor ) - { - removeQueue_.enqueue( editor ); - - // 2006-01-13 AF, restart the thread - if( !isRunning() && !stopHighlighting_ ) - start( QThread::LowPriority ); - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-05 - * - * \brief check if text editor is in highlighter thread - */ - bool HighlighterThread::haveEditor( QTextEdit *editor ) - { - if( editor ) - { - if( stack_.indexOf( editor ) >= 0 ) - return true; - else - return false; - } - - return false; - } - - /*! - * \author Anders Fernström - * \date 2006-01-05 - * - * \brief Set whether or not highlight should be stopped. - */ - void HighlighterThread::setStop( bool stop ) - { - stopHighlighting_ = stop; - if( stopHighlighting_ && isRunning() ) - this->exit(); - - if( !stopHighlighting_ && !isRunning() ) - start( QThread::LowPriority ); - } + /*! + * \class NullHighlighter + * \author Ingemar Axelsson and Anders Ferström + * \date 2006-01-09 (update) + * + * \brief This class is used if no SyntaxHighlighter is set. + * + * 2005-10-27 AF, Change this class to reflect the changes made + * to the SyntaxHighlighter interface. + * 2006-01-09 AF, Change this class to reflect the changes made + * to the SyntaxHighlighter interface (again). + */ + class NullHighlighter : public SyntaxHighlighter + { + public: + virtual void highlight(QTextDocument *){} + }; + + /*! + * \class HighlighterThread + * \author Anders Fernström + * \date 2005-12-17 + * + * \bried Class for runing the highligher in a seperted thread. + */ + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief The class constructor + */ + HighlighterThread::HighlighterThread( SyntaxHighlighter *highlighter, QObject *parent ) + : QThread( parent ), + highlighter_( highlighter ), + stopHighlighting_( true ) + { + } + + // The instance + HighlighterThread *HighlighterThread::instance_ = 0; + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief returns the instance of the object, if no instance exists + * the functions creates an new instance. + * + * \return the instance + */ + HighlighterThread *HighlighterThread::instance( SyntaxHighlighter *highlighter, QObject *parent ) + { + if( !instance_ ) + { + if( highlighter ) + instance_ = new HighlighterThread( highlighter, parent ); + else + instance_ = new HighlighterThread( new NullHighlighter(), parent ); + } + + return instance_; + } + + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * \date 2006-01-13 (update) + * + * \brief implementation of the virutal run function in QThread + * + * 2006-01-06 AF, added remove queue + * 2006-01-13 AF, stop thread when nothing to do + */ + void HighlighterThread::run() + { + //cout << "Highlight-1" << endl; + + //2005-12-29 + while( true ) + { + //cout << "Highlight-2" << endl; + + if( !stack_.isEmpty() ) + { + QTextEdit *editor = stack_.pop(); + + //if( editor->isVisible() ) + //{ + highlighter_->highlight( editor->document() ); + + + // force text to be updated +// editor->update(); +// QCoreApplication::processEvents(); +// QTextCursor cursor = editor->textCursor(); +// editor->setTextCursor( cursor ); + //} + //else + //{ + // add last + //stack_.push_back( editor ); + //} + } + + // 2006-01-05 AF, check if any editor should be removed + while( !removeQueue_.isEmpty() ) + { + //cout << "Highlight - Remove size: " << removeQueue_.size() << endl; + QTextEdit *editor = removeQueue_.dequeue(); + int index = stack_.indexOf( editor ); + if( index >= 0 ) + stack_.remove( index ); + } + + //cout << "Highlight - Stack size: " << stack_.size() << endl; + + // 2006-01-13 AF, stop thread when nothing to do + if( stack_.isEmpty() ) + { + //cout << "Highlight: Exit thread" << endl; + //this->exit(); + break; + } + + } + + //cout << "Highlight-3" << endl; + } + + /*! + * \author Anders Fernström + * \date 2005-12-29 + * \date 2006-01-13 (update) + * + * \brief add an text editor for highlightning + * + * 2006-01-13 AF, restart thread if it have been stoped + */ + void HighlighterThread::addEditor( QTextEdit *editor ) + { + if( editor ) + { + int index = stack_.indexOf( editor ); + if( index >= 0 ) + { + stack_.remove( index ); + stack_.push( editor ); + } + else + stack_.push( editor ); + + // 2006-01-13 AF, restart the thread + if( !isRunning() && !stopHighlighting_ ) + start( QThread::LowPriority ); + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-05 + * \date 2006-01-13 (update) + * + * \brief add text editor to remove queue + * + * 2006-01-13 AF, restart thread if it have been stoped + */ + void HighlighterThread::removeEditor( QTextEdit *editor ) + { + if( editor ) + { + removeQueue_.enqueue( editor ); + + // 2006-01-13 AF, restart the thread + if( !isRunning() && !stopHighlighting_ ) + start( QThread::LowPriority ); + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-05 + * + * \brief check if text editor is in highlighter thread + */ + bool HighlighterThread::haveEditor( QTextEdit *editor ) + { + if( editor ) + { + if( stack_.indexOf( editor ) >= 0 ) + return true; + else + return false; + } + + return false; + } + + /*! + * \author Anders Fernström + * \date 2006-01-05 + * + * \brief Set whether or not highlight should be stopped. + */ + void HighlighterThread::setStop( bool stop ) + { + stopHighlighting_ = stop; + if( stopHighlighting_ && isRunning() ) + this->exit(); + + if( !stopHighlighting_ && !isRunning() ) + start( QThread::LowPriority ); + } } diff --git a/OMNotebook/OMNotebookQT4/highlighterthread.h b/OMNotebook/OMNotebookQT4/highlighterthread.h index 836d61dddea..daf1bb76939 100644 --- a/OMNotebook/OMNotebookQT4/highlighterthread.h +++ b/OMNotebook/OMNotebookQT4/highlighterthread.h @@ -54,26 +54,26 @@ class QTextEdit; using namespace std; namespace IAEX { - class HighlighterThread : public QThread - { - public: - static HighlighterThread *instance( SyntaxHighlighter *highlighter = 0, QObject *parent = 0 ); - void run(); - void addEditor( QTextEdit *editor ); // Added 2005-12-29 AF - void removeEditor( QTextEdit *editor ); // Added 2006-01-05 AF - bool haveEditor( QTextEdit *editor ); // Added 2006-01-05 AF - void setStop( bool stop ); // Added 2006-05-03 AF + class HighlighterThread : public QThread + { + public: + static HighlighterThread *instance( SyntaxHighlighter *highlighter = 0, QObject *parent = 0 ); + void run(); + void addEditor( QTextEdit *editor ); // Added 2005-12-29 AF + void removeEditor( QTextEdit *editor ); // Added 2006-01-05 AF + bool haveEditor( QTextEdit *editor ); // Added 2006-01-05 AF + void setStop( bool stop ); // Added 2006-05-03 AF - private: - HighlighterThread( SyntaxHighlighter *highlighter = 0, QObject *parent = 0 ); + private: + HighlighterThread( SyntaxHighlighter *highlighter = 0, QObject *parent = 0 ); - private: - static HighlighterThread *instance_; - bool stopHighlighting_; + private: + static HighlighterThread *instance_; + bool stopHighlighting_; - SyntaxHighlighter *highlighter_; - QStack stack_; - QQueue removeQueue_; - }; + SyntaxHighlighter *highlighter_; + QStack stack_; + QQueue removeQueue_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/imagesizedlg.h b/OMNotebook/OMNotebookQT4/imagesizedlg.h index c40d6a7753e..d1adb78bb24 100644 --- a/OMNotebook/OMNotebookQT4/imagesizedlg.h +++ b/OMNotebook/OMNotebookQT4/imagesizedlg.h @@ -46,66 +46,66 @@ namespace IAEX { - /*! - * \class ImageSizeDlg - * \author Anders Fernström - * \date 2005-11-20 - * - * \breif Class of opening a dialog window for selecting image size... - */ - class ImageSizeDlg : public QDialog - { - public: - ImageSizeDlg( QWidget *parent, QImage *image) - : QDialog(parent), image_(image) - { - ui.setupUi(this); - - QString width; - width.setNum( image->size().width() ); - ui.widthEdit->setText( width ); - - QString height; - height.setNum( image->size().height() ); - ui.heightEdit->setText( height ); - - //set fixed size - - setMinimumHeight( this->height() ); - setMaximumHeight( this->height() ); - setMinimumWidth( this->width() ); - setMaximumWidth( this->width() ); - } - virtual ~ImageSizeDlg(){} - - QSize value() - { - bool heightOK; - bool widthOK; - - int height = ui.heightEdit->text().toInt( &heightOK ); - int width = ui.widthEdit->text().toInt( &widthOK ); - - QSize size; - if( heightOK && widthOK ) - { - size.setHeight( height ); - size.setWidth( width ); - } - else - { - size.setHeight( -1 ); - size.setWidth( -1 ); - } - - return size; - } - - - private: - Ui::ImageDialog ui; - QImage *image_; - }; + /*! + * \class ImageSizeDlg + * \author Anders Fernström + * \date 2005-11-20 + * + * \breif Class of opening a dialog window for selecting image size... + */ + class ImageSizeDlg : public QDialog + { + public: + ImageSizeDlg( QWidget *parent, QImage *image) + : QDialog(parent), image_(image) + { + ui.setupUi(this); + + QString width; + width.setNum( image->size().width() ); + ui.widthEdit->setText( width ); + + QString height; + height.setNum( image->size().height() ); + ui.heightEdit->setText( height ); + + //set fixed size + + setMinimumHeight( this->height() ); + setMaximumHeight( this->height() ); + setMinimumWidth( this->width() ); + setMaximumWidth( this->width() ); + } + virtual ~ImageSizeDlg(){} + + QSize value() + { + bool heightOK; + bool widthOK; + + int height = ui.heightEdit->text().toInt( &heightOK ); + int width = ui.widthEdit->text().toInt( &widthOK ); + + QSize size; + if( heightOK && widthOK ) + { + size.setHeight( height ); + size.setWidth( width ); + } + else + { + size.setHeight( -1 ); + size.setWidth( -1 ); + } + + return size; + } + + + private: + Ui::ImageDialog ui; + QImage *image_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/indent.cpp b/OMNotebook/OMNotebookQT4/indent.cpp index 9826a18748b..ce26f5809c4 100644 --- a/OMNotebook/OMNotebookQT4/indent.cpp +++ b/OMNotebook/OMNotebookQT4/indent.cpp @@ -44,11 +44,11 @@ IndentationState::~IndentationState() } Indent::ISM::ISM() { - level = 0; - state = 0; - skipNext = false; - lMod = false; - nextMod = 0; + level = 0; + state = 0; + skipNext = false; + lMod = false; + nextMod = 0; } Indent::ISM::~ISM() { @@ -57,291 +57,291 @@ Indent::ISM::~ISM() void Indent::ISM::newToken(QString s, QString s2) { - if(skipNext) - { - skipNext = false; - return; - } - - if(state != 4 && s.count("\"")%2) - { - oldState = state; - state = 4; - return; - } + if(skipNext) + { + skipNext = false; + return; + } + + if(state != 4 && s.count("\"")%2) + { + oldState = state; + state = 4; + return; + } /* - if(state != 5 && s.left(2) == "//") - { - oldState = state; - state = 5; - return; - } + if(state != 5 && s.left(2) == "//") + { + oldState = state; + state = 5; + return; + } */ - switch(state) - { - case 0: - loopBlock = false; - - if(s == "equation") - { - equationSection = true; - lMod = true; - break; - } - else if(s == "algorithm") - { - equationSection = false; - lMod = true; - break; - } - else if(s == "class" || s == "package" || s == "function" || s == "model" || s == "record" || s == "connector") - { - ++level; - skipNext = true; - lMod = true; - break; - } - else if(s == "end") - { - // --level; - nextMod = -1; - skipNext = true; - lMod = true; - break; - } - else if(s == "public" || s == "protected") - { - lMod = true; - break; - } - lMod = false; - - if(s2 == "if" || s == "if" ) - { - if(s == "=") - equation = true; - else - equation = false; - - state = 1; - // lMod = true; - } - else if(s == "when" || s == "for") - { - loopBlock = true; - state = 1; - - } - break; - - case 1: - if(loopBlock && (s == "then" || s == "loop")) - { -// ++level; -// lMod = true; - nextMod = +1; - state = 0; - } - else if(s == "then" ) - { -// ++level; - if(equation || equationSection) - state = 2; - else - state = 3; -// lMod = true; - nextMod = +1; - } - - break; - - case 2: - if(s == "elseif" || (s == "else" && s2 == "if" && (skipNext = true))) - { -// lMod = true;; - --level; -// nextMod = -1; - state = 1; - break; - } - else if(s2 == "else") - { - // lMod = true; - } - else if(s == "else") - { - lMod = true; - - } - else - { - // lMod = false; - //--level; - nextMod = -1; - state = 0; - } - break; - - case 3: - if( s == "elseif" || (s == "else" && s2 == "if" && (skipNext = true))) - { -// lMod = true; - state = 1; - // nextMod = -1; - --level; - } - else if(s == "when" || s == "for") - { - lMod = true; - state = 1; - - } - else if(s == "else") - { - lMod = true; - state = 1; - // nextMod = -1; - // --level; - } - else if(s == "end" && (s2.left(2) == "if" || s2.left(3) == "for" || s2.left(4) == "when") && (skipNext = true)) - { - // skipNext = true; - state = 0; - --level; - - // nextMod = -1; - // lMod = true; - - } - - break; - case 4: //Text strings - - if(s.count("\"")%2) - state = oldState; - break; - - case 5: //Comments - // QMessageBox::information(0, "uu", s); - if(s == "") - state = oldState; - - break; - } - //switch(state) - //{ - //case 0: //default state - // if(s == QString("=") && s2 == QString("if")) - // { - // state = 1; - // break; - // } - // if(s == QString("algorithm")) - // { - // equation = false; - // break; - // } - // else if (s == QString("equation")) - // { - // equation = true; - // break; - // } - - // if(s == QString("if")) - // state = equation?1:4; - - // break; - //case 1: // then, loop - // if(s == QString("then")) - // { - // state = 2; - // ++currentLevel; - // } - // break; - //case 2: // else - - // if(s2 == QString("elseif")) - // state = 1; - // else if(s2 == QString("else")) - // state = 3; - // else - // state = 0; - // --currentLevel; - - // break; - //case 3: // if, elseif, end - // if(s == QString("else")) - // { - // if(s2 == QString("if")) - // { - // state = 1; - // } - // else - // { - // ++currentLevel; - // state = 2; - // } - // } - // else if (s == QString("elseif")) - // { - // state = 1; - // } - // else - // { - // state = 0; - // equation = false; - // } - // break; - //case 4: // if, elseif, end - // if(s == QString("then")) - // { - // ++currentLevel; - // state = 5; - // } - - // break; - //case 5: // if, elseif, end - // if(s == QString("else")) - // { - // if(s2 == QString("if")) - // { - // state = 4; - // --currentLevel; - - // } - // else - // { - // state = 6; - // } - // } - // else if(s == QString("end") && s2 == QString("if")) - // state = 7; - // break; - //case 6: // if, elseif, end - // state = 5; - // break; - //case 7: - // state = 0; - // --currentLevel; - // break; - - //} + switch(state) + { + case 0: + loopBlock = false; + + if(s == "equation") + { + equationSection = true; + lMod = true; + break; + } + else if(s == "algorithm") + { + equationSection = false; + lMod = true; + break; + } + else if(s == "class" || s == "package" || s == "function" || s == "model" || s == "record" || s == "connector") + { + ++level; + skipNext = true; + lMod = true; + break; + } + else if(s == "end") + { + // --level; + nextMod = -1; + skipNext = true; + lMod = true; + break; + } + else if(s == "public" || s == "protected") + { + lMod = true; + break; + } + lMod = false; + + if(s2 == "if" || s == "if" ) + { + if(s == "=") + equation = true; + else + equation = false; + + state = 1; + // lMod = true; + } + else if(s == "when" || s == "for") + { + loopBlock = true; + state = 1; + + } + break; + + case 1: + if(loopBlock && (s == "then" || s == "loop")) + { +// ++level; +// lMod = true; + nextMod = +1; + state = 0; + } + else if(s == "then" ) + { +// ++level; + if(equation || equationSection) + state = 2; + else + state = 3; +// lMod = true; + nextMod = +1; + } + + break; + + case 2: + if(s == "elseif" || (s == "else" && s2 == "if" && (skipNext = true))) + { +// lMod = true;; + --level; +// nextMod = -1; + state = 1; + break; + } + else if(s2 == "else") + { + // lMod = true; + } + else if(s == "else") + { + lMod = true; + + } + else + { + // lMod = false; + //--level; + nextMod = -1; + state = 0; + } + break; + + case 3: + if( s == "elseif" || (s == "else" && s2 == "if" && (skipNext = true))) + { +// lMod = true; + state = 1; + // nextMod = -1; + --level; + } + else if(s == "when" || s == "for") + { + lMod = true; + state = 1; + + } + else if(s == "else") + { + lMod = true; + state = 1; + // nextMod = -1; + // --level; + } + else if(s == "end" && (s2.left(2) == "if" || s2.left(3) == "for" || s2.left(4) == "when") && (skipNext = true)) + { + // skipNext = true; + state = 0; + --level; + + // nextMod = -1; + // lMod = true; + + } + + break; + case 4: //Text strings + + if(s.count("\"")%2) + state = oldState; + break; + + case 5: //Comments + // QMessageBox::information(0, "uu", s); + if(s == "") + state = oldState; + + break; + } + //switch(state) + //{ + //case 0: //default state + // if(s == QString("=") && s2 == QString("if")) + // { + // state = 1; + // break; + // } + // if(s == QString("algorithm")) + // { + // equation = false; + // break; + // } + // else if (s == QString("equation")) + // { + // equation = true; + // break; + // } + + // if(s == QString("if")) + // state = equation?1:4; + + // break; + //case 1: // then, loop + // if(s == QString("then")) + // { + // state = 2; + // ++currentLevel; + // } + // break; + //case 2: // else + + // if(s2 == QString("elseif")) + // state = 1; + // else if(s2 == QString("else")) + // state = 3; + // else + // state = 0; + // --currentLevel; + + // break; + //case 3: // if, elseif, end + // if(s == QString("else")) + // { + // if(s2 == QString("if")) + // { + // state = 1; + // } + // else + // { + // ++currentLevel; + // state = 2; + // } + // } + // else if (s == QString("elseif")) + // { + // state = 1; + // } + // else + // { + // state = 0; + // equation = false; + // } + // break; + //case 4: // if, elseif, end + // if(s == QString("then")) + // { + // ++currentLevel; + // state = 5; + // } + + // break; + //case 5: // if, elseif, end + // if(s == QString("else")) + // { + // if(s2 == QString("if")) + // { + // state = 4; + // --currentLevel; + + // } + // else + // { + // state = 6; + // } + // } + // else if(s == QString("end") && s2 == QString("if")) + // state = 7; + // break; + //case 6: // if, elseif, end + // state = 5; + // break; + //case 7: + // state = 0; + // --currentLevel; + // break; + + //} } Indent::Indent(QString s, bool aggressive_) { - // ts.reset(); - buffer1 = s; - // QMessageBox::information(0, "uu3", s); - // ts.setString(s); - // ts << s.trimmed(); - // ts.string()->append(s); - // ts.resetStatus(); - - aggressive = aggressive_; - currentLevel = 0; - lineModifiers = 0; + // ts.reset(); + buffer1 = s; + // QMessageBox::information(0, "uu3", s); + // ts.setString(s); + // ts << s.trimmed(); + // ts.string()->append(s); + // ts.resetStatus(); + + aggressive = aggressive_; + currentLevel = 0; + lineModifiers = 0; } Indent::~Indent() @@ -350,134 +350,134 @@ Indent::~Indent() void Indent::setText(QString s) { - ts.reset(); - ts << s; + ts.reset(); + ts << s; } int Indent::level() { - return ism.level; + return ism.level; } bool Indent::lMod() { - return lmod; + return lmod; } QString Indent::indentedText(QMap* states) { - buffer1 = buffer1.replace('\n', " ") + " " + " "; - buffer1 = buffer1.replace("//", " //"); - buffer1 = buffer1.replace("=", " = "); - QTextStream ts(&buffer1, QIODevice::ReadWrite); - - //QString current, next, comment; - - QString comment; - - current = ""; - ts >> next; -// next = ""; - - int newline, n, N=1; - QString tmp, res, tmp2; - while(!ts.atEnd()) - { - current = next; - ts >> next; - newline = 0; + buffer1 = buffer1.replace('\n', " ") + " " + " "; + buffer1 = buffer1.replace("//", " //"); + buffer1 = buffer1.replace("=", " = "); + QTextStream ts(&buffer1, QIODevice::ReadWrite); + + //QString current, next, comment; + + QString comment; + + current = ""; + ts >> next; +// next = ""; + + int newline, n, N=1; + QString tmp, res, tmp2; + while(!ts.atEnd()) + { + current = next; + ts >> next; + newline = 0; //***************** - if((n=next.indexOf("//")) >=0) - { - // QMessageBox::information(0, "uu", "." + next.right(next.size() -n) +"."); - comment = " " + next.right(next.size() -n); - // QMessageBox::information(0, "uu", "." + comment + "."); - next = next.left(n); - - ts >> tmp2; - while(tmp2 != "") - { - // QMessageBox::information(0, "uu2", tmp2); - comment += " " + tmp2; - ts >> tmp2; - - - } - // tmp2 = ts.readLine(); - // next = ""; - // comment += tmp2.left(tmp2.size() - next.size()); - next = tmp2; - ++newline; - - } + if((n=next.indexOf("//")) >=0) + { + // QMessageBox::information(0, "uu", "." + next.right(next.size() -n) +"."); + comment = " " + next.right(next.size() -n); + // QMessageBox::information(0, "uu", "." + comment + "."); + next = next.left(n); + + ts >> tmp2; + while(tmp2 != "") + { + // QMessageBox::information(0, "uu2", tmp2); + comment += " " + tmp2; + ts >> tmp2; + + + } + // tmp2 = ts.readLine(); + // next = ""; + // comment += tmp2.left(tmp2.size() - next.size()); + next = tmp2; + ++newline; + + } //******************** - // newline = false; - - - while(next == "") - { - ++newline; - ts >> next; - } - - - // if(next.left(2) == "//") - // comment = true; - -// qDebug() << current << ", " << next << endl; - - ism.newToken(current, next); -// qDebug() << ism.state << ", " << ism.level << ", " << ism.lMod << endl; - - if(current == "") - { - current = "\n"; -// if(ism.state == 5) -// ism.state = ism.oldState; - } - - if(newline) - { - N += newline; - // qDebug() << ism.level << endl; - // if(ism.lMod) - // --ism.level; - // ism.level = max(ism.level, 0); - // QMessageBox::information(0, "uu", "." + comment + "."); - if(comment.size()) - { - res = res + "\n" + QString(2*ism.level -2*ism.lMod, ' ') +tmp + current.trimmed() +" " + comment.trimmed(); //QString(tmp.size()?1:0, ' ') + current.trimmed(); - } - else - res = res + "\n" + QString(2*ism.level -2*ism.lMod, ' ') +tmp + current.trimmed() + QString(newline-1, '\n'); //QString(tmp.size()?1:0, ' ') + current.trimmed(); - // res = res + "\n" + QString(2*ism.level -2*ism.lMod, ' ') +tmp + current.trimmed() + QString(comment.size()?1:0,'\n') + QString(newline-1, '\n'); //QString(tmp.size()?1:0, ' ') + current.trimmed(); - - - // res = res + "\n" + QString(2*4 -2*2, '#') + tmp + QString(tmp.size()?0:1, ' ') + current; - comment = ""; - tmp = ""; - ism.level += ism.nextMod; - ism.nextMod = 0; - - lmod = ism.lMod; - ism.lMod = false; -// qDebug() << "nu" << endl; - if(states && !(N % 10)) - { - if(states->find(N) != states->end()) - states->remove(N); - // delete states->find(N); - (*states)[N] = new IndentationState(ism.state, ism.level, ism.nextMod, current, next, ism.skipNext, ism.lMod, ism.equation, ism.equationSection, ism.loopBlock); - } - } - else - tmp += current.trimmed() + QString(current.size()?1:0, ' ') ; - - - } - - - - return res.trimmed(); + // newline = false; + + + while(next == "") + { + ++newline; + ts >> next; + } + + + // if(next.left(2) == "//") + // comment = true; + +// qDebug() << current << ", " << next << endl; + + ism.newToken(current, next); +// qDebug() << ism.state << ", " << ism.level << ", " << ism.lMod << endl; + + if(current == "") + { + current = "\n"; +// if(ism.state == 5) +// ism.state = ism.oldState; + } + + if(newline) + { + N += newline; + // qDebug() << ism.level << endl; + // if(ism.lMod) + // --ism.level; + // ism.level = max(ism.level, 0); + // QMessageBox::information(0, "uu", "." + comment + "."); + if(comment.size()) + { + res = res + "\n" + QString(2*ism.level -2*ism.lMod, ' ') +tmp + current.trimmed() +" " + comment.trimmed(); //QString(tmp.size()?1:0, ' ') + current.trimmed(); + } + else + res = res + "\n" + QString(2*ism.level -2*ism.lMod, ' ') +tmp + current.trimmed() + QString(newline-1, '\n'); //QString(tmp.size()?1:0, ' ') + current.trimmed(); + // res = res + "\n" + QString(2*ism.level -2*ism.lMod, ' ') +tmp + current.trimmed() + QString(comment.size()?1:0,'\n') + QString(newline-1, '\n'); //QString(tmp.size()?1:0, ' ') + current.trimmed(); + + + // res = res + "\n" + QString(2*4 -2*2, '#') + tmp + QString(tmp.size()?0:1, ' ') + current; + comment = ""; + tmp = ""; + ism.level += ism.nextMod; + ism.nextMod = 0; + + lmod = ism.lMod; + ism.lMod = false; +// qDebug() << "nu" << endl; + if(states && !(N % 10)) + { + if(states->find(N) != states->end()) + states->remove(N); + // delete states->find(N); + (*states)[N] = new IndentationState(ism.state, ism.level, ism.nextMod, current, next, ism.skipNext, ism.lMod, ism.equation, ism.equationSection, ism.loopBlock); + } + } + else + tmp += current.trimmed() + QString(current.size()?1:0, ' ') ; + + + } + + + + return res.trimmed(); } diff --git a/OMNotebook/OMNotebookQT4/indent.h b/OMNotebook/OMNotebookQT4/indent.h index d96635d1849..4e83f0d9f79 100644 --- a/OMNotebook/OMNotebookQT4/indent.h +++ b/OMNotebook/OMNotebookQT4/indent.h @@ -39,53 +39,53 @@ class IndentationState { public: - IndentationState(int state_, int level_, int nextMod_, QString current_, QString next_, bool skipNext_, bool lMod_, bool equation_, bool equationSection_, bool loopBlock_): - state(state_), level(level_), nextMod(nextMod_), current(current_), next(next_), skipNext(skipNext_), lMod(lMod_), equation(equation_), equationSection(equationSection_), loopBlock(loopBlock_) - { + IndentationState(int state_, int level_, int nextMod_, QString current_, QString next_, bool skipNext_, bool lMod_, bool equation_, bool equationSection_, bool loopBlock_): + state(state_), level(level_), nextMod(nextMod_), current(current_), next(next_), skipNext(skipNext_), lMod(lMod_), equation(equation_), equationSection(equationSection_), loopBlock(loopBlock_) + { - } - ~IndentationState(); + } + ~IndentationState(); - int level, state, nextMod; - QString current, next; - bool skipNext, lMod, equation, equationSection, loopBlock; + int level, state, nextMod; + QString current, next; + bool skipNext, lMod, equation, equationSection, loopBlock; }; class Indent { public: - Indent(QString t = QString(), bool a = false); - ~Indent(); + Indent(QString t = QString(), bool a = false); + ~Indent(); - QString indentedText(QMap* states = 0); - void setText(QString); - int level(); - bool lMod(); + QString indentedText(QMap* states = 0); + void setText(QString); + int level(); + bool lMod(); private: - int currentLevel; - int lineModifiers; - QTextStream ts; - bool aggressive, lmod; - QString buffer1, buffer2; + int currentLevel; + int lineModifiers; + QTextStream ts; + bool aggressive, lmod; + QString buffer1, buffer2; - class ISM - { - public: - ISM(); - ~ISM(); + class ISM + { + public: + ISM(); + ~ISM(); - void newToken(QString, QString); - int level, lineModifiers, state, nextMod; - bool equation, equationSection, loopBlock; - bool skipNext; - bool lMod; - int oldState; + void newToken(QString, QString); + int level, lineModifiers, state, nextMod; + bool equation, equationSection, loopBlock; + bool skipNext; + bool lMod; + int oldState; - }; + }; public: - ISM ism; - QString current, next; + ISM ism; + QString current, next; }; diff --git a/OMNotebook/OMNotebookQT4/inputcell.cpp b/OMNotebook/OMNotebookQT4/inputcell.cpp index f43000ee0c1..dfe26507526 100644 --- a/OMNotebook/OMNotebookQT4/inputcell.cpp +++ b/OMNotebook/OMNotebookQT4/inputcell.cpp @@ -71,1526 +71,1526 @@ namespace IAEX { - /*! - * \class SleeperThread - * \author Anders Ferström - * - * \brief Extends QThread. A small trick to get access to protected - * function in QThread. - */ - class SleeperThread : public QThread - { - public: - static void msleep(unsigned long msecs) - { - QThread::msleep(msecs); - } - }; - - - - /*! - * \class MyTextEdit - * \author Anders Ferström - * \date 2005-11-01 - * - * \brief Extends QTextEdit. Mostly so I can catch when a user - * clicks on the editor - */ - MyTextEdit::MyTextEdit(QWidget *parent) - : QTextBrowser(parent), - inCommand(false), - stopHighlighter(false) - { - } - - MyTextEdit::~MyTextEdit() - { - } - - bool MyTextEdit::isStopingHighlighter() - { - return stopHighlighter; - } - - /*! - * \author Anders Fernström - * \date 2005-11-01 - * \date 2005-12-15 (update) - * - * Needed a signal to be emited when the user click on the cell. - * - * 2005-12-15 AF, set inCommand to false when clicking on the cell, - * otherwise the commandcompletion class want be reseted when - * changing inputcells by clicking. - */ - void MyTextEdit::mousePressEvent(QMouseEvent *event) - { - stopHighlighter = false; - inCommand = false; - QTextBrowser::mousePressEvent(event); - - if( event->modifiers() == Qt::ShiftModifier || - textCursor().hasSelection() ) - { - return; - } - - emit clickOnCell(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-28 - * - * \brief Handles mouse wheel events, ignore them and send the up - * in the cell hierarchy - */ - void MyTextEdit::wheelEvent(QWheelEvent * event) - { - // ignore event and send it up in the event hierarchy - event->ignore(); - emit wheelMove( event ); - } - - /*! - * \author Anders Fernström - * \date 2005-12-15 - * \date 2006-01-30 (update) - * - * \brief Handles key event, check if command completion or eval, - * otherwise send them to the textbrowser - * - * 2006-01-30 AF, added ignore to 'Alt+Enter' - */ - void MyTextEdit::keyPressEvent(QKeyEvent *event ) - { - - // EVAL, key: SHIFT + RETURN || SHIFT + ENTER - if( event->modifiers() == Qt::ShiftModifier && - - (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) ) - { - inCommand = false; - stopHighlighter = false; - - event->accept(); - emit eval(); - } - // COMMAND COMPLETION, key: SHIFT + TAB (= BACKTAB) || CTRL + SPACE - else if( (event->modifiers() == Qt::ShiftModifier && event->key() == Qt::Key_Backtab ) || - (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Space) ) - { - stopHighlighter = false; - - event->accept(); - if( inCommand ) - { - emit nextCommand(); - } - else - { - inCommand = true; - emit command(); - } - } - // COMMAND COMPLETION- NEXT FIELD, key: CTRL + TAB - else if( event->modifiers() == Qt::ControlModifier && - event->key() == Qt::Key_Tab ) - { - stopHighlighter = false; - - event->accept(); - inCommand = false; - emit nextField(); - } - // BACKSPACE, DELETE - else if( event->key() == Qt::Key_Backspace || - event->key() == Qt::Key_Delete ) - { - inCommand = false; - stopHighlighter = true; - - QTextBrowser::keyPressEvent( event ); - } - // ALT+ENTER (ignore) - else if( event->modifiers() == Qt::AltModifier && - ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )) - { - inCommand = false; - stopHighlighter = false; - - event->ignore(); - } - // PAGE UP (ignore) - else if( event->key() == Qt::Key_PageUp ) - { - inCommand = false; - stopHighlighter = false; - - event->ignore(); - } - // PAGE DOWN (ignore) - else if( event->key() == Qt::Key_PageDown ) - { - inCommand = false; - stopHighlighter = false; - - event->ignore(); - } - // CTRL+C - else if( event->modifiers() == Qt::ControlModifier && - event->key() == Qt::Key_C ) - { - inCommand = false; - stopHighlighter = false; - - event->ignore(); - emit forwardAction( 1 ); - } - // CTRL+X - else if( event->modifiers() == Qt::ControlModifier && - event->key() == Qt::Key_X ) - { - inCommand = false; - stopHighlighter = false; - - event->ignore(); - emit forwardAction( 2 ); - } - // CTRL+V - else if( event->modifiers() == Qt::ControlModifier && - event->key() == Qt::Key_V ) - { - inCommand = false; - stopHighlighter = false; - - event->ignore(); - emit forwardAction( 3 ); - } - - // TAB - else if( event->key() == Qt::Key_Tab ) - { - inCommand = false; - stopHighlighter = false; + /*! + * \class SleeperThread + * \author Anders Ferström + * + * \brief Extends QThread. A small trick to get access to protected + * function in QThread. + */ + class SleeperThread : public QThread + { + public: + static void msleep(unsigned long msecs) + { + QThread::msleep(msecs); + } + }; + + + + /*! + * \class MyTextEdit + * \author Anders Ferström + * \date 2005-11-01 + * + * \brief Extends QTextEdit. Mostly so I can catch when a user + * clicks on the editor + */ + MyTextEdit::MyTextEdit(QWidget *parent) + : QTextBrowser(parent), + inCommand(false), + stopHighlighter(false) + { + } + + MyTextEdit::~MyTextEdit() + { + } + + bool MyTextEdit::isStopingHighlighter() + { + return stopHighlighter; + } + + /*! + * \author Anders Fernström + * \date 2005-11-01 + * \date 2005-12-15 (update) + * + * Needed a signal to be emited when the user click on the cell. + * + * 2005-12-15 AF, set inCommand to false when clicking on the cell, + * otherwise the commandcompletion class want be reseted when + * changing inputcells by clicking. + */ + void MyTextEdit::mousePressEvent(QMouseEvent *event) + { + stopHighlighter = false; + inCommand = false; + QTextBrowser::mousePressEvent(event); + + if( event->modifiers() == Qt::ShiftModifier || + textCursor().hasSelection() ) + { + return; + } + + emit clickOnCell(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-28 + * + * \brief Handles mouse wheel events, ignore them and send the up + * in the cell hierarchy + */ + void MyTextEdit::wheelEvent(QWheelEvent * event) + { + // ignore event and send it up in the event hierarchy + event->ignore(); + emit wheelMove( event ); + } + + /*! + * \author Anders Fernström + * \date 2005-12-15 + * \date 2006-01-30 (update) + * + * \brief Handles key event, check if command completion or eval, + * otherwise send them to the textbrowser + * + * 2006-01-30 AF, added ignore to 'Alt+Enter' + */ + void MyTextEdit::keyPressEvent(QKeyEvent *event ) + { + + // EVAL, key: SHIFT + RETURN || SHIFT + ENTER + if( event->modifiers() == Qt::ShiftModifier && + + (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) ) + { + inCommand = false; + stopHighlighter = false; + + event->accept(); + emit eval(); + } + // COMMAND COMPLETION, key: SHIFT + TAB (= BACKTAB) || CTRL + SPACE + else if( (event->modifiers() == Qt::ShiftModifier && event->key() == Qt::Key_Backtab ) || + (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Space) ) + { + stopHighlighter = false; + + event->accept(); + if( inCommand ) + { + emit nextCommand(); + } + else + { + inCommand = true; + emit command(); + } + } + // COMMAND COMPLETION- NEXT FIELD, key: CTRL + TAB + else if( event->modifiers() == Qt::ControlModifier && + event->key() == Qt::Key_Tab ) + { + stopHighlighter = false; + + event->accept(); + inCommand = false; + emit nextField(); + } + // BACKSPACE, DELETE + else if( event->key() == Qt::Key_Backspace || + event->key() == Qt::Key_Delete ) + { + inCommand = false; + stopHighlighter = true; + + QTextBrowser::keyPressEvent( event ); + } + // ALT+ENTER (ignore) + else if( event->modifiers() == Qt::AltModifier && + ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )) + { + inCommand = false; + stopHighlighter = false; + + event->ignore(); + } + // PAGE UP (ignore) + else if( event->key() == Qt::Key_PageUp ) + { + inCommand = false; + stopHighlighter = false; + + event->ignore(); + } + // PAGE DOWN (ignore) + else if( event->key() == Qt::Key_PageDown ) + { + inCommand = false; + stopHighlighter = false; + + event->ignore(); + } + // CTRL+C + else if( event->modifiers() == Qt::ControlModifier && + event->key() == Qt::Key_C ) + { + inCommand = false; + stopHighlighter = false; + + event->ignore(); + emit forwardAction( 1 ); + } + // CTRL+X + else if( event->modifiers() == Qt::ControlModifier && + event->key() == Qt::Key_X ) + { + inCommand = false; + stopHighlighter = false; + + event->ignore(); + emit forwardAction( 2 ); + } + // CTRL+V + else if( event->modifiers() == Qt::ControlModifier && + event->key() == Qt::Key_V ) + { + inCommand = false; + stopHighlighter = false; + + event->ignore(); + emit forwardAction( 3 ); + } + + // TAB + else if( event->key() == Qt::Key_Tab ) + { + inCommand = false; + stopHighlighter = false; textCursor().insertText( " " ); - } - else - { - inCommand = false; - stopHighlighter = false; - - QTextBrowser::keyPressEvent( event ); - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-23 - * - * \brief If the mimedata that should be insertet contain text, - * create a new mimedata object that only contains text, otherwise - * text format is insertet also - don't want that for inputcells. - */ - void MyTextEdit::insertFromMimeData(const QMimeData *source) - { - if( source->hasText() ) - { - QMimeData *newSource = new QMimeData(); - newSource->setText( source->text() ); - QTextBrowser::insertFromMimeData( newSource ); - delete newSource; - } - else - QTextBrowser::insertFromMimeData( source ); - } - - /*! - * \class InputCell - * \author Ingemar Axelsson and Anders Fernström - * - * \brief Describes how an inputcell works. - * - * Input cells is places where the user can do input. To evaluate - * the content of an inputcell just press shift+enter. It will - * throw an exception if it cant find OMC. Start OMC with - * following commandline: - * - * # omc +d=interactiveCorba - * - * - * \todo Make it possiblee to add and change syntax coloring of code.(Ingemar Axelsson) - */ - - int InputCell::numEvals_ = 1; - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-11-23 (update) - * - * \brief The class constructor - * - * 2005-10-27 AF, updated the method due to porting from Q3Support - * to pure QT4 classes. - * 2005-11-23 AF, added document to the constructor, because need - * the document to insert images to the output part if ploting. - */ - InputCell::InputCell(Document *doc, QWidget *parent) - : Cell(parent), - evaluated_(false), - closed_(true), - delegate_(0), - oldHeight_( 0 ), - document_(doc) - { - QWidget *main = new QWidget(this); - setMainWidget(main); - - layout_ = new QGridLayout(mainWidget()); - layout_->setMargin(0); - layout_->setSpacing(0); - - setTreeWidget(new InputTreeView(this)); - - //2005-10-07 AF, Porting, change from 'QWidget::' to 'Qt::' - setFocusPolicy(Qt::NoFocus); - - createInputCell(); - createOutputCell(); - - //setBackgroundColor(QColor(200,200,255)); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * - * \brief The class destructor - */ - InputCell::~InputCell() - { - //2006-01-05 AF, check if input texteditor is in the highlighter, - //if it is - wait for 60 ms and check again. - HighlighterThread *thread = HighlighterThread::instance(); - int sleepTime = 0; - bool firstTime = true; - while( thread->haveEditor( input_ ) ) - { - if( firstTime ) - { - thread->removeEditor( input_ ); - firstTime = false; - } - - SleeperThread::msleep( 60 ); - sleepTime++; - - if( sleepTime > 100 ) - break; - } - - - delete input_; - delete output_; - //delete syntaxHighlighter_; - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2006-03-02 (update) - * - * \brief Creates the QTextEdit for the input part of the - * inputcell - * - * 2005-10-27 AF, Large part of this function was changes due to - * porting to QT4 (changes from Q3TextEdit to QTextEdit). - * 2005-12-15 AF, Added more connections to the editor, mostly for - * commandcompletion, but also for eval. invoking eval have moved - * from the eventfilter on this cell to the reimplemented key event - * handler in the editor - * 2006-03-02 AF, Added call to createChapterCounter(); - */ - void InputCell::createInputCell() - { - input_ = new MyTextEdit( mainWidget() ); - layout_->addWidget( input_, 1, 1 ); - - // 2006-03-02 AF, Add a chapter counter - createChapterCounter(); - - //input_->setReadOnly( false ); - input_->setReadOnly( true ); - input_->setUndoRedoEnabled( true ); - //input_->setFrameStyle( QFrame::NoFrame ); - input_->setFrameShape( QFrame::Box ); - input_->setAutoFormatting( QTextEdit::AutoNone ); - - input_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - input_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); -// input_->setContextMenuPolicy( Qt::NoContextMenu ); - - QPalette palette; - palette.setColor(input_->backgroundRole(), QColor(200,200,255)); - input_->setPalette(palette); - - // is this needed, don't know /AF - input_->installEventFilter(this); - - - connect( input_, SIGNAL( textChanged() ), - this, SLOT( contentChanged() )); - - connect( input_, SIGNAL( clickOnCell() ), - this, SLOT( clickEvent() )); - connect( input_, SIGNAL( wheelMove(QWheelEvent*) ), - this, SLOT( wheelEvent(QWheelEvent*) )); - // 2005-12-15 AF, new connections - connect( input_, SIGNAL( eval() ), - this, SLOT( eval() )); - connect( input_, SIGNAL( command() ), - this, SLOT( command() )); - connect( input_, SIGNAL( nextCommand() ), - this, SLOT( nextCommand() )); - connect( input_, SIGNAL( nextField() ), - this, SLOT( nextField() )); - //2005-12-29 AF - connect( input_, SIGNAL( textChanged() ), - this, SLOT( addToHighlighter() )); - // 2006-01-17 AF, new... - connect( input_, SIGNAL( currentCharFormatChanged(const QTextCharFormat &) ), - this, SLOT( charFormatChanged(const QTextCharFormat &) )); - // 2006-04-27 AF, - connect( input_, SIGNAL( forwardAction(int) ), - this, SIGNAL( forwardAction(int) )); - - contentChanged(); - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2005-10-28 (update) - * - * \brief Creates the QTextEdit for the output part of the - * inputcell - * - * Large part of this function was changes due to porting - * to QT4 (changes from Q3TextEdit to QTextEdit). - */ - void InputCell::createOutputCell() - { - output_ = new MyTextEdit( mainWidget() ); - layout_->addWidget( output_, 2, 1 ); - - output_->setReadOnly( true ); - //output_->setFrameShape( QFrame::Panel ); - output_->setFrameShape( QFrame::Box ); - output_->setAutoFormatting( QTextEdit::AutoNone ); - - output_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - output_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); -// output_->setContextMenuPolicy( Qt::NoContextMenu ); - - connect( output_, SIGNAL( textChanged() ), - this, SLOT(contentChanged())); - connect( output_, SIGNAL( clickOnCell() ), - this, SLOT( clickEventOutput() )); - connect( output_, SIGNAL( wheelMove(QWheelEvent*) ), - this, SLOT( wheelEvent(QWheelEvent*) )); - - connect(output_, SIGNAL(forwardAction(int)), this, SIGNAL(forwardAction(int))); - - setOutputStyle(); - - - output_->hide(); - } - - /*! - * \author Anders Fernström - * \date 2006-04-21 - * - * \brief Set the output style - */ - void InputCell::setOutputStyle() - { - // Set the correct style for the QTextEdit output_ - output_->selectAll(); - - Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); - CellStyle style = sheet->getStyle( "Output" ); - - if( style.name() != "null" ) - { - output_->setAlignment( (Qt::AlignmentFlag)style.alignment() ); - output_->mergeCurrentCharFormat( (*style.textCharFormat()) ); - output_->document()->rootFrame()->setFrameFormat( (*style.textFrameFormat()) ); - } - else - { - // 2006-01-30 AF, add message box - QString msg = "No Output style defened, please define a Output style in stylesheet.xml"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - - QTextCursor cursor = output_->textCursor(); - cursor.clearSelection(); - output_->setTextCursor( cursor ); - } - - /*! - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief Creates the chapter counter - */ - void InputCell::createChapterCounter() - { - chaptercounter_ = new MyTextEdit(this); - chaptercounter_->setFrameStyle( QFrame::NoFrame ); - chaptercounter_->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding)); - chaptercounter_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - chaptercounter_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - chaptercounter_->setContextMenuPolicy( Qt::NoContextMenu ); - - chaptercounter_->setFixedWidth(50); - chaptercounter_->setReadOnly( true ); - - connect( chaptercounter_, SIGNAL( clickOnCell() ), - this, SLOT( clickEvent() )); - - addChapterCounter( chaptercounter_ ); - } - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * - * \brief Returns the text (as plain text) fromthe cell - * - * \return The text, as plain text - */ - QString InputCell::text() - { - return input_->toPlainText(); - } - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * - * \brief Return the text inside the cell as Html code - * - * \return Html code - */ - QString InputCell::textHtml() - { - return input_->toHtml(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-23 - * - * \brief Return the text inside the output part of the cell - * as plain text - * - * \return output text - */ - QString InputCell::textOutput() - { - return output_->toPlainText(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-23 - * - * \brief Return the text inside the output part of the cell - * as html code - * - * \return html code - */ - QString InputCell::textOutputHtml() - { - return output_->toHtml(); - } - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * - * \brief Return the text cursor to the QTextEdit that make up - * the inputpart of the inputcell - * - * \return Text cursor to the cell - */ - QTextCursor InputCell::textCursor() - { - return input_->textCursor(); - } - - /*! - * \author Anders Fernström - * \date 2006-01-05 - * - * \brief Return the input texteditor - * - * \return Texteditor for the inputpart of the inputcell - */ - QTextEdit *InputCell::textEdit() - { - return input_; - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * - * \brief Return the output texteditor - * - * \return Texteditor for the output part of the inputcell - */ - QTextEdit* InputCell::textEditOutput() - { - return output_; - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-12-16 (update) - * - * \brief Set text to the cell - * - * \param text The text that should be placed inside the cell - * - * 2005-10-04 AF, added some code for removing/replacing some text - * 2005-10-27 AF, updated the function due to porting from qt3 to qt4 - * 2005-12-08 AF, added code that removed any document()->blockSignals(true); - - // 2005-10-04 AF, added some code to replace/remove - QString tmp = text.replace("
", "\n"); - tmp.replace( "    ", " " ); - - // 2005-12-08 AF, remove any " ); - tmp.remove( spanEnd ); - int pos = 0; - while( true ) - { - int startpos = tmp.indexOf( "= 0 ) - { - int endpos = tmp.indexOf( "\">", startpos ); - if( endpos >= 0 ) - { - endpos += 2; - tmp.remove( startpos, endpos - startpos ); - } - else - break; - } - else - break; - - pos = startpos; - - } - - // set the text - input_->setPlainText( tmp ); - - // 2005-12-16 AF, unblock signals and tell highlighter to highlight - input_->document()->blockSignals(false); + } + else + { + inCommand = false; + stopHighlighter = false; + + QTextBrowser::keyPressEvent( event ); + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-23 + * + * \brief If the mimedata that should be insertet contain text, + * create a new mimedata object that only contains text, otherwise + * text format is insertet also - don't want that for inputcells. + */ + void MyTextEdit::insertFromMimeData(const QMimeData *source) + { + if( source->hasText() ) + { + QMimeData *newSource = new QMimeData(); + newSource->setText( source->text() ); + QTextBrowser::insertFromMimeData( newSource ); + delete newSource; + } + else + QTextBrowser::insertFromMimeData( source ); + } + + /*! + * \class InputCell + * \author Ingemar Axelsson and Anders Fernström + * + * \brief Describes how an inputcell works. + * + * Input cells is places where the user can do input. To evaluate + * the content of an inputcell just press shift+enter. It will + * throw an exception if it cant find OMC. Start OMC with + * following commandline: + * + * # omc +d=interactiveCorba + * + * + * \todo Make it possiblee to add and change syntax coloring of code.(Ingemar Axelsson) + */ + + int InputCell::numEvals_ = 1; + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-11-23 (update) + * + * \brief The class constructor + * + * 2005-10-27 AF, updated the method due to porting from Q3Support + * to pure QT4 classes. + * 2005-11-23 AF, added document to the constructor, because need + * the document to insert images to the output part if ploting. + */ + InputCell::InputCell(Document *doc, QWidget *parent) + : Cell(parent), + evaluated_(false), + closed_(true), + delegate_(0), + oldHeight_( 0 ), + document_(doc) + { + QWidget *main = new QWidget(this); + setMainWidget(main); + + layout_ = new QGridLayout(mainWidget()); + layout_->setMargin(0); + layout_->setSpacing(0); + + setTreeWidget(new InputTreeView(this)); + + //2005-10-07 AF, Porting, change from 'QWidget::' to 'Qt::' + setFocusPolicy(Qt::NoFocus); + + createInputCell(); + createOutputCell(); + + //setBackgroundColor(QColor(200,200,255)); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * + * \brief The class destructor + */ + InputCell::~InputCell() + { + //2006-01-05 AF, check if input texteditor is in the highlighter, + //if it is - wait for 60 ms and check again. + HighlighterThread *thread = HighlighterThread::instance(); + int sleepTime = 0; + bool firstTime = true; + while( thread->haveEditor( input_ ) ) + { + if( firstTime ) + { + thread->removeEditor( input_ ); + firstTime = false; + } + + SleeperThread::msleep( 60 ); + sleepTime++; + + if( sleepTime > 100 ) + break; + } + + + delete input_; + delete output_; + //delete syntaxHighlighter_; + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2006-03-02 (update) + * + * \brief Creates the QTextEdit for the input part of the + * inputcell + * + * 2005-10-27 AF, Large part of this function was changes due to + * porting to QT4 (changes from Q3TextEdit to QTextEdit). + * 2005-12-15 AF, Added more connections to the editor, mostly for + * commandcompletion, but also for eval. invoking eval have moved + * from the eventfilter on this cell to the reimplemented key event + * handler in the editor + * 2006-03-02 AF, Added call to createChapterCounter(); + */ + void InputCell::createInputCell() + { + input_ = new MyTextEdit( mainWidget() ); + layout_->addWidget( input_, 1, 1 ); + + // 2006-03-02 AF, Add a chapter counter + createChapterCounter(); + + //input_->setReadOnly( false ); + input_->setReadOnly( true ); + input_->setUndoRedoEnabled( true ); + //input_->setFrameStyle( QFrame::NoFrame ); + input_->setFrameShape( QFrame::Box ); + input_->setAutoFormatting( QTextEdit::AutoNone ); + + input_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + input_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); +// input_->setContextMenuPolicy( Qt::NoContextMenu ); + + QPalette palette; + palette.setColor(input_->backgroundRole(), QColor(200,200,255)); + input_->setPalette(palette); + + // is this needed, don't know /AF + input_->installEventFilter(this); + + + connect( input_, SIGNAL( textChanged() ), + this, SLOT( contentChanged() )); + + connect( input_, SIGNAL( clickOnCell() ), + this, SLOT( clickEvent() )); + connect( input_, SIGNAL( wheelMove(QWheelEvent*) ), + this, SLOT( wheelEvent(QWheelEvent*) )); + // 2005-12-15 AF, new connections + connect( input_, SIGNAL( eval() ), + this, SLOT( eval() )); + connect( input_, SIGNAL( command() ), + this, SLOT( command() )); + connect( input_, SIGNAL( nextCommand() ), + this, SLOT( nextCommand() )); + connect( input_, SIGNAL( nextField() ), + this, SLOT( nextField() )); + //2005-12-29 AF + connect( input_, SIGNAL( textChanged() ), + this, SLOT( addToHighlighter() )); + // 2006-01-17 AF, new... + connect( input_, SIGNAL( currentCharFormatChanged(const QTextCharFormat &) ), + this, SLOT( charFormatChanged(const QTextCharFormat &) )); + // 2006-04-27 AF, + connect( input_, SIGNAL( forwardAction(int) ), + this, SIGNAL( forwardAction(int) )); + + contentChanged(); + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2005-10-28 (update) + * + * \brief Creates the QTextEdit for the output part of the + * inputcell + * + * Large part of this function was changes due to porting + * to QT4 (changes from Q3TextEdit to QTextEdit). + */ + void InputCell::createOutputCell() + { + output_ = new MyTextEdit( mainWidget() ); + layout_->addWidget( output_, 2, 1 ); + + output_->setReadOnly( true ); + //output_->setFrameShape( QFrame::Panel ); + output_->setFrameShape( QFrame::Box ); + output_->setAutoFormatting( QTextEdit::AutoNone ); + + output_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + output_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); +// output_->setContextMenuPolicy( Qt::NoContextMenu ); + + connect( output_, SIGNAL( textChanged() ), + this, SLOT(contentChanged())); + connect( output_, SIGNAL( clickOnCell() ), + this, SLOT( clickEventOutput() )); + connect( output_, SIGNAL( wheelMove(QWheelEvent*) ), + this, SLOT( wheelEvent(QWheelEvent*) )); + + connect(output_, SIGNAL(forwardAction(int)), this, SIGNAL(forwardAction(int))); + + setOutputStyle(); + + + output_->hide(); + } + + /*! + * \author Anders Fernström + * \date 2006-04-21 + * + * \brief Set the output style + */ + void InputCell::setOutputStyle() + { + // Set the correct style for the QTextEdit output_ + output_->selectAll(); + + Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); + CellStyle style = sheet->getStyle( "Output" ); + + if( style.name() != "null" ) + { + output_->setAlignment( (Qt::AlignmentFlag)style.alignment() ); + output_->mergeCurrentCharFormat( (*style.textCharFormat()) ); + output_->document()->rootFrame()->setFrameFormat( (*style.textFrameFormat()) ); + } + else + { + // 2006-01-30 AF, add message box + QString msg = "No Output style defened, please define a Output style in stylesheet.xml"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + + QTextCursor cursor = output_->textCursor(); + cursor.clearSelection(); + output_->setTextCursor( cursor ); + } + + /*! + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief Creates the chapter counter + */ + void InputCell::createChapterCounter() + { + chaptercounter_ = new MyTextEdit(this); + chaptercounter_->setFrameStyle( QFrame::NoFrame ); + chaptercounter_->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding)); + chaptercounter_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + chaptercounter_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + chaptercounter_->setContextMenuPolicy( Qt::NoContextMenu ); + + chaptercounter_->setFixedWidth(50); + chaptercounter_->setReadOnly( true ); + + connect( chaptercounter_, SIGNAL( clickOnCell() ), + this, SLOT( clickEvent() )); + + addChapterCounter( chaptercounter_ ); + } + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * + * \brief Returns the text (as plain text) fromthe cell + * + * \return The text, as plain text + */ + QString InputCell::text() + { + return input_->toPlainText(); + } + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * + * \brief Return the text inside the cell as Html code + * + * \return Html code + */ + QString InputCell::textHtml() + { + return input_->toHtml(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-23 + * + * \brief Return the text inside the output part of the cell + * as plain text + * + * \return output text + */ + QString InputCell::textOutput() + { + return output_->toPlainText(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-23 + * + * \brief Return the text inside the output part of the cell + * as html code + * + * \return html code + */ + QString InputCell::textOutputHtml() + { + return output_->toHtml(); + } + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * + * \brief Return the text cursor to the QTextEdit that make up + * the inputpart of the inputcell + * + * \return Text cursor to the cell + */ + QTextCursor InputCell::textCursor() + { + return input_->textCursor(); + } + + /*! + * \author Anders Fernström + * \date 2006-01-05 + * + * \brief Return the input texteditor + * + * \return Texteditor for the inputpart of the inputcell + */ + QTextEdit *InputCell::textEdit() + { + return input_; + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * + * \brief Return the output texteditor + * + * \return Texteditor for the output part of the inputcell + */ + QTextEdit* InputCell::textEditOutput() + { + return output_; + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-12-16 (update) + * + * \brief Set text to the cell + * + * \param text The text that should be placed inside the cell + * + * 2005-10-04 AF, added some code for removing/replacing some text + * 2005-10-27 AF, updated the function due to porting from qt3 to qt4 + * 2005-12-08 AF, added code that removed any document()->blockSignals(true); + + // 2005-10-04 AF, added some code to replace/remove + QString tmp = text.replace("
", "\n"); + tmp.replace( "    ", " " ); + + // 2005-12-08 AF, remove any " ); + tmp.remove( spanEnd ); + int pos = 0; + while( true ) + { + int startpos = tmp.indexOf( "= 0 ) + { + int endpos = tmp.indexOf( "\">", startpos ); + if( endpos >= 0 ) + { + endpos += 2; + tmp.remove( startpos, endpos - startpos ); + } + else + break; + } + else + break; + + pos = startpos; + + } + + // set the text + input_->setPlainText( tmp ); + + // 2005-12-16 AF, unblock signals and tell highlighter to highlight + input_->document()->blockSignals(false); // input_->document()->setHtml( input_->toHtml() ); -// input_->document()->setPlainText( input_->toPlainText() ); // This causes a crash with Qt >= 4.2 - input_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); - - contentChanged(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-01 - * - * \brief Sets the visible text using html code. - * - * Sets the text that should be visible using html code. Can change - * the cellheight if the text is very long. - * - * \param html Html code that should be visible as normal text inside the cell mainarea. - */ - void InputCell::setTextHtml(QString html) - { - input_->setHtml( html ); - setStyle( style_ ); - - contentChanged(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-23 - * - * \brief Set text to the output part of the cell - * - * \param text The text that should be placed inside the output part - */ - void InputCell::setTextOutput(QString text) - { - if( !text.isNull() && !text.isEmpty() ) - { - output_->setPlainText( text ); - evaluated_ = true; - //setClosed( false ); - - contentChanged(); - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-23 - * - * \brief Sets the output text using html code. - * - * Sets the text that should be visible in the output part of the - * cell using html code. Can change the cellheight if the text is - * very long. - * - * \param html Html code that should be visible as normal text inside the cell mainarea. - */ - void InputCell::setTextOutputHtml(QString html) - { - if( !html.isNull() && !html.isEmpty() ) - { - output_->setHtml( html ); - evaluated_ = true; - //setClosed( false ); - - contentChanged(); - } - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Set cell style - * - * IMPORTANT: User shouldn't be able to change style on inputcells - * so this function always use "Input" as style. - * - * \param stylename The style name of the style that is to be applyed to the cell - */ - void InputCell::setStyle(const QString &) - { - Cell::setStyle( "Input" ); - } - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * \date 2006-03-02 (update) - * - * \brief Set cell style - * - * IMPORTANT: User shouldn't be able to change style on inputcells - * so this function always use "Input" as style. - * - * 2005-11-03 AF, updated so the text is selected when the style - * is changed, after the text is unselected. - * 2006-03-02 AF, set chapter style - * - * \param style The cell style that is to be applyed to the cell - */ - void InputCell::setStyle(CellStyle style) - { - if( style.name() == "Input" ) - { - Cell::setStyle( style ); - - // select all the text - input_->selectAll(); - - // set the new style settings - input_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); - input_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); - input_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); - - // unselect the text - QTextCursor cursor( input_->textCursor() ); - cursor.clearSelection(); - input_->setTextCursor( cursor ); - - // 2006-03-02 AF, set chapter counter style - chaptercounter_->selectAll(); - chaptercounter_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); - - QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); - format.setMargin( style_.textFrameFormat()->margin() + - style_.textFrameFormat()->border() + - style_.textFrameFormat()->padding() ); - chaptercounter_->document()->rootFrame()->setFrameFormat( format ); - - chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); - - cursor = chaptercounter_->textCursor(); - cursor.clearSelection(); - chaptercounter_->setTextCursor( cursor ); - } - else - { - setStyle( "Input" ); - } - } - - /*! - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief set the chapter counter - */ - void InputCell::setChapterCounter( QString number ) - { - chaptercounter_->selectAll(); - chaptercounter_->setPlainText( number ); - chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); - QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); - format.setMargin( style_.textFrameFormat()->margin() + - style_.textFrameFormat()->border() + - style_.textFrameFormat()->padding() ); - chaptercounter_->document()->rootFrame()->setFrameFormat( format ); - } - - /*! - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief return the value of the chapter counter, as plain text. - * Returns null if the counter is empty - */ - QString InputCell::ChapterCounter() - { - if( chaptercounter_->toPlainText().isEmpty() ) - return QString::null; - - return chaptercounter_->toPlainText(); - } - - /*! - * \author Anders Fernström - * \date 2006-03-03 - * - * \brief return the value of the chapter counter, as html code. - * Returns null if the counter is empty - */ - QString InputCell::ChapterCounterHtml() - { - if( chaptercounter_->toPlainText().isEmpty() ) - return QString::null; - - return chaptercounter_->toHtml(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-01 - * \date 2006-03-02 (update) - * - * \breif Set readonly value on the texteditor - * - * \param readonly The boolean value of readonly property - * - * 2006-03-02 AF, clear text selection in chapter counter - */ - void InputCell::setReadOnly(const bool readonly) - { - if( readonly ) - { - QTextCursor cursor = input_->textCursor(); - cursor.clearSelection(); - input_->setTextCursor( cursor ); - - cursor = output_->textCursor(); - cursor.clearSelection(); - output_->setTextCursor( cursor ); - - // 2006-03-02 AF, clear selection in chapter counter - cursor = chaptercounter_->textCursor(); - cursor.clearSelection(); - chaptercounter_->setTextCursor( cursor ); - } - - input_->setReadOnly(readonly); - } - - /*! - * \author Anders Fernström - * \date 2006-01-16 - * - * \breif Set evaluated value on the texteditor - * - * \param evaluated The boolean value of evaluated property - */ - void InputCell::setEvaluated(const bool evaluated) - { - evaluated_ = evaluated; - } - - /*! - * \author Ingemar Axelsson (and Anders Fernström) - * \date 2005-11-01 (update) - * - * \breif Set if the output part of the cell shoud be - * closed(hidden) or not. - * - * 2005-11-01 AF, Made some small changes to how the function - * calculate the new height, to reflect the changes made when - * porting from Q3TextEdit to QTextEdit. - */ - void InputCell::setClosed(const bool closed, bool update) - { - if( closed ) - output_->hide(); - else - { - if( evaluated_ ) - output_->show(); - } - - closed_ = closed; - contentChanged(); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - */ - void InputCell::setFocus(const bool focus) - { - if(focus) - input_->setFocus(); - } - - /*! - * \author Anders Fernström - */ - void InputCell::setFocusOutput(const bool focus) - { - if(focus) - output_->setFocus(); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - */ - void InputCell::clickEvent() - { - //if( input_->isReadOnly() ) - emit clicked(this); - } - - /*! - * \author Anders Fernström - */ - void InputCell::clickEventOutput() - { - emit clickedOutput(this); - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2006-04-10 (update) - * - * \breif Recalculates height. - * - * 2005-10-31 AF, Large part of this function was changes due to - * porting to QT4 (changes from Q3TextBrowser to QTextBrowser). - * 2006-04-10 AF, emits heightChanged if the height changes - */ - void InputCell::contentChanged() - { - int height = input_->document()->documentLayout()->documentSize().toSize().height(); - - if( height < 0 ) - height = 30; - - // add a little extra, just in case /AF - input_->setMinimumHeight( height + 3 ); - - if( evaluated_ && !closed_ ) - { - int outHeight = output_->document()->documentLayout()->documentSize().toSize().height(); - - if( outHeight < 0 ) - outHeight = 30; - - output_->setMinimumHeight( outHeight ); - height += outHeight; - } - - // add a little extra, just in case, emit 'heightChanged()' if height - // have chagned /AF - setHeight( height + 3 ); - emit textChanged(); - - if( oldHeight_ != (height + 3) ) - emit heightChanged(); - - oldHeight_ = height + 3; - } - - /*! - * \author Anders Fernström - * \date 2006-01-17 - * - * \brief Returns true if inputcell is closed, otherwise the method - * returns false. - * - * \return State of inputcell (closed or not) - */ - bool InputCell::isClosed() - { - return closed_; - } - - /*! - * \author Anders Fernström - * \date 2005-10-27 - * - * \brief Function for telling if the user is allowed to change - * the text settings for the text inside the cell. User isn't - * allowed to change the text settings for inputcell so this - * function always return false. - * - * \return False - */ - bool InputCell::isEditable() - { - return false; - } - - /*! - * \author Anders Fernström - * \date 2005-11-23 - * - * \brief Returns true if inputcell is evaluated, returns false if - * inputcell haven't been evaluated. - * - * \return State of inputcell (evaluated or not) - */ - bool InputCell::isEvaluated() - { - return evaluated_; - } - - /*! - * \author Anders Fernström - * \date 2005-11-23 - * - * \brief Returns true if the expression in the text is a plot - * command, returns false otherwise. If no text is sent to the - * method it will test the text in the input part of the cell. - * - * \param text The text that should be tested, if no text the - * inputpart of the cell will be tested. - * \return If plot command or not - */ - bool InputCell::isJavaPlot(QString text) - { - QRegExp exp( "plot2\\((.*)|plotParametric2\\((.*)" ); - - - if( text.isNull() ) - { - if( 0 <= input_->toPlainText().indexOf( exp, 0 ) ) - return true; - else - return false; - } - else - { - if( 0 <= text.indexOf( exp, 0 ) ) - return true; - else - return false; - - } - } - - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2006-04-18 (update) - * - *\brief Sends the content of the inputcell to the evaluator. - * Displays the result in a outputcell. - * - * 2005-11-01 AF, updated so the text that is sent to be evaled isn't - * in html code. - * 2005-11-17 AF, added a check if the result if empty, if so add - * some default text - * 2005-11-23 AF, added support for inserting image to output - * 2006-04-18 AF, uses environment variable to find the plot - * - * Removes whitespaces and tags from the content string. Then sends - * the content to the delegate object for evaluation. The result is - * printed in a output cell. No indentation and syntax - * highlightning is used in the output cell. - * - */ - void InputCell::eval() - { - input_->blockSignals(true); - output_->blockSignals(true); - - if( hasDelegate() ) - { - // Only the text, no html tags. /AF - QString expr = input_->toPlainText(); - //expr = expr.simplified(); - - - QString openmodelica = OmcInteractiveEnvironment::OpenModelicaHome(); - if( openmodelica.isEmpty() ) - QMessageBox::critical( 0, "OpenModelica Error", "Could not find environment variable OPENMODELICAHOME; OMNotebook will therefore not work correctly" ); - - if( openmodelica.endsWith("/") || openmodelica.endsWith( "\\") ) - openmodelica += "tmp/"; - else - openmodelica += "/tmp/"; - - QString imagename = "omc_tmp_plot.png"; - - QDir dir1 = QDir::current(); - QString filename1 = dir1.absolutePath(); - - QDir dir2 = QDir::current(); dir2.setPath( openmodelica ); - QString filename2 = dir2.absolutePath(); - if( !filename1.endsWith( "/" ) ) filename1 += "/"; - filename1 += imagename; - if( !filename2.endsWith( "/" ) ) filename2 += "/"; - filename2 += imagename; - - // 2006-02-17 AF, - evaluated_ = true; - setClosed(false); - - // 2006-02-17 AF, set text '{evaluation expression}" during - // evaluation of expressiuon - output_->selectAll(); - output_->textCursor().insertText( "{evaluating expression}" ); - setOutputStyle(); - //output_->setPlainText( "{evaluating expression}" ); - output_->update(); - QCoreApplication::processEvents(); - - - // remove plot.png if it already exist, don't want any - // old plot. - if( isJavaPlot(input_->toPlainText()) ) - { - if( dir1.exists( imagename )) - dir1.remove( imagename ); - if( dir2.exists( imagename )) - dir2.remove( imagename ); - } - - // 2006-02-02 AF, Added try-catch - try - { - delegate()->evalExpression( expr ); - } - catch( exception &e ) - { - exceptionInEval(e); - input_->blockSignals(false); - output_->blockSignals(false); - return; - } - - // 2005-11-24 AF, added check to see if the user wants to quit - if( 0 == expr.indexOf( "quit()", 0, Qt::CaseSensitive )) - { - qApp->closeAllWindows(); - input_->blockSignals(false); - output_->blockSignals(false); - return; - } - - // get the result - QString res = delegate()->getResult(); - QString error; - - // 2006-02-02 AF, Added try-catch - try - { - error = delegate()->getError(); - } - catch( exception &e ) - { - exceptionInEval(e); - input_->blockSignals(false); - output_->blockSignals(false); - return; - } - - - // if the expression is a plot command and the is no errors - // in the result, find the image and insert it into the - // output part of the cell. - if( isJavaPlot(input_->toPlainText()) && error.isEmpty() ) - { - - output_->selectAll(); - output_->textCursor().insertText( "{creating plot}" ); - //output_->setPlainText( "{creating plot}" ); - output_->update(); - QCoreApplication::processEvents(); - - int sleepTime = 1; - bool firstTry = true; - while( true ) - { - QString filename = ""; - bool foundIt = false; - /* Search BOTH $OPENMODELICA/tmp and the current directory! */ - if( dir1.exists( imagename )) { filename = filename1; foundIt = true; } - else if( dir2.exists( imagename )) { filename = filename2; foundIt = true; } - - if (foundIt) - { - QImage *image = new QImage( filename ); - if( !image->isNull() ) - { - QString newname = document_->addImage( image ); - QTextCharFormat format = output_->currentCharFormat(); - - QTextImageFormat imageformat; - imageformat.merge( format ); - imageformat.setHeight( image->height() ); - imageformat.setWidth( image->width() ); - imageformat.setName( newname ); - - output_->selectAll(); - //output_->textCursor().insertText( "{Plot - Generated by PtPlot}" ); - //output_->setPlainText("{Plot}\n"); - QTextCursor outCursor = output_->textCursor(); - //outCursor.movePosition( QTextCursor::End ); - outCursor.insertImage( imageformat ); - break; - } - else - { - if( firstTry ) - { - firstTry = false; - delete image; - } - else - { - output_->selectAll(); - output_->textCursor().insertText( "[Error] Unable to read plot image \"" + - filename1 + " or " + filename2 + "\". Please retry." ); - break; - } - } - } - - if( sleepTime > 25 ) - { - output_->selectAll(); - output_->textCursor().insertText( "[Error] Unable to find plot image \"" + - filename1 + " or " + filename2 + "\"" ); - break; - } - - SleeperThread::msleep( 1000 ); - sleepTime++; - } - - } - else - { - // check if resualt is empty - if( res.isEmpty() && error.isEmpty() ) - res = "[done]"; - - if( !error.isEmpty() ) - res += QString("\n") + error; - - output_->selectAll(); - output_->textCursor().insertText( res ); - //output_->setPlainText( res ); - } - - ++numEvals_; - /* remove the image */ - if( dir1.exists( imagename )) - dir1.remove( imagename ); - if( dir2.exists( imagename )) - dir2.remove( imagename ); - - contentChanged(); - - //Emit that the text have changed - emit textChanged(true); - } - else - cout << "Not delegate on inputcell" << endl; - - input_->blockSignals(false); - output_->blockSignals(false); - } - - /*! - * \author Anders Fernström - * \date 2006-02-02 - * \date 2006-02-09 (update) - * - *\brief Method for handleing exceptions in eval() - */ - void InputCell::exceptionInEval(exception &e) - { - // 2006-0-09 AF, try to reconnect to OMC first. - try - { - delegate_->closeConnection(); - delegate_->reconnect(); - eval(); - } - catch( exception &e ) - { - // unable to reconnect, ask if user want to restart omc. - QString msg = QString( e.what() ) + "\n\nUnable to reconnect with OMC. Do you want to restart OMC?"; - int result = QMessageBox::critical( 0, tr("Communication Error with OMC"), - msg, - QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No ); - - if( result == QMessageBox::Yes ) - { - delegate_->closeConnection(); - if( delegate_->startDelegate() ) - { - // 2006-03-14 AF, wait before trying to reconnect, - // give OMC time to start up - SleeperThread::msleep( 1000 ); - - //delegate_->closeConnection(); - try - { - delegate_->reconnect(); - eval(); - } - catch( exception &e ) - { - QMessageBox::critical( 0, tr("Communication Error"), - tr("Unable to communication correctlly with OMC.") ); - } - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-12-15 - * - *\brief Get/Insert the command that match the last word in the - * input editor. - */ - void InputCell::command() - { - CommandCompletion *commandcompletion = CommandCompletion::instance( "commands.xml" ); - QTextCursor cursor = input_->textCursor(); - - if( commandcompletion->insertCommand( cursor )) - input_->setTextCursor( cursor ); - } - - /*! - * \author Anders Fernström - * \date 2005-12-15 - * - *\brief Get/Insert the next command that match the last word in - * the input editor. - */ - void InputCell::nextCommand() - { - qDebug("Next Command"); - CommandCompletion *commandcompletion = CommandCompletion::instance( "commands.xml" ); - QTextCursor cursor = input_->textCursor(); - - if( commandcompletion->nextCommand( cursor )) - input_->setTextCursor( cursor ); - } - - /*! - * \author Anders Fernström - * \date 2005-12-15 - * - *\brief Select the next field in the command, if any exists - */ - void InputCell::nextField() - { - qDebug("Next Field"); - CommandCompletion *commandcompletion = CommandCompletion::instance( "commands.xml" ); - QTextCursor cursor = input_->textCursor(); - - if( commandcompletion->nextField( cursor )) - input_->setTextCursor( cursor ); - } - - /*! - * \author Anders Fernström - * \date 2005-12-29 - * \date 2006-01-16 (update) - * - * \breif adds the input text editor to the highlighter thread - * when text have changed. - * - * 2006-01-16 AF, don't add text editor if MyTextEdit says NO - */ - void InputCell::addToHighlighter() - { - emit textChanged(true); - - if( input_->toPlainText().isEmpty() ) - return; - - // 2006-01-16 AF, Don't add the text editor if mytextedit - // don't allow it. mytextedit says no if the user removes - // text (backspace or delete). - if( dynamic_cast(input_)->isStopingHighlighter() ) - return; - - HighlighterThread *thread = HighlighterThread::instance(); - thread->addEditor( input_ ); - } - - /*! - * \author Anders Fernström - * \date 2006-01-17 - * - * \breif set the correct style if the charFormat is changed and the - * cell is empty. This is done because otherwise the style is lost if - * all text is removed inside a cell. - */ - void InputCell::charFormatChanged(const QTextCharFormat &) - { - //if( input_->toPlainText().isEmpty() ) - //{ - input_->blockSignals( true ); - input_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); - input_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); - input_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); - input_->blockSignals( false ); - contentChanged(); - //} - } - - - - - // *************************************************************** - - - /*! \brief Sets the evaulator delegate. - */ - void InputCell::setDelegate(InputCellDelegate *d) - { - delegate_ = d; - } - - InputCellDelegate *InputCell::delegate() - { - if(!hasDelegate()) - throw runtime_error("No delegate."); - - return delegate_; - } - - - - bool InputCell::hasDelegate() - { - return delegate_ != 0; - } - - - - - - - - - - - /*! \brief Do not use this member. - * - * This is an ugly part of the cell structure. - */ - void InputCell::addCellWidgets() - { - layout_->addWidget(input_,0,0); +// input_->document()->setPlainText( input_->toPlainText() ); // This causes a crash with Qt >= 4.2 + input_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); + + contentChanged(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-01 + * + * \brief Sets the visible text using html code. + * + * Sets the text that should be visible using html code. Can change + * the cellheight if the text is very long. + * + * \param html Html code that should be visible as normal text inside the cell mainarea. + */ + void InputCell::setTextHtml(QString html) + { + input_->setHtml( html ); + setStyle( style_ ); + + contentChanged(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-23 + * + * \brief Set text to the output part of the cell + * + * \param text The text that should be placed inside the output part + */ + void InputCell::setTextOutput(QString text) + { + if( !text.isNull() && !text.isEmpty() ) + { + output_->setPlainText( text ); + evaluated_ = true; + //setClosed( false ); + + contentChanged(); + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-23 + * + * \brief Sets the output text using html code. + * + * Sets the text that should be visible in the output part of the + * cell using html code. Can change the cellheight if the text is + * very long. + * + * \param html Html code that should be visible as normal text inside the cell mainarea. + */ + void InputCell::setTextOutputHtml(QString html) + { + if( !html.isNull() && !html.isEmpty() ) + { + output_->setHtml( html ); + evaluated_ = true; + //setClosed( false ); + + contentChanged(); + } + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Set cell style + * + * IMPORTANT: User shouldn't be able to change style on inputcells + * so this function always use "Input" as style. + * + * \param stylename The style name of the style that is to be applyed to the cell + */ + void InputCell::setStyle(const QString &) + { + Cell::setStyle( "Input" ); + } + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * \date 2006-03-02 (update) + * + * \brief Set cell style + * + * IMPORTANT: User shouldn't be able to change style on inputcells + * so this function always use "Input" as style. + * + * 2005-11-03 AF, updated so the text is selected when the style + * is changed, after the text is unselected. + * 2006-03-02 AF, set chapter style + * + * \param style The cell style that is to be applyed to the cell + */ + void InputCell::setStyle(CellStyle style) + { + if( style.name() == "Input" ) + { + Cell::setStyle( style ); + + // select all the text + input_->selectAll(); + + // set the new style settings + input_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); + input_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); + input_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); + + // unselect the text + QTextCursor cursor( input_->textCursor() ); + cursor.clearSelection(); + input_->setTextCursor( cursor ); + + // 2006-03-02 AF, set chapter counter style + chaptercounter_->selectAll(); + chaptercounter_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); + + QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); + format.setMargin( style_.textFrameFormat()->margin() + + style_.textFrameFormat()->border() + + style_.textFrameFormat()->padding() ); + chaptercounter_->document()->rootFrame()->setFrameFormat( format ); + + chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); + + cursor = chaptercounter_->textCursor(); + cursor.clearSelection(); + chaptercounter_->setTextCursor( cursor ); + } + else + { + setStyle( "Input" ); + } + } + + /*! + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief set the chapter counter + */ + void InputCell::setChapterCounter( QString number ) + { + chaptercounter_->selectAll(); + chaptercounter_->setPlainText( number ); + chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); + QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); + format.setMargin( style_.textFrameFormat()->margin() + + style_.textFrameFormat()->border() + + style_.textFrameFormat()->padding() ); + chaptercounter_->document()->rootFrame()->setFrameFormat( format ); + } + + /*! + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief return the value of the chapter counter, as plain text. + * Returns null if the counter is empty + */ + QString InputCell::ChapterCounter() + { + if( chaptercounter_->toPlainText().isEmpty() ) + return QString::null; + + return chaptercounter_->toPlainText(); + } + + /*! + * \author Anders Fernström + * \date 2006-03-03 + * + * \brief return the value of the chapter counter, as html code. + * Returns null if the counter is empty + */ + QString InputCell::ChapterCounterHtml() + { + if( chaptercounter_->toPlainText().isEmpty() ) + return QString::null; + + return chaptercounter_->toHtml(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-01 + * \date 2006-03-02 (update) + * + * \breif Set readonly value on the texteditor + * + * \param readonly The boolean value of readonly property + * + * 2006-03-02 AF, clear text selection in chapter counter + */ + void InputCell::setReadOnly(const bool readonly) + { + if( readonly ) + { + QTextCursor cursor = input_->textCursor(); + cursor.clearSelection(); + input_->setTextCursor( cursor ); + + cursor = output_->textCursor(); + cursor.clearSelection(); + output_->setTextCursor( cursor ); + + // 2006-03-02 AF, clear selection in chapter counter + cursor = chaptercounter_->textCursor(); + cursor.clearSelection(); + chaptercounter_->setTextCursor( cursor ); + } + + input_->setReadOnly(readonly); + } + + /*! + * \author Anders Fernström + * \date 2006-01-16 + * + * \breif Set evaluated value on the texteditor + * + * \param evaluated The boolean value of evaluated property + */ + void InputCell::setEvaluated(const bool evaluated) + { + evaluated_ = evaluated; + } + + /*! + * \author Ingemar Axelsson (and Anders Fernström) + * \date 2005-11-01 (update) + * + * \breif Set if the output part of the cell shoud be + * closed(hidden) or not. + * + * 2005-11-01 AF, Made some small changes to how the function + * calculate the new height, to reflect the changes made when + * porting from Q3TextEdit to QTextEdit. + */ + void InputCell::setClosed(const bool closed, bool update) + { + if( closed ) + output_->hide(); + else + { + if( evaluated_ ) + output_->show(); + } + + closed_ = closed; + contentChanged(); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + */ + void InputCell::setFocus(const bool focus) + { + if(focus) + input_->setFocus(); + } + + /*! + * \author Anders Fernström + */ + void InputCell::setFocusOutput(const bool focus) + { + if(focus) + output_->setFocus(); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + */ + void InputCell::clickEvent() + { + //if( input_->isReadOnly() ) + emit clicked(this); + } + + /*! + * \author Anders Fernström + */ + void InputCell::clickEventOutput() + { + emit clickedOutput(this); + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2006-04-10 (update) + * + * \breif Recalculates height. + * + * 2005-10-31 AF, Large part of this function was changes due to + * porting to QT4 (changes from Q3TextBrowser to QTextBrowser). + * 2006-04-10 AF, emits heightChanged if the height changes + */ + void InputCell::contentChanged() + { + int height = input_->document()->documentLayout()->documentSize().toSize().height(); + + if( height < 0 ) + height = 30; + + // add a little extra, just in case /AF + input_->setMinimumHeight( height + 3 ); + + if( evaluated_ && !closed_ ) + { + int outHeight = output_->document()->documentLayout()->documentSize().toSize().height(); + + if( outHeight < 0 ) + outHeight = 30; + + output_->setMinimumHeight( outHeight ); + height += outHeight; + } + + // add a little extra, just in case, emit 'heightChanged()' if height + // have chagned /AF + setHeight( height + 3 ); + emit textChanged(); + + if( oldHeight_ != (height + 3) ) + emit heightChanged(); + + oldHeight_ = height + 3; + } + + /*! + * \author Anders Fernström + * \date 2006-01-17 + * + * \brief Returns true if inputcell is closed, otherwise the method + * returns false. + * + * \return State of inputcell (closed or not) + */ + bool InputCell::isClosed() + { + return closed_; + } + + /*! + * \author Anders Fernström + * \date 2005-10-27 + * + * \brief Function for telling if the user is allowed to change + * the text settings for the text inside the cell. User isn't + * allowed to change the text settings for inputcell so this + * function always return false. + * + * \return False + */ + bool InputCell::isEditable() + { + return false; + } + + /*! + * \author Anders Fernström + * \date 2005-11-23 + * + * \brief Returns true if inputcell is evaluated, returns false if + * inputcell haven't been evaluated. + * + * \return State of inputcell (evaluated or not) + */ + bool InputCell::isEvaluated() + { + return evaluated_; + } + + /*! + * \author Anders Fernström + * \date 2005-11-23 + * + * \brief Returns true if the expression in the text is a plot + * command, returns false otherwise. If no text is sent to the + * method it will test the text in the input part of the cell. + * + * \param text The text that should be tested, if no text the + * inputpart of the cell will be tested. + * \return If plot command or not + */ + bool InputCell::isJavaPlot(QString text) + { + QRegExp exp( "plot2\\((.*)|plotParametric2\\((.*)" ); + + + if( text.isNull() ) + { + if( 0 <= input_->toPlainText().indexOf( exp, 0 ) ) + return true; + else + return false; + } + else + { + if( 0 <= text.indexOf( exp, 0 ) ) + return true; + else + return false; + + } + } + + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2006-04-18 (update) + * + *\brief Sends the content of the inputcell to the evaluator. + * Displays the result in a outputcell. + * + * 2005-11-01 AF, updated so the text that is sent to be evaled isn't + * in html code. + * 2005-11-17 AF, added a check if the result if empty, if so add + * some default text + * 2005-11-23 AF, added support for inserting image to output + * 2006-04-18 AF, uses environment variable to find the plot + * + * Removes whitespaces and tags from the content string. Then sends + * the content to the delegate object for evaluation. The result is + * printed in a output cell. No indentation and syntax + * highlightning is used in the output cell. + * + */ + void InputCell::eval() + { + input_->blockSignals(true); + output_->blockSignals(true); + + if( hasDelegate() ) + { + // Only the text, no html tags. /AF + QString expr = input_->toPlainText(); + //expr = expr.simplified(); + + + QString openmodelica = OmcInteractiveEnvironment::OpenModelicaHome(); + if( openmodelica.isEmpty() ) + QMessageBox::critical( 0, "OpenModelica Error", "Could not find environment variable OPENMODELICAHOME; OMNotebook will therefore not work correctly" ); + + if( openmodelica.endsWith("/") || openmodelica.endsWith( "\\") ) + openmodelica += "tmp/"; + else + openmodelica += "/tmp/"; + + QString imagename = "omc_tmp_plot.png"; + + QDir dir1 = QDir::current(); + QString filename1 = dir1.absolutePath(); + + QDir dir2 = QDir::current(); dir2.setPath( openmodelica ); + QString filename2 = dir2.absolutePath(); + if( !filename1.endsWith( "/" ) ) filename1 += "/"; + filename1 += imagename; + if( !filename2.endsWith( "/" ) ) filename2 += "/"; + filename2 += imagename; + + // 2006-02-17 AF, + evaluated_ = true; + setClosed(false); + + // 2006-02-17 AF, set text '{evaluation expression}" during + // evaluation of expressiuon + output_->selectAll(); + output_->textCursor().insertText( "{evaluating expression}" ); + setOutputStyle(); + //output_->setPlainText( "{evaluating expression}" ); + output_->update(); + QCoreApplication::processEvents(); + + + // remove plot.png if it already exist, don't want any + // old plot. + if( isJavaPlot(input_->toPlainText()) ) + { + if( dir1.exists( imagename )) + dir1.remove( imagename ); + if( dir2.exists( imagename )) + dir2.remove( imagename ); + } + + // 2006-02-02 AF, Added try-catch + try + { + delegate()->evalExpression( expr ); + } + catch( exception &e ) + { + exceptionInEval(e); + input_->blockSignals(false); + output_->blockSignals(false); + return; + } + + // 2005-11-24 AF, added check to see if the user wants to quit + if( 0 == expr.indexOf( "quit()", 0, Qt::CaseSensitive )) + { + qApp->closeAllWindows(); + input_->blockSignals(false); + output_->blockSignals(false); + return; + } + + // get the result + QString res = delegate()->getResult(); + QString error; + + // 2006-02-02 AF, Added try-catch + try + { + error = delegate()->getError(); + } + catch( exception &e ) + { + exceptionInEval(e); + input_->blockSignals(false); + output_->blockSignals(false); + return; + } + + + // if the expression is a plot command and the is no errors + // in the result, find the image and insert it into the + // output part of the cell. + if( isJavaPlot(input_->toPlainText()) && error.isEmpty() ) + { + + output_->selectAll(); + output_->textCursor().insertText( "{creating plot}" ); + //output_->setPlainText( "{creating plot}" ); + output_->update(); + QCoreApplication::processEvents(); + + int sleepTime = 1; + bool firstTry = true; + while( true ) + { + QString filename = ""; + bool foundIt = false; + /* Search BOTH $OPENMODELICA/tmp and the current directory! */ + if( dir1.exists( imagename )) { filename = filename1; foundIt = true; } + else if( dir2.exists( imagename )) { filename = filename2; foundIt = true; } + + if (foundIt) + { + QImage *image = new QImage( filename ); + if( !image->isNull() ) + { + QString newname = document_->addImage( image ); + QTextCharFormat format = output_->currentCharFormat(); + + QTextImageFormat imageformat; + imageformat.merge( format ); + imageformat.setHeight( image->height() ); + imageformat.setWidth( image->width() ); + imageformat.setName( newname ); + + output_->selectAll(); + //output_->textCursor().insertText( "{Plot - Generated by PtPlot}" ); + //output_->setPlainText("{Plot}\n"); + QTextCursor outCursor = output_->textCursor(); + //outCursor.movePosition( QTextCursor::End ); + outCursor.insertImage( imageformat ); + break; + } + else + { + if( firstTry ) + { + firstTry = false; + delete image; + } + else + { + output_->selectAll(); + output_->textCursor().insertText( "[Error] Unable to read plot image \"" + + filename1 + " or " + filename2 + "\". Please retry." ); + break; + } + } + } + + if( sleepTime > 25 ) + { + output_->selectAll(); + output_->textCursor().insertText( "[Error] Unable to find plot image \"" + + filename1 + " or " + filename2 + "\"" ); + break; + } + + SleeperThread::msleep( 1000 ); + sleepTime++; + } + + } + else + { + // check if resualt is empty + if( res.isEmpty() && error.isEmpty() ) + res = "[done]"; + + if( !error.isEmpty() ) + res += QString("\n") + error; + + output_->selectAll(); + output_->textCursor().insertText( res ); + //output_->setPlainText( res ); + } + + ++numEvals_; + /* remove the image */ + if( dir1.exists( imagename )) + dir1.remove( imagename ); + if( dir2.exists( imagename )) + dir2.remove( imagename ); + + contentChanged(); + + //Emit that the text have changed + emit textChanged(true); + } + else + cout << "Not delegate on inputcell" << endl; + + input_->blockSignals(false); + output_->blockSignals(false); + } + + /*! + * \author Anders Fernström + * \date 2006-02-02 + * \date 2006-02-09 (update) + * + *\brief Method for handleing exceptions in eval() + */ + void InputCell::exceptionInEval(exception &e) + { + // 2006-0-09 AF, try to reconnect to OMC first. + try + { + delegate_->closeConnection(); + delegate_->reconnect(); + eval(); + } + catch( exception &e ) + { + // unable to reconnect, ask if user want to restart omc. + QString msg = QString( e.what() ) + "\n\nUnable to reconnect with OMC. Do you want to restart OMC?"; + int result = QMessageBox::critical( 0, tr("Communication Error with OMC"), + msg, + QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No ); + + if( result == QMessageBox::Yes ) + { + delegate_->closeConnection(); + if( delegate_->startDelegate() ) + { + // 2006-03-14 AF, wait before trying to reconnect, + // give OMC time to start up + SleeperThread::msleep( 1000 ); + + //delegate_->closeConnection(); + try + { + delegate_->reconnect(); + eval(); + } + catch( exception &e ) + { + QMessageBox::critical( 0, tr("Communication Error"), + tr("Unable to communication correctlly with OMC.") ); + } + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-12-15 + * + *\brief Get/Insert the command that match the last word in the + * input editor. + */ + void InputCell::command() + { + CommandCompletion *commandcompletion = CommandCompletion::instance( "commands.xml" ); + QTextCursor cursor = input_->textCursor(); + + if( commandcompletion->insertCommand( cursor )) + input_->setTextCursor( cursor ); + } + + /*! + * \author Anders Fernström + * \date 2005-12-15 + * + *\brief Get/Insert the next command that match the last word in + * the input editor. + */ + void InputCell::nextCommand() + { + qDebug("Next Command"); + CommandCompletion *commandcompletion = CommandCompletion::instance( "commands.xml" ); + QTextCursor cursor = input_->textCursor(); + + if( commandcompletion->nextCommand( cursor )) + input_->setTextCursor( cursor ); + } + + /*! + * \author Anders Fernström + * \date 2005-12-15 + * + *\brief Select the next field in the command, if any exists + */ + void InputCell::nextField() + { + qDebug("Next Field"); + CommandCompletion *commandcompletion = CommandCompletion::instance( "commands.xml" ); + QTextCursor cursor = input_->textCursor(); + + if( commandcompletion->nextField( cursor )) + input_->setTextCursor( cursor ); + } + + /*! + * \author Anders Fernström + * \date 2005-12-29 + * \date 2006-01-16 (update) + * + * \breif adds the input text editor to the highlighter thread + * when text have changed. + * + * 2006-01-16 AF, don't add text editor if MyTextEdit says NO + */ + void InputCell::addToHighlighter() + { + emit textChanged(true); + + if( input_->toPlainText().isEmpty() ) + return; + + // 2006-01-16 AF, Don't add the text editor if mytextedit + // don't allow it. mytextedit says no if the user removes + // text (backspace or delete). + if( dynamic_cast(input_)->isStopingHighlighter() ) + return; + + HighlighterThread *thread = HighlighterThread::instance(); + thread->addEditor( input_ ); + } + + /*! + * \author Anders Fernström + * \date 2006-01-17 + * + * \breif set the correct style if the charFormat is changed and the + * cell is empty. This is done because otherwise the style is lost if + * all text is removed inside a cell. + */ + void InputCell::charFormatChanged(const QTextCharFormat &) + { + //if( input_->toPlainText().isEmpty() ) + //{ + input_->blockSignals( true ); + input_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); + input_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); + input_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); + input_->blockSignals( false ); + contentChanged(); + //} + } + + + + + // *************************************************************** + + + /*! \brief Sets the evaulator delegate. + */ + void InputCell::setDelegate(InputCellDelegate *d) + { + delegate_ = d; + } + + InputCellDelegate *InputCell::delegate() + { + if(!hasDelegate()) + throw runtime_error("No delegate."); + + return delegate_; + } + + + + bool InputCell::hasDelegate() + { + return delegate_ != 0; + } + + + + + + + + + + + /*! \brief Do not use this member. + * + * This is an ugly part of the cell structure. + */ + void InputCell::addCellWidgets() + { + layout_->addWidget(input_,0,0); - if(evaluated_) - layout_->addWidget(output_,1,0); - } + if(evaluated_) + layout_->addWidget(output_,1,0); + } - void InputCell::removeCellWidgets() - { - /* - // PORT >> layout_->remove(input_); - if(evaluated_) - layout_->remove(output_); - */ + void InputCell::removeCellWidgets() + { + /* + // PORT >> layout_->remove(input_); + if(evaluated_) + layout_->remove(output_); + */ - layout_->removeWidget(input_); - if(evaluated_) - layout_->removeWidget(output_); - } + layout_->removeWidget(input_); + if(evaluated_) + layout_->removeWidget(output_); + } - /*! \brief resets the input cell. Removes all output data and - * restores the initial state. - */ - void InputCell::clear() - { - if(evaluated_) - { - output_->clear(); - evaluated_ = false; - // PORT >> layout_->remove(output_); - layout_->removeWidget(output_); - } + /*! \brief resets the input cell. Removes all output data and + * restores the initial state. + */ + void InputCell::clear() + { + if(evaluated_) + { + output_->clear(); + evaluated_ = false; + // PORT >> layout_->remove(output_); + layout_->removeWidget(output_); + } - //input_->setReadOnly(false); - input_->setReadOnly(true); - input_->clear(); - treeView()->setClosed(false); //Notis this - setClosed(true); - } + //input_->setReadOnly(false); + input_->setReadOnly(true); + input_->clear(); + treeView()->setClosed(false); //Notis this + setClosed(true); + } - /*! - * Resize textcell when the mainwindow is resized. This because the - * cellcontent should always be visible. - * - * Added by AF, copied from textcell.cpp - */ - void InputCell::resizeEvent(QResizeEvent *event) - { - contentChanged(); - Cell::resizeEvent(event); - } + /*! + * Resize textcell when the mainwindow is resized. This because the + * cellcontent should always be visible. + * + * Added by AF, copied from textcell.cpp + */ + void InputCell::resizeEvent(QResizeEvent *event) + { + contentChanged(); + Cell::resizeEvent(event); + } @@ -1598,26 +1598,26 @@ namespace IAEX - void InputCell::mouseDoubleClickEvent(QMouseEvent *) - { - // PORT >>if(treeView()->hasMouse()) - if(treeView()->testAttribute(Qt::WA_UnderMouse)) - { - setClosed(!closed_); - } - } + void InputCell::mouseDoubleClickEvent(QMouseEvent *) + { + // PORT >>if(treeView()->hasMouse()) + if(treeView()->testAttribute(Qt::WA_UnderMouse)) + { + setClosed(!closed_); + } + } - void InputCell::accept(Visitor &v) - { - v.visitInputCellNodeBefore(this); + void InputCell::accept(Visitor &v) + { + v.visitInputCellNodeBefore(this); - if(hasChilds()) - child()->accept(v); + if(hasChilds()) + child()->accept(v); - v.visitInputCellNodeAfter(this); + v.visitInputCellNodeAfter(this); - if(hasNext()) - next()->accept(v); - } + if(hasNext()) + next()->accept(v); + } } diff --git a/OMNotebook/OMNotebookQT4/inputcell.h b/OMNotebook/OMNotebookQT4/inputcell.h index 033795ce980..6b7bddb0663 100644 --- a/OMNotebook/OMNotebookQT4/inputcell.h +++ b/OMNotebook/OMNotebookQT4/inputcell.h @@ -61,137 +61,137 @@ namespace IAEX { - class InputCell : public Cell - { - Q_OBJECT - - public: - InputCell(Document *doc, QWidget *parent=0); // Changed 2005-11-23 AF - virtual ~InputCell(); - - QString text(); - QString textHtml(); // Added 2005-10-27 AF - virtual QString textOutput(); // Added 2005-11-23 AF - virtual QString textOutputHtml(); // Added 2005-11-23 AF - virtual QTextCursor textCursor(); // Added 2005-10-27 AF - virtual QTextEdit* textEdit(); // Added 2006-01-05 AF - virtual QTextEdit* textEditOutput(); // Added 2006-02-03 AF - virtual void viewExpression(const bool){} - - virtual void addCellWidgets(); - virtual void removeCellWidgets(); - - void setDelegate(InputCellDelegate *d); - virtual void accept(Visitor &v); - virtual bool isClosed(); // Added 2006-01-17 AF - virtual bool isEditable(); - virtual bool isEvaluated(); // Added 2005-11-23 AF - virtual bool isJavaPlot(QString text = QString::null); // Added 2005-11-23 AF - - - signals: - void heightChanged(); - void textChanged(); - void textChanged( bool ); - void clickedOutput( Cell* ); // Added 2006-02-03 AF - void forwardAction( int ); // Added 2006-04-27 AF - - public slots: - void eval(); - void command(); // Added 2005-12-15 AF - void nextCommand(); // Added 2005-12-15 AF - void nextField(); // Added 2005-12-15 AF - void clickEvent(); - void clickEventOutput(); // Added 2006-02-03 AF - void contentChanged(); - void setText(QString text); - void setTextHtml(QString html); // Added 2005-11-01 AF - virtual void setTextOutput(QString output); // Added 2005-11-23 AF - virtual void setTextOutputHtml(QString html); // Added 2005-11-23 AF - void setStyle(const QString &stylename); // Changed 2005-10-28 AF - void setStyle(CellStyle style); // Changed 2005-10-27 AF - void setChapterCounter(QString number); // Added 2006-03-02 AF - QString ChapterCounter(); // Added 2006-03-02 AF - QString ChapterCounterHtml(); // Added 2006-03-03 AF - void setReadOnly(const bool readonly); // Added 2005-11-01 AF - void setEvaluated(const bool evaluated); // Added 2006-01-16 AF - void setClosed(const bool closed, bool update = true); //Changed 2006-08-24 - virtual void setFocus(const bool focus); - virtual void setFocusOutput(const bool focus); // Added 2006-02-03 AF - - - - protected: - void resizeEvent(QResizeEvent *event); //AF - void mouseDoubleClickEvent(QMouseEvent *); - void clear(); - - bool hasDelegate(); - InputCellDelegate *delegate(); - - private slots: - void addToHighlighter(); // Added 2005-12-29 AF - void charFormatChanged(const QTextCharFormat &); // Added 2006-01-17 AF - - private: - void createInputCell(); - void createOutputCell(); - void createChapterCounter(); - void exceptionInEval(exception &e); // Added 2006-02-02 AF - void setOutputStyle(); // Added 2006-04-21 AF - - private: - bool evaluated_; - bool closed_; - static int numEvals_; - int oldHeight_; // Added 2006-04-10 AF - - public: - QTextBrowser *input_; - QTextBrowser *output_; - private: - QTextBrowser *chaptercounter_; - - InputCellDelegate *delegate_; - //SyntaxHighlighter *syntaxHighlighter_; - - QGridLayout *layout_; - Document *document_; - }; - - - //*************************************************** - // 2005-12-13 AF, changed from QTextEdit to QTextBrowser (browser better when working with images) - class MyTextEdit : public QTextBrowser - { - Q_OBJECT - - public: - MyTextEdit(QWidget *parent=0); - virtual ~MyTextEdit(); - - bool isStopingHighlighter(); // Added 2006-01-16 AF - - signals: - void clickOnCell(); // Added 2005-11-01 AF - void wheelMove( QWheelEvent* ); // Added 2005-11-28 AF - void command(); // Added 2005-12-15 AF - void nextCommand(); // Added 2005-12-15 AF - void nextField(); // Added 2005-12-15 AF - void eval(); // Added 2005-12-15 AF - void forwardAction( int ); // Added 2006-04-27 AF - - - protected: - void mousePressEvent(QMouseEvent *event); // Added 2005-11-01 AF - void wheelEvent(QWheelEvent *event); // Added 2005-11-28 AF - void keyPressEvent(QKeyEvent *event ); // Added 2005-12-15 AF - void insertFromMimeData(const QMimeData *source); // Added 2006-01-23 AF - - private: - bool inCommand; // Added 2005-12-15 AF - bool stopHighlighter; // Added 2006-01-16 AF - }; + class InputCell : public Cell + { + Q_OBJECT + + public: + InputCell(Document *doc, QWidget *parent=0); // Changed 2005-11-23 AF + virtual ~InputCell(); + + QString text(); + QString textHtml(); // Added 2005-10-27 AF + virtual QString textOutput(); // Added 2005-11-23 AF + virtual QString textOutputHtml(); // Added 2005-11-23 AF + virtual QTextCursor textCursor(); // Added 2005-10-27 AF + virtual QTextEdit* textEdit(); // Added 2006-01-05 AF + virtual QTextEdit* textEditOutput(); // Added 2006-02-03 AF + virtual void viewExpression(const bool){} + + virtual void addCellWidgets(); + virtual void removeCellWidgets(); + + void setDelegate(InputCellDelegate *d); + virtual void accept(Visitor &v); + virtual bool isClosed(); // Added 2006-01-17 AF + virtual bool isEditable(); + virtual bool isEvaluated(); // Added 2005-11-23 AF + virtual bool isJavaPlot(QString text = QString::null); // Added 2005-11-23 AF + + + signals: + void heightChanged(); + void textChanged(); + void textChanged( bool ); + void clickedOutput( Cell* ); // Added 2006-02-03 AF + void forwardAction( int ); // Added 2006-04-27 AF + + public slots: + void eval(); + void command(); // Added 2005-12-15 AF + void nextCommand(); // Added 2005-12-15 AF + void nextField(); // Added 2005-12-15 AF + void clickEvent(); + void clickEventOutput(); // Added 2006-02-03 AF + void contentChanged(); + void setText(QString text); + void setTextHtml(QString html); // Added 2005-11-01 AF + virtual void setTextOutput(QString output); // Added 2005-11-23 AF + virtual void setTextOutputHtml(QString html); // Added 2005-11-23 AF + void setStyle(const QString &stylename); // Changed 2005-10-28 AF + void setStyle(CellStyle style); // Changed 2005-10-27 AF + void setChapterCounter(QString number); // Added 2006-03-02 AF + QString ChapterCounter(); // Added 2006-03-02 AF + QString ChapterCounterHtml(); // Added 2006-03-03 AF + void setReadOnly(const bool readonly); // Added 2005-11-01 AF + void setEvaluated(const bool evaluated); // Added 2006-01-16 AF + void setClosed(const bool closed, bool update = true); //Changed 2006-08-24 + virtual void setFocus(const bool focus); + virtual void setFocusOutput(const bool focus); // Added 2006-02-03 AF + + + + protected: + void resizeEvent(QResizeEvent *event); //AF + void mouseDoubleClickEvent(QMouseEvent *); + void clear(); + + bool hasDelegate(); + InputCellDelegate *delegate(); + + private slots: + void addToHighlighter(); // Added 2005-12-29 AF + void charFormatChanged(const QTextCharFormat &); // Added 2006-01-17 AF + + private: + void createInputCell(); + void createOutputCell(); + void createChapterCounter(); + void exceptionInEval(exception &e); // Added 2006-02-02 AF + void setOutputStyle(); // Added 2006-04-21 AF + + private: + bool evaluated_; + bool closed_; + static int numEvals_; + int oldHeight_; // Added 2006-04-10 AF + + public: + QTextBrowser *input_; + QTextBrowser *output_; + private: + QTextBrowser *chaptercounter_; + + InputCellDelegate *delegate_; + //SyntaxHighlighter *syntaxHighlighter_; + + QGridLayout *layout_; + Document *document_; + }; + + + //*************************************************** + // 2005-12-13 AF, changed from QTextEdit to QTextBrowser (browser better when working with images) + class MyTextEdit : public QTextBrowser + { + Q_OBJECT + + public: + MyTextEdit(QWidget *parent=0); + virtual ~MyTextEdit(); + + bool isStopingHighlighter(); // Added 2006-01-16 AF + + signals: + void clickOnCell(); // Added 2005-11-01 AF + void wheelMove( QWheelEvent* ); // Added 2005-11-28 AF + void command(); // Added 2005-12-15 AF + void nextCommand(); // Added 2005-12-15 AF + void nextField(); // Added 2005-12-15 AF + void eval(); // Added 2005-12-15 AF + void forwardAction( int ); // Added 2006-04-27 AF + + + protected: + void mousePressEvent(QMouseEvent *event); // Added 2005-11-01 AF + void wheelEvent(QWheelEvent *event); // Added 2005-11-28 AF + void keyPressEvent(QKeyEvent *event ); // Added 2005-12-15 AF + void insertFromMimeData(const QMimeData *source); // Added 2006-01-23 AF + + private: + bool inCommand; // Added 2005-12-15 AF + bool stopHighlighter; // Added 2006-01-16 AF + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/inputcelldelegate.h b/OMNotebook/OMNotebookQT4/inputcelldelegate.h index 6cc9f8d4df4..593ae755dc6 100644 --- a/OMNotebook/OMNotebookQT4/inputcelldelegate.h +++ b/OMNotebook/OMNotebookQT4/inputcelldelegate.h @@ -54,11 +54,11 @@ namespace IAEX { public: virtual QString getResult() = 0; - virtual QString getError() = 0; // Added 2006-02-02 AF + virtual QString getError() = 0; // Added 2006-02-02 AF virtual void evalExpression(const QString expr) = 0; - virtual void closeConnection() = 0; // Added 2006-02-02 AF - virtual void reconnect() = 0; // Added 2006-02-02 AF - virtual bool startDelegate() = 0; // Added 2006-02-09 AF + virtual void closeConnection() = 0; // Added 2006-02-02 AF + virtual void reconnect() = 0; // Added 2006-02-02 AF + virtual bool startDelegate() = 0; // Added 2006-02-09 AF }; } diff --git a/OMNotebook/OMNotebookQT4/notebook.cpp b/OMNotebook/OMNotebookQT4/notebook.cpp index bee3ecac0df..9a27fdad2f8 100644 --- a/OMNotebook/OMNotebookQT4/notebook.cpp +++ b/OMNotebook/OMNotebookQT4/notebook.cpp @@ -87,3665 +87,3665 @@ using namespace std; namespace IAEX { - /*! - * \class NotebookWindow - * \author Ingemar Axelsson and Anders Fernström - * - * \brief This class describes a mainwindow using the CellDocument - * - * This is the main applicationwindow. It contains of a menu, a - * toolbar, a statusbar and a workspace. The workspace will contain a - * celldocument view. - * - * - * \todo implement a timer that saves a document every 5 minutes - * or so. - * - * \todo Implement section numbering. Could be done with some kind - * of vistors. - * - * - * \bug Segmentation fault when quit. Only sometimes. - */ - - - // 2006-03-01 AF, Open, Save, Image and Link dir - QString NotebookWindow::openDir_ = QString::null; - QString NotebookWindow::saveDir_ = QString::null; - QString NotebookWindow::imageDir_ = QString::null; - QString NotebookWindow::linkDir_ = QString::null; - - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2006-01-17 (update) - * - * \brief The class constructor - * - * 2006-01-16 AF, Added an icon to the window - * Also made som other updates /AF - */ - NotebookWindow::NotebookWindow(Document *subject, - const QString filename, QWidget *parent) - : DocumentView(parent), - subject_(subject), - filename_(filename), - closing_(false), - app_( subject->application() ), //AF - findForm_( 0 ) //AF - { - if( filename_ != QString::null ) - qDebug( filename_.toStdString().c_str() ); - -// subject_->attach(this); -// setMinimumSize( 150, 220 ); //AF - - toolBar = new QToolBar("Show toolbar", this); - - - posIndicator = new QLabel(""); - posIndicator->setMinimumWidth(75); - stateIndicator = new QLabel(""); - stateIndicator->setMinimumWidth(60); - - statusBar()->insertPermanentWidget(0,posIndicator); - statusBar()->insertPermanentWidget(0,stateIndicator); - createFileMenu(); - createEditMenu(); - createCellMenu(); - createFormatMenu(); - createInsertMenu(); - createWindowMenu(); - createAboutMenu(); - - toolBar->addSeparator(); - toolBar->addAction(quitWindowAction); - addToolBar(toolBar); //Add icons, update the edit menu etc. - - subject_->attach(this); - setMinimumSize( 150, 220 ); //AF - - - // 2006-01-16 AF, Added an icon to the window -// setWindowIcon( QIcon("./omnotebook_png.png") ); - setWindowIcon( QIcon(":/Resources/omnotebook_png.png")); - - statusBar()->showMessage("Ready"); - resize(800, 600); - - connect( subject_->getCursor(), SIGNAL( changedPosition() ), - this, SLOT( updateMenus() )); - connect( subject_, SIGNAL( contentChanged() ), - this, SLOT( updateWindowTitle() )); - connect( subject_, SIGNAL( hoverOverFile(QString) ), - this, SLOT( setStatusMessage(QString) )); - // 2006-04-27 AF - connect( subject_, SIGNAL( forwardAction(int) ), - this, SLOT( forwardedAction(int) )); - - connect( subject_, SIGNAL(updatePos(int, int)), this, SLOT(setPosition(int, int))); - - connect( subject_, SIGNAL(newState(QString)), this, SLOT(setState(QString))); - - connect( subject_, SIGNAL(setStatusMenu(QList)), this, SLOT(setStatusMenu(QList))); - - updateWindowTitle(); - updateChapterCounters(); - update(); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2006-08-24 (update) - * - * \brief The class destructor - * - * 2005-11-03/04/07 AF, added som things that should be deleted. - * 2006-01-05 AF, added code so all inputcells are added to the - * removelist in the highlighter - * 2006-01-27 AF, remove this notebook window from the list of - * notebook windows in the main applicaiton - * 2006-08-24 AF, delete replace action - */ - NotebookWindow::~NotebookWindow() - { - //2006-01-27 AF, remove document view from application lsit - application()->removeDocumentView( this ); - - //2006-01-05 AF, add all inputcell to removelist on highlighter - RemoveHighlighterVisitor visitor; - subject_->runVisitor( visitor ); - - subject_->detach(this); - delete subject_; - //subject_ = 0; - - // 2005-11-03/04/07 AF, remova all created QAction - map::iterator s_iter = styles_.begin(); - while( s_iter != styles_.end() ) - { - delete (*s_iter).second; - ++s_iter; - } - - QHash::iterator f_iter = fonts_.begin(); - while( f_iter != fonts_.end() ) - { - delete f_iter.value(); - ++f_iter; - } - - QHash::iterator c_iter = colors_.begin(); - while( c_iter != colors_.end() ) - { - delete c_iter.value(); - ++c_iter; - } - - QHash::iterator w_iter = windows_.begin(); - while( w_iter != windows_.end() ) - { - delete w_iter.key(); - ++w_iter; - } - - delete stylesgroup; - delete fontsgroup; - delete sizesgroup; - delete stretchsgroup; - delete colorsgroup; - delete alignmentsgroup; - delete verticalAlignmentsgroup; - delete bordersgroup; - delete marginsgroup; - delete paddingsgroup; - - - delete newAction; - delete openFileAction; - delete saveAsAction; - delete saveAction; - delete printAction; - delete closeFileAction; - delete quitWindowAction; - - delete undoAction; - delete redoAction; - delete cutAction; - delete copyAction; - delete pasteAction; - delete findAction; - delete replaceAction; - delete showExprAction; - - //delete cutCellAction; - //delete copyCellAction; - //delete pasteCellAction; - delete addCellAction; - delete ungroupCellAction; - delete splitCellAction; - delete deleteCellAction; - delete nextCellAction; - delete previousCellAction; - - delete groupAction; - delete inputAction; - delete textAction; - - delete aboutAction; - delete helpAction; - delete aboutQtAction; - - delete facePlain; - delete faceBold; - delete faceItalic; - delete faceUnderline; - - delete sizeSmaller; - delete sizeLarger; - delete size8pt; - delete size9pt; - delete size10pt; - delete size12pt; - delete size14pt; - delete size16pt; - delete size18pt; - delete size20pt; - delete size24pt; - delete size36pt; - delete size72pt; - delete sizeOther; - - delete stretchUltraCondensed; - delete stretchExtraCondensed; - delete stretchCondensed; - delete stretchSemiCondensed; - delete stretchUnstretched; - delete stretchSemiExpanded; - delete stretchExpanded; - delete stretchExtraExpanded; - delete stretchUltraExpanded; - - delete colorBlack; - delete colorWhite; - delete color10Gray; - delete color33Gray; - delete color50Gray; - delete color66Gray; - delete color90Gray; - delete colorRed; - delete colorGreen; - delete colorBlue; - delete colorCyan; - delete colorMagenta; - delete colorYellow; - delete colorOther; - - delete chooseFont; - - delete alignmentLeft; - delete alignmentRight; - delete alignmentCenter; - delete alignmentJustify; - delete verticalNormal; - delete verticalSub; - delete verticalSuper; - - delete borderOther; - delete marginOther; - delete paddingOther; - - delete insertImageAction; - delete insertLinkAction; - delete importOldFile; - delete exportPureText; - - // 2006-08-24 AF, delete findForm if it exists - if( findForm_ ) - delete findForm_; - - delete toolBar; - delete posIndicator; - delete stateIndicator; - } - - /*! - * \author Ingemar Axelsson - */ - - //class Frame: public QFrame - //{ - //protected: - // void paintEvent(QPaintEvent *event) - // { - // QPainter p(this); - // p.save(); - // p.setMatrix(QMatrix(.5, 1, .3, .7,1,1)); - // QFrame::paintEvent(event); - // p.restore(); - // } - //}; - void NotebookWindow::update() - { - QFrame *mainWidget = subject_->getState(); - - mainWidget->setParent(this); - mainWidget->move( QPoint(0,0) ); - - - setCentralWidget(mainWidget); -// mainWidget->setMaximumHeight(250); - mainWidget->show(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-30 - * - * \brief Return the notebook windons document - */ - Document* NotebookWindow::document() - { - return subject_; - } - - /*! - * \author Ingemar Axelsson - */ - CellApplication *NotebookWindow::application() - { - return subject_->application(); - } - - /*! - * \author Anders Fernström - * \date 2005-12-01 (update) - * - * \brief Method for creating file nemu. - * - * 2005-10-07 AF, Updated/Remade the function when porting to QT4. - * 2005-11-21 AF, Added a export menu - * 2005-12-01 AF, Added a import menu - */ - void NotebookWindow::createFileMenu() - { - // NEW - newAction = new QAction( tr("&New"), this ); - newAction->setShortcut( tr("Ctrl+N") ); - newAction->setStatusTip( tr("Create a new document") ); - connect(newAction, SIGNAL(triggered()), this, SLOT(newFile())); - newAction->setIcon(QIcon(":/Resources/toolbarIcons/filenew.png")); - - toolBar->addAction(newAction); - - - recentMenu = new QMenu("Recent &Files", this); - - // OPEN FILE - openFileAction = new QAction( tr("&Open"), this ); - openFileAction->setShortcut( tr("Ctrl+O") ); - openFileAction->setStatusTip( tr("Open a file") ); - connect(openFileAction, SIGNAL(triggered()), this, SLOT(openFile())); - openFileAction->setIcon(QIcon(":/Resources/toolbarIcons/fileopen.png")); - - QToolButton *b = new QToolButton(this); - b->setDefaultAction(openFileAction); - b->setMenu(recentMenu); - b->setPopupMode(QToolButton::MenuButtonPopup); -// toolBar->addAction(openFileAction); - toolBar->addWidget(b); - - // SAVE AS - saveAsAction = new QAction( tr("Save &As..."), this ); - saveAsAction->setShortcut( tr("Ctrl+Shift+S") ); - saveAsAction->setStatusTip( tr("Save the document as a new file") ); - connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveas())); - - // SAVE - saveAction = new QAction( tr("&Save"), this ); - saveAction->setShortcut( tr("Ctrl+S") ); - saveAction->setStatusTip( tr("Save the document") ); - connect(saveAction, SIGNAL(triggered()), this, SLOT(save())); - saveAction->setIcon(QIcon(":/Resources/toolbarIcons/filesave.png")); - toolBar->addAction(saveAction); - - toolBar->addSeparator(); - - // CLOSE FILE - closeFileAction = new QAction( tr("&Close"), this ); - closeFileAction->setShortcut( tr("Ctrl+F4") ); - closeFileAction->setStatusTip( tr("Close the window") ); - connect(closeFileAction, SIGNAL(triggered()), this, SLOT(closeFile())); - - // PRINT - printAction = new QAction( tr("&Print"), this ); - printAction->setShortcut( tr("Ctrl+P") ); - printAction->setStatusTip( tr("Print the document") ); - connect(printAction, SIGNAL(triggered()), this, SLOT(print())); - printAction->setIcon(QIcon(":/Resources/toolbarIcons/fileprint.png")); - toolBar->addAction(printAction); - - toolBar->addSeparator(); - - - - // QUIT WINDOW - quitWindowAction = new QAction( tr("&Quit"), this ); - quitWindowAction->setShortcut( tr("Ctrl+Q") ); - quitWindowAction->setStatusTip( tr("Quit OMNotebook") ); - quitWindowAction->setIcon(QIcon(":/Resources/toolbarIcons/exit.png")); - - connect(quitWindowAction, SIGNAL(triggered()), this, SLOT(quitOMNotebook())); - - // CREATE MENU - fileMenu = menuBar()->addMenu( tr("&File") ); - fileMenu->addAction( newAction ); - fileMenu->addAction( openFileAction ); - fileMenu->addAction( saveAction ); - fileMenu->addAction( saveAsAction ); - fileMenu->addAction( closeFileAction ); - fileMenu->addSeparator(); - fileMenu->addAction( printAction ); - fileMenu->addSeparator(); - - // RECENT FILES -// recentMenu = fileMenu->addMenu("Recent &Files"); - fileMenu->addMenu(recentMenu); - - QSettings s("PELAB", "OMNotebook"); - QString recentFile; - for(int i = 0; i < 4; ++i) - { - if((recentFile = s.value(QString("Recent")+QString(i), QString()).toString()) != QString()) - { - QAction* tmpAction = recentMenu->addAction(recentFile); - connect(tmpAction, SIGNAL(triggered()), this, SLOT(recentTriggered())); - - } - } - - fileMenu->addSeparator(); - - importMenu = fileMenu->addMenu( tr("&Import") ); - exportMenu = fileMenu->addMenu( tr("E&xport") ); - fileMenu->addSeparator(); - fileMenu->addAction( quitWindowAction ); - - - // IMPORT MENU - // Added 2005-12-01 - importOldFile = new QAction( tr("&Old OMNotebook file"), this ); - importOldFile->setStatusTip( tr("Import an old OMNotebook file") ); - connect( importOldFile, SIGNAL( triggered() ), - this, SLOT( openOldFile() )); - - importMenu->addAction( importOldFile ); - - - // EXPORT MENU - // Added 2005-11-21 - exportPureText = new QAction( tr("&Pure text"), this ); - exportPureText->setStatusTip( tr("Export the document content to pure text") ); - connect( exportPureText, SIGNAL( triggered() ), - this, SLOT( pureText() )); - - exportMenu->addAction( exportPureText ); - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 (update) - * - * \brief Method for creating edit nemu. - * - * 2005-10-07 AF, Remade the function when porting to QT4. - * 2006-02-03 AF, Made undo, redo, cut, copy and paste actions for the editor - * 2006-08-24 AF, added a replace action, renamed search action to find action - */ - void NotebookWindow::createEditMenu() - { - // 2005-10-07 AF, Porting, replaced this - //QAction *undoAction = new QAction("Undo", "&Undo", 0, this, "undoaction"); - undoAction = new QAction( tr("&Undo"), this); - undoAction->setShortcut( tr("Ctrl+Z") ); - undoAction->setStatusTip( tr("Undo last action") ); - connect( undoAction, SIGNAL( triggered() ), - this, SLOT( undoEdit() )); - - undoAction->setEnabled(false); - undoAction->setIcon(QIcon(":/Resources/toolbarIcons/undo.png")); - toolBar->addAction(undoAction); - - - // 2005-10-07 AF, Porting, replaced this - //QAction *redoAction = new QAction("Redo", "&Redo", 0, this, "redoaction"); - redoAction = new QAction( tr("&Redo"), this); - redoAction->setShortcut( tr("Ctrl+Y") ); - redoAction->setStatusTip( tr("Redo last action") ); - connect( redoAction, SIGNAL( triggered() ), - this, SLOT( redoEdit() )); - - redoAction->setEnabled(false); - redoAction->setIcon(QIcon(":/Resources/toolbarIcons/redo.png")); - toolBar->addAction(redoAction); - - toolBar->addSeparator(); - - // CUT - cutAction = new QAction( tr("Cu&t"), this); - cutAction->setShortcut( tr("Ctrl+X") ); - cutAction->setStatusTip( tr("Cut selected text") ); - connect( cutAction, SIGNAL( triggered() ), - this, SLOT( cutEdit() )); - - cutAction->setEnabled(false); - cutAction->setIcon(QIcon(":/Resources/toolbarIcons/editcut.png")); - toolBar->addAction(cutAction); - - // COPY - copyAction = new QAction( tr("&Copy"), this); - copyAction->setShortcut( tr("Ctrl+C") ); - copyAction->setStatusTip( tr("Copy selected text") ); - connect( copyAction, SIGNAL( triggered() ), - this, SLOT( copyEdit() )); - - copyAction->setEnabled(false); - copyAction->setIcon(QIcon(":/Resources/toolbarIcons/editcopy.png")); - toolBar->addAction(copyAction); - - - // PASTE - pasteAction = new QAction( tr("&Paste"), this); - pasteAction->setShortcut( tr("Ctrl+V") ); - pasteAction->setStatusTip( tr("Paste text from clipboard") ); - connect( pasteAction, SIGNAL( triggered() ), - this, SLOT( pasteEdit() )); - - - pasteAction->setIcon(QIcon(":/Resources/toolbarIcons/editpaste.png")); - toolBar->addAction(pasteAction); - - toolBar->addSeparator(); - - - // FIND - findAction = new QAction( tr("&Find"), this); - findAction->setShortcut( tr("Ctrl+F") ); - findAction->setStatusTip( tr("Search through the document") ); - connect( findAction, SIGNAL( triggered() ), - this, SLOT( findEdit() )); - - findAction->setIcon(QIcon(":/Resources/toolbarIcons/find.png")); - toolBar->addAction(findAction); - toolBar->addSeparator(); - - // REPLACE, added 2006-08-24 AF - replaceAction = new QAction( tr("Re&place"), this); - replaceAction->setShortcut( tr("Ctrl+H") ); - replaceAction->setStatusTip( tr("Search through the document and replace") ); - connect( replaceAction, SIGNAL( triggered() ), - this, SLOT( replaceEdit() )); - - - // 2005-10-07 AF, Porting, replaced this - //QAction *showExprAction = new QAction("View Expression", "&View Expression",0, this, "viewexpr"); - //QObject::connect(showExprAction, SIGNAL(toggled(bool)), subject_, SLOT(showHTML(bool))); - showExprAction = new QAction( tr("&View Expression"), this); - showExprAction->setStatusTip( tr("View the expression in the cell") ); - showExprAction->setCheckable(true); - showExprAction->setChecked(false); - connect(showExprAction, SIGNAL(toggled(bool)), subject_, SLOT(showHTML(bool))); - - // 2005-10-07 AF, Porting, new code for creating menu - // 2006-02-03 AF, removed SEARCH from menu, - // because they havn't been implemented yet. - editMenu = menuBar()->addMenu( tr("&Edit") ); - editMenu->addAction( undoAction ); - editMenu->addAction( redoAction ); - editMenu->addSeparator(); - editMenu->addAction( cutAction ); - editMenu->addAction( copyAction ); - editMenu->addAction( pasteAction ); - editMenu->addSeparator(); - editMenu->addAction( findAction ); - editMenu->addAction( replaceAction ); - editMenu->addSeparator(); - editMenu->addAction( showExprAction ); - - - /* Old menu code //AF - editMenu = new Q3PopupMenu(this); - menuBar()->insertItem("&Edit", editMenu); - undoAction->addTo(editMenu); - redoAction->addTo(editMenu); - editMenu->insertSeparator(3); - searchAction->addTo(editMenu); - showExprAction->addTo(editMenu); - */ - - -// QObject::connect(editMenu, SIGNAL(aboutToShow()), //HE 071119 -// this, SLOT(updateEditMenu())); // -''- - } - - /*! - * \author Anders Fernström - * \date 2006-04-27 (update) - * - * \brief Method for creating cell nemu. - * - * Remade the function when porting to QT4. - * - * 2006-04-26 AF, Added UNGROUP and SPLIT CELL - * 2006-04-27 AF, remove cut,copy,paste cell from menu - */ - void NotebookWindow::createCellMenu() - { - // 2005-10-07 AF, Porting, replaced this - //QAction *cutCellAction = new QAction("Cut cell", "&Cut Cell", CTRL+SHIFT+Key_X, this, "cutcell"); - //QObject::connect(cutCellAction, SIGNAL(activated()), this, SLOT(cutCell())); - /* - cutCellAction = new QAction( tr("Cu&t Cell"), this); - cutCellAction->setShortcut( tr("Ctrl+Shift+X") ); - cutCellAction->setStatusTip( tr("Cut selected cell") ); - connect(cutCellAction, SIGNAL(triggered()), this, SLOT(cutCell())); - - // 2005-10-07 AF, Porting, replaced this - //QAction *copyCellAction = new QAction("Copy cell", "&Copy Cell", CTRL+SHIFT+Key_C, this, "copycell"); - //QObject::connect(copyCellAction, SIGNAL(activated()), this, SLOT(copyCell())); - copyCellAction = new QAction( tr("&Copy Cell"), this); - copyCellAction->setShortcut( tr("Ctrl+Shift+C") ); - copyCellAction->setStatusTip( tr("Copy selected cell") ); - connect(copyCellAction, SIGNAL(triggered()), this, SLOT(copyCell())); - - // 2005-10-07 AF, Porting, replaced this - //QAction *pasteCellAction = new QAction("Paste cell", "&Paste Cell", CTRL+SHIFT+Key_V, this, "pastecell"); - //QObject::connect(pasteCellAction, SIGNAL(activated()), this, SLOT(pasteCell())); - pasteCellAction = new QAction( tr("&Paste Cell"), this); - pasteCellAction->setShortcut( tr("Ctrl+Shift+V") ); - pasteCellAction->setStatusTip( tr("Paste in a cell") ); - connect(pasteCellAction, SIGNAL(triggered()), this, SLOT(pasteCell())); - */ - - addCellAction = new QAction( tr("&Add Cell (previus cell style)"), this); - addCellAction->setShortcut( tr("Alt+Enter") ); - addCellAction->setStatusTip( tr("Add a new textcell with the previuos cells style") ); - connect(addCellAction, SIGNAL(triggered()), this, SLOT(createNewCell())); - - inputAction = new QAction( tr("Add &Inputcell"), this); - inputAction->setShortcut( tr("Ctrl+Shift+I") ); - inputAction->setStatusTip( tr("Add an input cell") ); - connect(inputAction, SIGNAL(triggered()), this, SLOT(inputCellsAction())); - /// fjass - textAction = new QAction( tr("Add &Textcell"), this); - textAction->setShortcut( tr("Ctrl+Shift+T") ); - textAction->setStatusTip( tr("Add a text cell") ); - connect(textAction, SIGNAL(triggered()), this, SLOT(textCellsAction())); - // \fjass - - groupAction = new QAction( tr("&Groupcell"), this); - groupAction->setShortcut( tr("Ctrl+Shift+G") ); - groupAction->setStatusTip( tr("Groupcell") ); - connect( groupAction, SIGNAL( triggered() ), - this, SLOT( groupCellsAction() )); - - // 2006-04-26 AF, UNGROUP - ungroupCellAction = new QAction( tr("&Ungroup groupcell"), this); - ungroupCellAction->setShortcut( tr("Ctrl+Shift+U") ); - ungroupCellAction->setStatusTip( tr("Ungroup the selected groupcell in the tree view") ); - connect( ungroupCellAction, SIGNAL( triggered() ), - this, SLOT( ungroupCell() )); - - // 2006-04-26 AF, SPLIT CELL - splitCellAction = new QAction( tr("&Split cell"), this); - splitCellAction->setShortcut( tr("Ctrl+Shift+P") ); - splitCellAction->setStatusTip( tr("Split selected cell") ); - connect( splitCellAction, SIGNAL( triggered() ), - this, SLOT( splitCell() )); - - // 2005-10-07 AF, Porting, replaced this - //QAction *deleteCellAction = new QAction("Delete cell", "&Delete Cell", CTRL+SHIFT+Key_D, this, "deletecell"); - //QObject::connect(deleteCellAction, SIGNAL(activated()), this, SLOT(deleteCurrentCell())); - deleteCellAction = new QAction( tr("&Delete Cell"), this); - deleteCellAction->setShortcut( tr("Ctrl+Shift+D") ); - deleteCellAction->setStatusTip( tr("Delete selected cell") ); - connect(deleteCellAction, SIGNAL(triggered()), this, SLOT(deleteCurrentCell())); - - // 2005-10-07 AF, Porting, replaced this - //QAction *nextCellAction = new QAction("next cell", "&Next Cell", 0, this, "nextcell"); - //QObject::connect(nextCellAction, SIGNAL(activated()), this, SLOT(moveCursorDown())); - nextCellAction = new QAction( tr("&Next Cell"), this); - nextCellAction->setStatusTip( tr("Move to next cell") ); - connect(nextCellAction, SIGNAL(triggered()), this, SLOT(moveCursorDown())); - - // 2005-10-07 AF, Porting, replaced this - //QAction *previousCellAction = new QAction("previous cell", "&Previous Cell", 0, this, "prevoiscell"); - //QObject::connect(previousCellAction, SIGNAL(activated()), this, SLOT(moveCursorUp())); - previousCellAction = new QAction( tr("P&revious Cell"), this); - previousCellAction->setStatusTip( tr("Move to previous cell") ); - connect(previousCellAction, SIGNAL(triggered()), this, SLOT(moveCursorUp())); - - - // 2005-10-07 AF, Porting, new code for creating menu - // 2006-04-27 AF, remove cut,copy,paste cell from menu - cellMenu = menuBar()->addMenu( tr("&Cell") ); - //cellMenu->addAction( cutCellAction ); - //cellMenu->addAction( copyCellAction ); - //cellMenu->addAction( pasteCellAction ); - //cellMenu->addSeparator(); - cellMenu->addAction( addCellAction ); - cellMenu->addAction( inputAction ); - cellMenu->addAction( textAction ); - - cellMenu->addAction( groupAction ); - cellMenu->addAction( ungroupCellAction ); - cellMenu->addAction( splitCellAction ); - cellMenu->addAction( deleteCellAction ); - cellMenu->addSeparator(); - cellMenu->addAction( nextCellAction ); - cellMenu->addAction( previousCellAction ); - - QObject::connect(cellMenu, SIGNAL(aboutToShow()), - this, SLOT(updateCellMenu())); - - - /* Old menu code //AF - cellMenu = new Q3PopupMenu(this); - menuBar()->insertItem("&Cell", cellMenu); - cutCellAction->addTo(cellMenu); - copyCellAction->addTo(cellMenu); - pasteCellAction->addTo(cellMenu); - addCellAction->addTo(cellMenu); - deleteCellAction->addTo(cellMenu); - nextCellAction->addTo(cellMenu); - previousCellAction->addTo(cellMenu); - cellMenu->insertSeparator(3); - cellMenu->insertSeparator(5); - */ - } - - /*! - * \author Anders Fernström - * \date 2005-10-07 - * \date 2005-11-03 (update) - * - * \brief Method for creating format nemu. - * - * Remade the function when porting to QT4. - * - * 2005-11-03 AF, Updated this function with functionality for - * changes text settings. - */ - void NotebookWindow::createFormatMenu() - { - // 2005-10-07 AF, Portin, Removed - //Create style menus. - //Q3ActionGroup *stylesgroup = new Q3ActionGroup(this, 0, true); - - // 2005-10-07 AF, Portin, Removed - //formatMenu = new Q3PopupMenu(this); - - - // 2005-10-03 AF, get the stylesheet instance - Stylesheet *sheet = Stylesheet::instance("stylesheet.xml"); - - // Create the style actions //AF - stylesgroup = new QActionGroup( this ); - formatMenu = menuBar()->addMenu( tr("&Format") ); - styleMenu = formatMenu->addMenu( tr("&Styles") ); - - vector styles = sheet->getAvailableStyleNames(); - vector::iterator i = styles.begin(); - for(;i != styles.end(); ++i) - { - QAction *tmp = new QAction( tr( (*i).toStdString().c_str() ), this ); - tmp->setCheckable( true ); - styleMenu->addAction( tmp ); - stylesgroup->addAction( tmp ); - styles_[(*i)] = tmp; - - /* old action/menu code - QAction *tmp = new QAction((*i),(*i),0, this, (*i)); - tmp->setToggleAction(true); - stylesgroup->add(tmp); - //tmp->addTo(styleMenu); - styles_[(*i)] = tmp; - */ - } - - // 2005-10-07 AF, Porting, replaced this - //QObject::connect(stylesgroup, SIGNAL(selected (QAction*)), this, SLOT(changeStyle(QAction*))); - connect( styleMenu, SIGNAL(triggered(QAction*)), this, SLOT(changeStyle(QAction*))); - - - // 2005-10-07 AF, Portin, Removed - //stylesgroup->setUsesDropDown(true); - //stylesgroup->setMenuText("&Styles"); - - - - // FONT - // ----------------------------------------------------- - // Code for createn the font menu - formatMenu->addSeparator(); - fontsgroup = new QActionGroup( this ); - fontMenu = formatMenu->addMenu( tr("&Font") ); - - QFontDatabase fontDatabase; - QStringList fonts = fontDatabase.families( QFontDatabase::Latin ); - for( int index = 0; index < fonts.count(); ++index ) - { - QAction *tmp = new QAction( fonts[index], this ); - tmp->setCheckable( true ); - fontMenu->addAction( tmp ); - fontsgroup->addAction( tmp ); - fonts_.insert( fonts[index], tmp ); - } - - connect( fontMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeFont(QAction*) )); - connect( fontMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateFontMenu() )); - - // ----------------------------------------------------- - // END: FONT - - - // FACE - // ----------------------------------------------------- - // Code for createn the face menu - faceMenu = formatMenu->addMenu( tr("Fa&ce") ); - - facePlain = new QAction( tr("&Plain"), this); - facePlain->setCheckable( false ); - facePlain->setStatusTip( tr("Set font face to Plain") ); - - faceBold = new QAction( tr("&Bold"), this); - faceBold->setShortcut( tr("Ctrl+B") ); - faceBold->setCheckable( true ); - faceBold->setStatusTip( tr("Set font face to Bold") ); - - faceItalic = new QAction( tr("&Italic"), this); - faceItalic->setShortcut( tr("Ctrl+I") ); - faceItalic->setCheckable( true ); - faceItalic->setStatusTip( tr("Set font face to Italic") ); - - faceUnderline = new QAction( tr("&Underline"), this); - faceUnderline->setShortcut( tr("Ctrl+U") ); - faceUnderline->setCheckable( true ); - faceUnderline->setStatusTip( tr("Set font face to Underline") ); - - - connect( faceMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateFontFaceMenu() )); - connect( faceMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeFontFace(QAction*) )); - - faceMenu->addAction( facePlain ); - faceMenu->addAction( faceBold ); - faceMenu->addAction( faceItalic ); - faceMenu->addAction( faceUnderline ); - - // ----------------------------------------------------- - // END: FONT - - - - // SIZE - // ----------------------------------------------------- - // Code for createn the size menu - - sizeMenu = formatMenu->addMenu( tr("Si&ze") ); - sizesgroup = new QActionGroup( this ); - - sizeSmaller = new QAction( tr("&Smaller"), this); - sizeSmaller->setShortcut( tr("Alt+-") ); - sizeSmaller->setCheckable( false ); - sizeSmaller->setStatusTip( tr("Set font size smaller") ); - - sizeLarger = new QAction( tr("&Larger"), this); - sizeLarger->setShortcut( tr("Alt+=") ); - sizeLarger->setCheckable( false ); - sizeLarger->setStatusTip( tr("Set font size larger") ); - - size8pt = new QAction( tr("8"), this); - size8pt->setCheckable( true ); - sizes_.insert( "8", size8pt ); - sizesgroup->addAction( size8pt ); - - size9pt = new QAction( tr("9"), this); - size9pt->setCheckable( true ); - sizes_.insert( "9", size9pt ); - sizesgroup->addAction( size9pt ); - - size10pt = new QAction( tr("10"), this); - size10pt->setCheckable( true ); - sizes_.insert( "10", size10pt ); - sizesgroup->addAction( size10pt ); - - size12pt = new QAction( tr("12"), this); - size12pt->setCheckable( true ); - sizes_.insert( "12", size12pt ); - sizesgroup->addAction( size12pt ); - - size14pt = new QAction( tr("14"), this); - size14pt->setCheckable( true ); - sizes_.insert( "14", size14pt ); - sizesgroup->addAction( size14pt ); - - size16pt = new QAction( tr("16"), this); - size16pt->setCheckable( true ); - sizes_.insert( "16", size16pt ); - sizesgroup->addAction( size16pt ); - - size18pt = new QAction( tr("18"), this); - size18pt->setCheckable( true ); - sizes_.insert( "18", size18pt ); - sizesgroup->addAction( size18pt ); - - size20pt = new QAction( tr("20"), this); - size20pt->setCheckable( true ); - sizes_.insert( "20", size20pt ); - sizesgroup->addAction( size20pt ); - - size24pt = new QAction( tr("24"), this); - size24pt->setCheckable( true ); - sizes_.insert( "24", size24pt ); - sizesgroup->addAction( size24pt ); - - size36pt = new QAction( tr("36"), this); - size36pt->setCheckable( true ); - sizes_.insert( "36", size36pt ); - sizesgroup->addAction( size36pt ); - - size72pt = new QAction( tr("72"), this); - size72pt->setCheckable( true ); - sizes_.insert( "72", size72pt ); - sizesgroup->addAction( size72pt ); - - sizeOther = new QAction( tr("&Other..."), this); - sizeOther->setCheckable( true ); - sizeOther->setStatusTip( tr("Select font size") ); - - - connect( sizeMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateFontSizeMenu() )); - connect( sizeMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeFontSize(QAction*) )); - - - sizeMenu->addAction( sizeSmaller ); - sizeMenu->addAction( sizeLarger ); - sizeMenu->addSeparator(); - sizeMenu->addAction( size8pt ); - sizeMenu->addAction( size9pt ); - sizeMenu->addAction( size10pt ); - sizeMenu->addAction( size12pt ); - sizeMenu->addAction( size14pt ); - sizeMenu->addAction( size16pt ); - sizeMenu->addAction( size18pt ); - sizeMenu->addAction( size20pt ); - sizeMenu->addAction( size24pt ); - sizeMenu->addAction( size36pt ); - sizeMenu->addAction( size72pt ); - sizeMenu->addSeparator(); - sizeMenu->addAction( sizeOther ); - - // ----------------------------------------------------- - // END: Size - - - - // STRETCH - // ----------------------------------------------------- - // Code for createn the stretch menu - - stretchMenu = formatMenu->addMenu( tr("S&tretch") ); - stretchsgroup = new QActionGroup( this ); - - stretchUltraCondensed = new QAction( tr("U<ra Condensed"), this); - stretchUltraCondensed->setCheckable( true ); - stretchUltraCondensed->setStatusTip( tr("Set font stretech to Ultra Condensed") ); - stretchs_.insert( QFont::UltraCondensed, stretchUltraCondensed ); - stretchsgroup->addAction( stretchUltraCondensed ); - - stretchExtraCondensed = new QAction( tr("E&xtra Condensed"), this); - stretchExtraCondensed->setCheckable( true ); - stretchExtraCondensed->setStatusTip( tr("Set font stretech to Extra Condensed") ); - stretchs_.insert( QFont::ExtraCondensed, stretchExtraCondensed ); - stretchsgroup->addAction( stretchExtraCondensed ); - - stretchCondensed = new QAction( tr("&Condensed"), this); - stretchCondensed->setCheckable( true ); - stretchCondensed->setStatusTip( tr("Set font stretech to Condensed") ); - stretchs_.insert( QFont::Condensed, stretchCondensed ); - stretchsgroup->addAction( stretchCondensed ); - - stretchSemiCondensed = new QAction( tr("S&emi Condensed"), this); - stretchSemiCondensed->setCheckable( true ); - stretchSemiCondensed->setStatusTip( tr("Set font stretech to Semi Condensed") ); - stretchs_.insert( QFont::SemiCondensed, stretchSemiCondensed ); - stretchsgroup->addAction( stretchSemiCondensed ); - - stretchUnstretched = new QAction( tr("&Unstretched"), this); - stretchUnstretched->setCheckable( true ); - stretchUnstretched->setStatusTip( tr("Set font stretech to Unstretched") ); - stretchs_.insert( QFont::Unstretched, stretchUnstretched ); - stretchsgroup->addAction( stretchUnstretched ); - - stretchSemiExpanded = new QAction( tr("&Semi Expanded"), this); - stretchSemiExpanded->setCheckable( true ); - stretchSemiExpanded->setStatusTip( tr("Set font stretech to Semi Expanded") ); - stretchs_.insert( QFont::SemiExpanded, stretchSemiExpanded ); - stretchsgroup->addAction( stretchSemiExpanded ); - - stretchExpanded = new QAction( tr("&Expanded"), this); - stretchExpanded->setCheckable( true ); - stretchExpanded->setStatusTip( tr("Set font stretech to Expanded") ); - stretchs_.insert( QFont::Expanded, stretchExpanded ); - stretchsgroup->addAction( stretchExpanded ); - - stretchExtraExpanded = new QAction( tr("Ex&tra Expanded"), this); - stretchExtraExpanded->setCheckable( true ); - stretchExtraExpanded->setStatusTip( tr("Set font stretech to Extra Expanded") ); - stretchs_.insert( QFont::ExtraExpanded, stretchExtraExpanded ); - stretchsgroup->addAction( stretchExtraExpanded ); - - stretchUltraExpanded = new QAction( tr("Ult&ra Expanded"), this); - stretchUltraExpanded->setCheckable( true ); - stretchUltraExpanded->setStatusTip( tr("Set font stretech to Ultra Expanded") ); - stretchs_.insert( QFont::UltraExpanded, stretchUltraExpanded ); - stretchsgroup->addAction( stretchUltraExpanded ); - - connect( stretchMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateFontStretchMenu() )); - connect( stretchMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeFontStretch(QAction*) )); - - - stretchMenu->addAction( stretchUltraCondensed ); - stretchMenu->addAction( stretchExtraCondensed ); - stretchMenu->addAction( stretchCondensed ); - stretchMenu->addAction( stretchSemiCondensed ); - stretchMenu->addSeparator(); - stretchMenu->addAction( stretchUnstretched ); - stretchMenu->addSeparator(); - stretchMenu->addAction( stretchSemiExpanded ); - stretchMenu->addAction( stretchExpanded ); - stretchMenu->addAction( stretchExtraExpanded ); - stretchMenu->addAction( stretchUltraExpanded ); - - // ----------------------------------------------------- - // END: Stretch - - - - // COLOR - // ----------------------------------------------------- - // Code for createn the color menu - colorMenu = formatMenu->addMenu( tr("&Color") ); - colorsgroup = new QActionGroup( this ); - - colorBlack = new QAction( tr("Blac&k"), this); - colorBlack->setCheckable( true ); - colorBlack->setStatusTip( tr("Set font color to Black") ); - colors_.insert( colorBlack, new QColor(0,0,0) ); - colorsgroup->addAction( colorBlack ); - - colorWhite = new QAction( tr("&White"), this); - colorWhite->setCheckable( true ); - colorWhite->setStatusTip( tr("Set font color to White") ); - colors_.insert( colorWhite, new QColor(255,255,255) ); - colorsgroup->addAction( colorWhite ); - - color10Gray = new QAction( tr("&10% Gray"), this); - color10Gray->setCheckable( true ); - color10Gray->setStatusTip( tr("Set font color to 10% Gray") ); - colors_.insert( color10Gray, new QColor(25,25,25) ); - colorsgroup->addAction( color10Gray ); - - color33Gray = new QAction( tr("&33% Gray"), this); - color33Gray->setCheckable( true ); - color33Gray->setStatusTip( tr("Set font color to 33% Gray") ); - colors_.insert( color33Gray, new QColor(85,85,85) ); - colorsgroup->addAction( color33Gray ); - - color50Gray = new QAction( tr("&50% Gray"), this); - color50Gray->setCheckable( true ); - color50Gray->setStatusTip( tr("Set font color to 50% Gray") ); - colors_.insert( color50Gray, new QColor(128,128,128) ); - colorsgroup->addAction( color50Gray ); - - color66Gray = new QAction( tr("&66% Gray"), this); - color66Gray->setCheckable( true ); - color66Gray->setStatusTip( tr("Set font color to 66% Gray") ); - colors_.insert( color66Gray, new QColor(170,170,170) ); - colorsgroup->addAction( color66Gray ); - - color90Gray = new QAction( tr("&90% Gray"), this); - color90Gray->setCheckable( true ); - color90Gray->setStatusTip( tr("Set font color to 90% Gray") ); - colors_.insert( color90Gray, new QColor(230,230,230) ); - colorsgroup->addAction( color90Gray ); - - colorRed = new QAction( tr("&Red"), this); - colorRed->setCheckable( true ); - colorRed->setStatusTip( tr("Set font color to Red") ); - colors_.insert( colorRed, new QColor(255,0,0) ); - colorsgroup->addAction( colorRed ); - - colorGreen = new QAction( tr("&Green"), this); - colorGreen->setCheckable( true ); - colorGreen->setStatusTip( tr("Set font color to Green") ); - colors_.insert( colorGreen, new QColor(0,255,0) ); - colorsgroup->addAction( colorGreen ); - - colorBlue = new QAction( tr("&Blue"), this); - colorBlue->setCheckable( true ); - colorBlue->setStatusTip( tr("Set font color to Blue") ); - colors_.insert( colorBlue, new QColor(0,0,255) ); - colorsgroup->addAction( colorBlue ); - - colorCyan = new QAction( tr("&Cyan"), this); - colorCyan->setCheckable( true ); - colorCyan->setStatusTip( tr("Set font color to Cyan") ); - colors_.insert( colorCyan, new QColor(0,255,255) ); - colorsgroup->addAction( colorCyan ); - - colorMagenta = new QAction( tr("&Magenta"), this); - colorMagenta->setCheckable( true ); - colorMagenta->setStatusTip( tr("Set font color to Magenta") ); - colors_.insert( colorMagenta, new QColor(255,0,255) ); - colorsgroup->addAction( colorMagenta ); - - colorYellow = new QAction( tr("&Yellow"), this); - colorYellow->setCheckable( true ); - colorYellow->setStatusTip( tr("Set font color to Yellow") ); - colors_.insert( colorYellow, new QColor(255,255,0) ); - colorsgroup->addAction( colorYellow ); - - colorOther = new QAction( tr("&Other..."), this); - colorOther->setCheckable( true ); - colorOther->setStatusTip( tr("Select font color") ); - - - connect( colorMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateFontColorMenu() )); - connect( colorMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeFontColor(QAction*) )); - - - colorMenu->addAction( colorBlack ); - colorMenu->addAction( colorWhite ); - colorMenu->addAction( color10Gray ); - colorMenu->addAction( color33Gray ); - colorMenu->addAction( color50Gray ); - colorMenu->addAction( color66Gray ); - colorMenu->addAction( color90Gray ); - colorMenu->addAction( colorRed ); - colorMenu->addAction( colorGreen ); - colorMenu->addAction( colorBlue ); - colorMenu->addAction( colorCyan ); - colorMenu->addAction( colorMagenta ); - colorMenu->addAction( colorYellow ); - colorMenu->addSeparator(); - colorMenu->addAction( colorOther ); - - // ----------------------------------------------------- - // END: Color - - - // Extra meny for choosing font from a dialog, because all fonts - // can't be displayed in the font menu - chooseFont = new QAction( tr("C&hoose Font..."), this); - chooseFont->setCheckable( false ); - chooseFont->setStatusTip( tr("Select font") ); - connect(chooseFont, SIGNAL(triggered()), this, SLOT(selectFont())); - formatMenu->addAction( chooseFont ); - - - // ALIGNMENT - // ----------------------------------------------------- - // Code for createn the alignment menus - formatMenu->addSeparator(); - - alignmentMenu = formatMenu->addMenu( tr("&Alignment") ); - alignmentsgroup = new QActionGroup( this ); - verticalAlignmentMenu = formatMenu->addMenu( tr("&Vertical Alignment") ); - verticalAlignmentsgroup = new QActionGroup( this ); - - alignmentLeft = new QAction( tr("&Left"), this); - alignmentLeft->setCheckable( true ); - alignmentLeft->setStatusTip( tr("Set text alignment to Left") ); - alignments_.insert( Qt::AlignLeft, alignmentLeft ); - alignmentsgroup->addAction( alignmentLeft ); - - alignmentRight = new QAction( tr("&Right"), this); - alignmentRight->setCheckable( true ); - alignmentRight->setStatusTip( tr("Set text alignment to Right") ); - alignments_.insert( Qt::AlignRight, alignmentRight ); - alignmentsgroup->addAction( alignmentRight ); - - alignmentCenter = new QAction( tr("&Center"), this); - alignmentCenter->setCheckable( true ); - alignmentCenter->setStatusTip( tr("Set text alignment to Center") ); - alignments_.insert( Qt::AlignHCenter, alignmentCenter ); - alignmentsgroup->addAction( alignmentCenter ); - - alignmentJustify = new QAction( tr("&Justify"), this); - alignmentJustify->setCheckable( true ); - alignmentJustify->setStatusTip( tr("Set text alignment to Justify") ); - alignments_.insert( Qt::AlignJustify, alignmentJustify ); - alignmentsgroup->addAction( alignmentJustify ); - - verticalNormal = new QAction( tr("&Normal/Baseline"), this); - verticalNormal->setCheckable( true ); - verticalNormal->setStatusTip( tr("Set vertical text alignment to Normal") ); - verticals_.insert( QTextCharFormat::AlignNormal, verticalNormal ); - verticalAlignmentsgroup->addAction( verticalNormal ); - - verticalSub = new QAction( tr("&Subscript"), this); - verticalSub->setCheckable( true ); - verticalSub->setStatusTip( tr("Set vertical text alignment to Subscript") ); - verticals_.insert( QTextCharFormat::AlignSubScript, verticalSub ); - verticalAlignmentsgroup->addAction( verticalSub ); - - verticalSuper = new QAction( tr("S&uperscript"), this); - verticalSuper->setCheckable( true ); - verticalSuper->setStatusTip( tr("Set vertical text alignment to Superscript") ); - verticals_.insert( QTextCharFormat::AlignSuperScript, verticalSuper ); - verticalAlignmentsgroup->addAction( verticalSuper ); - - connect( alignmentMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateTextAlignmentMenu() )); - connect( alignmentMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeTextAlignment(QAction*) )); - connect( verticalAlignmentMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateVerticalAlignmentMenu() )); - connect( verticalAlignmentMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeVerticalAlignment(QAction*) )); - - - alignmentMenu->addAction( alignmentLeft ); - alignmentMenu->addAction( alignmentRight ); - alignmentMenu->addAction( alignmentCenter ); - alignmentMenu->addAction( alignmentJustify ); - verticalAlignmentMenu->addAction( verticalNormal ); - verticalAlignmentMenu->addAction( verticalSub ); - verticalAlignmentMenu->addAction( verticalSuper ); - - // ----------------------------------------------------- - // END: Text Alignment - - - // BORDER - // ----------------------------------------------------- - // Code for createn the border menu - formatMenu->addSeparator(); - borderMenu = formatMenu->addMenu( tr("&Border") ); - bordersgroup = new QActionGroup( this ); - - int borderSizes[] = { 0,1,2,3,4,5,6,7,8,9,10 }; - for( int i = 0; i < sizeof(borderSizes)/sizeof(int); i++ ) - { - QString name; - name.setNum( borderSizes[i] ); - QAction *tmp = new QAction( name, this ); - tmp->setCheckable( true ); - borders_.insert( borderSizes[i], tmp ); - borderMenu->addAction( tmp ); - bordersgroup->addAction( tmp ); - } - - - connect( borderMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateBorderMenu() )); - connect( borderMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeBorder(QAction*) )); - - - borderMenu->addSeparator(); - borderOther = new QAction( "&Other...", this ); - borderOther->setCheckable( true ); - borderMenu->addAction( borderOther ); - - // ----------------------------------------------------- - // END: Border - - - // MARGIN - // ----------------------------------------------------- - // Code for createn the margin menu - marginMenu = formatMenu->addMenu( tr("&Margin") ); - marginsgroup = new QActionGroup( this ); - - int marginSizes[] = { 0,1,2,3,4,5,6,7,8,9,10,15,20,25,30 }; - for( int i = 0; i < sizeof(marginSizes)/sizeof(int); i++ ) - { - QString name; - name.setNum( marginSizes[i] ); - QAction *tmp = new QAction( name, this ); - tmp->setCheckable( true ); - margins_.insert( marginSizes[i], tmp ); - marginMenu->addAction( tmp ); - marginsgroup->addAction( tmp ); - } - - - connect( marginMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateMarginMenu() )); - connect( marginMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changeMargin(QAction*) )); - - - marginMenu->addSeparator(); - marginOther = new QAction( "&Other...", this ); - marginOther->setCheckable( true ); - marginMenu->addAction( marginOther ); - - // ----------------------------------------------------- - // END: Margin - - - // PADDING - // ----------------------------------------------------- - // Code for createn the padding menu - paddingMenu = formatMenu->addMenu( tr("&Padding") ); - paddingsgroup = new QActionGroup( this ); - - int paddingSizes[] = { 0,2,4,6,8,10,15 }; - for( int i = 0; i < sizeof(paddingSizes)/sizeof(int); i++ ) - { - QString name; - name.setNum( paddingSizes[i] ); - QAction *tmp = new QAction( name, this ); - tmp->setCheckable( true ); - paddings_.insert( paddingSizes[i], tmp ); - paddingMenu->addAction( tmp ); - paddingsgroup->addAction( tmp ); - } - - - connect( paddingMenu, SIGNAL( aboutToShow() ), - this, SLOT( updatePaddingMenu() )); - connect( paddingMenu, SIGNAL( triggered(QAction*) ), - this, SLOT( changePadding(QAction*) )); - - - paddingMenu->addSeparator(); - paddingOther = new QAction( "&Other...", this ); - paddingOther->setCheckable( true ); - paddingMenu->addAction( paddingOther ); - - // ----------------------------------------------------- - // END: Padding - - - /* Old menu code //AF - menuBar()->insertItem("&Format", formatMenu); - stylesgroup->addTo(formatMenu); - groupAction->addTo(formatMenu); - inputAction->addTo(formatMenu); - formatMenu->insertSeparator(1); - */ - - connect(formatMenu, SIGNAL(aboutToShow()), - this, SLOT(updateStyleMenu())); - connect( formatMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateMenus() )); - - formatMenu->addSeparator(); - formatMenu->addAction(toolBar->toggleViewAction()); - - -// showToolBarAction = new QAction(formatMenu, "Show toolbar", true); -// connect(showToolBarAction, SIGNAL(toggled(bool)), toolBar, SLOT(setVisible(bool))); -// connect(toolBar->toggleViewAction(), SIGNAL(toggled(bool)), showToolBarAction - - } - - /*! - * \author Anders Fernström - * \date 2005-11-18 - * - * \brief Method for creating insert nemu. - */ - void NotebookWindow::createInsertMenu() - { - // IMAGE - insertImageAction = new QAction( tr("&Image"), this ); - insertImageAction->setShortcut( tr("Ctrl+Shift+M") ); - insertImageAction->setStatusTip( tr("Insert a image into the cell") ); - connect( insertImageAction, SIGNAL( triggered() ), - this, SLOT( insertImage() )); - insertImageAction->setIcon(QIcon(":/Resources/toolbarIcons/image.png")); - toolBar->addAction(insertImageAction); - - // LINK - insertLinkAction = new QAction( tr("&Link"), this ); - insertLinkAction->setShortcut( tr("Ctrl+Shift+L") ); - insertLinkAction->setStatusTip( tr("Insert a link to the selected text") ); - connect( insertLinkAction, SIGNAL( triggered() ), - this, SLOT( insertLink() )); - insertLinkAction->setIcon(QIcon(":/Resources/toolbarIcons/text_under.png")); - toolBar->addAction(insertLinkAction); - - toolBar->addSeparator(); - - //INDENT - indentAction = new QAction(tr("Indent"), this); - indentAction->setStatusTip(tr("Indent the code in the selected cell")); - indentAction->setIcon(QIcon(":/Resources/toolbarIcons/text_right.png")); - connect(indentAction, SIGNAL(triggered()), this, SLOT(indent())); - - - QToolButton * b = new QToolButton; - b->setDefaultAction(indentAction); - indentMenu = new QMenu(this); - autoIndentAction = new QAction("Autoindent", this); - autoIndentAction->setStatusTip(tr("Tries to move the cursor to the right position when return is pressed")); - autoIndentAction->setCheckable(true); -// autoIndentAction->setChecked(true); - - b->hide(); //Disable indentation button - - QSettings s("PELAB", "OMNotebook"); - autoIndentAction->setChecked(s.value("AutoIndent", true).toBool()); - setAutoIndent(autoIndentAction->isChecked()); - - connect(autoIndentAction, SIGNAL(toggled(bool)), this, SLOT(setAutoIndent(bool))); - - - indentMenu->addAction(autoIndentAction); - b->setMenu(indentMenu); - b->setPopupMode(QToolButton::MenuButtonPopup); - toolBar->addWidget(b); - - - //EVAL - - evalAction = new QAction(tr("Evaluate"), this); - evalAction->setStatusTip(tr("Evaluate the selected cell")); - evalAction->setIcon(QIcon(":/Resources/toolbarIcons/apply.png")); - connect(evalAction, SIGNAL(triggered()), this, SLOT(eval())); - toolBar->addAction(evalAction); - - // MENU - insertMenu = menuBar()->addMenu( tr("&Insert") ); - insertMenu->addAction( insertImageAction ); - insertMenu->addAction( insertLinkAction ); - - connect( insertMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateMenus() )); - } - - /*! - * \author Anders Fernström - * \date 2006-01-27 - * - * \brief Method for creating window nemu. - */ - void NotebookWindow::createWindowMenu() - { - windowMenu = menuBar()->addMenu( tr("&Window") ); - - connect( windowMenu, SIGNAL( triggered(QAction *) ), - this, SLOT( changeWindow(QAction *) )); - connect( windowMenu, SIGNAL( aboutToShow() ), - this, SLOT( updateWindowMenu() )); - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 (update) - * - * \brief Method for creating about nemu. - * - * 2005-10-07 AF, Remade the function when porting to QT4. - * 2006-02-03 AF, added help action. - */ - void NotebookWindow::createAboutMenu() - { - // 2005-10-07 AF, Porting, replaced this - //QAction *aboutAction = new QAction("About", "&About", 0, this, "about"); - //QObject::connect(aboutAction, SIGNAL(activated()), this, SLOT(aboutQTNotebook())); - aboutAction = new QAction( tr("&About OMNotebook"), this ); - aboutAction->setStatusTip( tr("Display OMNotebook's About dialog") ); - connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutQTNotebook())); - - // 2006-02-03 AF, Added a help action - helpAction = new QAction( tr("&Help Text"), this ); - helpAction->setShortcut( tr("F1") ); - helpAction->setStatusTip( tr("Open help document") ); - connect( helpAction, SIGNAL( triggered() ), - this, SLOT( helpText() )); - - // 2006-02-21 AF, Added a about qt action - aboutQtAction = new QAction( tr("About &Qt"), this ); - aboutQtAction->setStatusTip( tr("Display information about Qt") ); - connect( aboutQtAction, SIGNAL( triggered() ), - this, SLOT( aboutQT() )); - - - // 2005-10-07 AF, Porting, new code for creating menu - aboutMenu = menuBar()->addMenu( tr("&Help") ); - aboutMenu->addAction( aboutAction ); - aboutMenu->addAction( aboutQtAction ); - aboutMenu->addSeparator(); - aboutMenu->addAction( helpAction ); - - /* Old menu code //AF - aboutMenu = new Q3PopupMenu(this); - menuBar()->insertItem("&Help", aboutMenu); - aboutAction->addTo(aboutMenu); - */ - } - - /*! - * \author Anders Fernström - * \date 2005-11-11 - * - * \brief Check if the currentCell is editable - */ - bool NotebookWindow::cellEditable() - { - return subject_->getCursor()->currentCell()->isEditable(); - } - - /*! - * \author Anders Fernström - * \date 2006-02-14 - * - * \brief eval all selected cell - */ - void NotebookWindow::evalCells() - { - application()->commandCenter()->executeCommand( - new EvalSelectedCells( subject_ )); - } - - /*! - * \author Ingemar Axelsson - */ + /*! + * \class NotebookWindow + * \author Ingemar Axelsson and Anders Fernström + * + * \brief This class describes a mainwindow using the CellDocument + * + * This is the main applicationwindow. It contains of a menu, a + * toolbar, a statusbar and a workspace. The workspace will contain a + * celldocument view. + * + * + * \todo implement a timer that saves a document every 5 minutes + * or so. + * + * \todo Implement section numbering. Could be done with some kind + * of vistors. + * + * + * \bug Segmentation fault when quit. Only sometimes. + */ + + + // 2006-03-01 AF, Open, Save, Image and Link dir + QString NotebookWindow::openDir_ = QString::null; + QString NotebookWindow::saveDir_ = QString::null; + QString NotebookWindow::imageDir_ = QString::null; + QString NotebookWindow::linkDir_ = QString::null; + + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2006-01-17 (update) + * + * \brief The class constructor + * + * 2006-01-16 AF, Added an icon to the window + * Also made som other updates /AF + */ + NotebookWindow::NotebookWindow(Document *subject, + const QString filename, QWidget *parent) + : DocumentView(parent), + subject_(subject), + filename_(filename), + closing_(false), + app_( subject->application() ), //AF + findForm_( 0 ) //AF + { + if( filename_ != QString::null ) + qDebug( filename_.toStdString().c_str() ); + +// subject_->attach(this); +// setMinimumSize( 150, 220 ); //AF + + toolBar = new QToolBar("Show toolbar", this); + + + posIndicator = new QLabel(""); + posIndicator->setMinimumWidth(75); + stateIndicator = new QLabel(""); + stateIndicator->setMinimumWidth(60); + + statusBar()->insertPermanentWidget(0,posIndicator); + statusBar()->insertPermanentWidget(0,stateIndicator); + createFileMenu(); + createEditMenu(); + createCellMenu(); + createFormatMenu(); + createInsertMenu(); + createWindowMenu(); + createAboutMenu(); + + toolBar->addSeparator(); + toolBar->addAction(quitWindowAction); + addToolBar(toolBar); //Add icons, update the edit menu etc. + + subject_->attach(this); + setMinimumSize( 150, 220 ); //AF + + + // 2006-01-16 AF, Added an icon to the window +// setWindowIcon( QIcon("./omnotebook_png.png") ); + setWindowIcon( QIcon(":/Resources/omnotebook_png.png")); + + statusBar()->showMessage("Ready"); + resize(800, 600); + + connect( subject_->getCursor(), SIGNAL( changedPosition() ), + this, SLOT( updateMenus() )); + connect( subject_, SIGNAL( contentChanged() ), + this, SLOT( updateWindowTitle() )); + connect( subject_, SIGNAL( hoverOverFile(QString) ), + this, SLOT( setStatusMessage(QString) )); + // 2006-04-27 AF + connect( subject_, SIGNAL( forwardAction(int) ), + this, SLOT( forwardedAction(int) )); + + connect( subject_, SIGNAL(updatePos(int, int)), this, SLOT(setPosition(int, int))); + + connect( subject_, SIGNAL(newState(QString)), this, SLOT(setState(QString))); + + connect( subject_, SIGNAL(setStatusMenu(QList)), this, SLOT(setStatusMenu(QList))); + + updateWindowTitle(); + updateChapterCounters(); + update(); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2006-08-24 (update) + * + * \brief The class destructor + * + * 2005-11-03/04/07 AF, added som things that should be deleted. + * 2006-01-05 AF, added code so all inputcells are added to the + * removelist in the highlighter + * 2006-01-27 AF, remove this notebook window from the list of + * notebook windows in the main applicaiton + * 2006-08-24 AF, delete replace action + */ + NotebookWindow::~NotebookWindow() + { + //2006-01-27 AF, remove document view from application lsit + application()->removeDocumentView( this ); + + //2006-01-05 AF, add all inputcell to removelist on highlighter + RemoveHighlighterVisitor visitor; + subject_->runVisitor( visitor ); + + subject_->detach(this); + delete subject_; + //subject_ = 0; + + // 2005-11-03/04/07 AF, remova all created QAction + map::iterator s_iter = styles_.begin(); + while( s_iter != styles_.end() ) + { + delete (*s_iter).second; + ++s_iter; + } + + QHash::iterator f_iter = fonts_.begin(); + while( f_iter != fonts_.end() ) + { + delete f_iter.value(); + ++f_iter; + } + + QHash::iterator c_iter = colors_.begin(); + while( c_iter != colors_.end() ) + { + delete c_iter.value(); + ++c_iter; + } + + QHash::iterator w_iter = windows_.begin(); + while( w_iter != windows_.end() ) + { + delete w_iter.key(); + ++w_iter; + } + + delete stylesgroup; + delete fontsgroup; + delete sizesgroup; + delete stretchsgroup; + delete colorsgroup; + delete alignmentsgroup; + delete verticalAlignmentsgroup; + delete bordersgroup; + delete marginsgroup; + delete paddingsgroup; + + + delete newAction; + delete openFileAction; + delete saveAsAction; + delete saveAction; + delete printAction; + delete closeFileAction; + delete quitWindowAction; + + delete undoAction; + delete redoAction; + delete cutAction; + delete copyAction; + delete pasteAction; + delete findAction; + delete replaceAction; + delete showExprAction; + + //delete cutCellAction; + //delete copyCellAction; + //delete pasteCellAction; + delete addCellAction; + delete ungroupCellAction; + delete splitCellAction; + delete deleteCellAction; + delete nextCellAction; + delete previousCellAction; + + delete groupAction; + delete inputAction; + delete textAction; + + delete aboutAction; + delete helpAction; + delete aboutQtAction; + + delete facePlain; + delete faceBold; + delete faceItalic; + delete faceUnderline; + + delete sizeSmaller; + delete sizeLarger; + delete size8pt; + delete size9pt; + delete size10pt; + delete size12pt; + delete size14pt; + delete size16pt; + delete size18pt; + delete size20pt; + delete size24pt; + delete size36pt; + delete size72pt; + delete sizeOther; + + delete stretchUltraCondensed; + delete stretchExtraCondensed; + delete stretchCondensed; + delete stretchSemiCondensed; + delete stretchUnstretched; + delete stretchSemiExpanded; + delete stretchExpanded; + delete stretchExtraExpanded; + delete stretchUltraExpanded; + + delete colorBlack; + delete colorWhite; + delete color10Gray; + delete color33Gray; + delete color50Gray; + delete color66Gray; + delete color90Gray; + delete colorRed; + delete colorGreen; + delete colorBlue; + delete colorCyan; + delete colorMagenta; + delete colorYellow; + delete colorOther; + + delete chooseFont; + + delete alignmentLeft; + delete alignmentRight; + delete alignmentCenter; + delete alignmentJustify; + delete verticalNormal; + delete verticalSub; + delete verticalSuper; + + delete borderOther; + delete marginOther; + delete paddingOther; + + delete insertImageAction; + delete insertLinkAction; + delete importOldFile; + delete exportPureText; + + // 2006-08-24 AF, delete findForm if it exists + if( findForm_ ) + delete findForm_; + + delete toolBar; + delete posIndicator; + delete stateIndicator; + } + + /*! + * \author Ingemar Axelsson + */ + + //class Frame: public QFrame + //{ + //protected: + // void paintEvent(QPaintEvent *event) + // { + // QPainter p(this); + // p.save(); + // p.setMatrix(QMatrix(.5, 1, .3, .7,1,1)); + // QFrame::paintEvent(event); + // p.restore(); + // } + //}; + void NotebookWindow::update() + { + QFrame *mainWidget = subject_->getState(); + + mainWidget->setParent(this); + mainWidget->move( QPoint(0,0) ); + + + setCentralWidget(mainWidget); +// mainWidget->setMaximumHeight(250); + mainWidget->show(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-30 + * + * \brief Return the notebook windons document + */ + Document* NotebookWindow::document() + { + return subject_; + } + + /*! + * \author Ingemar Axelsson + */ + CellApplication *NotebookWindow::application() + { + return subject_->application(); + } + + /*! + * \author Anders Fernström + * \date 2005-12-01 (update) + * + * \brief Method for creating file nemu. + * + * 2005-10-07 AF, Updated/Remade the function when porting to QT4. + * 2005-11-21 AF, Added a export menu + * 2005-12-01 AF, Added a import menu + */ + void NotebookWindow::createFileMenu() + { + // NEW + newAction = new QAction( tr("&New"), this ); + newAction->setShortcut( tr("Ctrl+N") ); + newAction->setStatusTip( tr("Create a new document") ); + connect(newAction, SIGNAL(triggered()), this, SLOT(newFile())); + newAction->setIcon(QIcon(":/Resources/toolbarIcons/filenew.png")); + + toolBar->addAction(newAction); + + + recentMenu = new QMenu("Recent &Files", this); + + // OPEN FILE + openFileAction = new QAction( tr("&Open"), this ); + openFileAction->setShortcut( tr("Ctrl+O") ); + openFileAction->setStatusTip( tr("Open a file") ); + connect(openFileAction, SIGNAL(triggered()), this, SLOT(openFile())); + openFileAction->setIcon(QIcon(":/Resources/toolbarIcons/fileopen.png")); + + QToolButton *b = new QToolButton(this); + b->setDefaultAction(openFileAction); + b->setMenu(recentMenu); + b->setPopupMode(QToolButton::MenuButtonPopup); +// toolBar->addAction(openFileAction); + toolBar->addWidget(b); + + // SAVE AS + saveAsAction = new QAction( tr("Save &As..."), this ); + saveAsAction->setShortcut( tr("Ctrl+Shift+S") ); + saveAsAction->setStatusTip( tr("Save the document as a new file") ); + connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveas())); + + // SAVE + saveAction = new QAction( tr("&Save"), this ); + saveAction->setShortcut( tr("Ctrl+S") ); + saveAction->setStatusTip( tr("Save the document") ); + connect(saveAction, SIGNAL(triggered()), this, SLOT(save())); + saveAction->setIcon(QIcon(":/Resources/toolbarIcons/filesave.png")); + toolBar->addAction(saveAction); + + toolBar->addSeparator(); + + // CLOSE FILE + closeFileAction = new QAction( tr("&Close"), this ); + closeFileAction->setShortcut( tr("Ctrl+F4") ); + closeFileAction->setStatusTip( tr("Close the window") ); + connect(closeFileAction, SIGNAL(triggered()), this, SLOT(closeFile())); + + // PRINT + printAction = new QAction( tr("&Print"), this ); + printAction->setShortcut( tr("Ctrl+P") ); + printAction->setStatusTip( tr("Print the document") ); + connect(printAction, SIGNAL(triggered()), this, SLOT(print())); + printAction->setIcon(QIcon(":/Resources/toolbarIcons/fileprint.png")); + toolBar->addAction(printAction); + + toolBar->addSeparator(); + + + + // QUIT WINDOW + quitWindowAction = new QAction( tr("&Quit"), this ); + quitWindowAction->setShortcut( tr("Ctrl+Q") ); + quitWindowAction->setStatusTip( tr("Quit OMNotebook") ); + quitWindowAction->setIcon(QIcon(":/Resources/toolbarIcons/exit.png")); + + connect(quitWindowAction, SIGNAL(triggered()), this, SLOT(quitOMNotebook())); + + // CREATE MENU + fileMenu = menuBar()->addMenu( tr("&File") ); + fileMenu->addAction( newAction ); + fileMenu->addAction( openFileAction ); + fileMenu->addAction( saveAction ); + fileMenu->addAction( saveAsAction ); + fileMenu->addAction( closeFileAction ); + fileMenu->addSeparator(); + fileMenu->addAction( printAction ); + fileMenu->addSeparator(); + + // RECENT FILES +// recentMenu = fileMenu->addMenu("Recent &Files"); + fileMenu->addMenu(recentMenu); + + QSettings s("PELAB", "OMNotebook"); + QString recentFile; + for(int i = 0; i < 4; ++i) + { + if((recentFile = s.value(QString("Recent")+QString(i), QString()).toString()) != QString()) + { + QAction* tmpAction = recentMenu->addAction(recentFile); + connect(tmpAction, SIGNAL(triggered()), this, SLOT(recentTriggered())); + + } + } + + fileMenu->addSeparator(); + + importMenu = fileMenu->addMenu( tr("&Import") ); + exportMenu = fileMenu->addMenu( tr("E&xport") ); + fileMenu->addSeparator(); + fileMenu->addAction( quitWindowAction ); + + + // IMPORT MENU + // Added 2005-12-01 + importOldFile = new QAction( tr("&Old OMNotebook file"), this ); + importOldFile->setStatusTip( tr("Import an old OMNotebook file") ); + connect( importOldFile, SIGNAL( triggered() ), + this, SLOT( openOldFile() )); + + importMenu->addAction( importOldFile ); + + + // EXPORT MENU + // Added 2005-11-21 + exportPureText = new QAction( tr("&Pure text"), this ); + exportPureText->setStatusTip( tr("Export the document content to pure text") ); + connect( exportPureText, SIGNAL( triggered() ), + this, SLOT( pureText() )); + + exportMenu->addAction( exportPureText ); + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 (update) + * + * \brief Method for creating edit nemu. + * + * 2005-10-07 AF, Remade the function when porting to QT4. + * 2006-02-03 AF, Made undo, redo, cut, copy and paste actions for the editor + * 2006-08-24 AF, added a replace action, renamed search action to find action + */ + void NotebookWindow::createEditMenu() + { + // 2005-10-07 AF, Porting, replaced this + //QAction *undoAction = new QAction("Undo", "&Undo", 0, this, "undoaction"); + undoAction = new QAction( tr("&Undo"), this); + undoAction->setShortcut( tr("Ctrl+Z") ); + undoAction->setStatusTip( tr("Undo last action") ); + connect( undoAction, SIGNAL( triggered() ), + this, SLOT( undoEdit() )); + + undoAction->setEnabled(false); + undoAction->setIcon(QIcon(":/Resources/toolbarIcons/undo.png")); + toolBar->addAction(undoAction); + + + // 2005-10-07 AF, Porting, replaced this + //QAction *redoAction = new QAction("Redo", "&Redo", 0, this, "redoaction"); + redoAction = new QAction( tr("&Redo"), this); + redoAction->setShortcut( tr("Ctrl+Y") ); + redoAction->setStatusTip( tr("Redo last action") ); + connect( redoAction, SIGNAL( triggered() ), + this, SLOT( redoEdit() )); + + redoAction->setEnabled(false); + redoAction->setIcon(QIcon(":/Resources/toolbarIcons/redo.png")); + toolBar->addAction(redoAction); + + toolBar->addSeparator(); + + // CUT + cutAction = new QAction( tr("Cu&t"), this); + cutAction->setShortcut( tr("Ctrl+X") ); + cutAction->setStatusTip( tr("Cut selected text") ); + connect( cutAction, SIGNAL( triggered() ), + this, SLOT( cutEdit() )); + + cutAction->setEnabled(false); + cutAction->setIcon(QIcon(":/Resources/toolbarIcons/editcut.png")); + toolBar->addAction(cutAction); + + // COPY + copyAction = new QAction( tr("&Copy"), this); + copyAction->setShortcut( tr("Ctrl+C") ); + copyAction->setStatusTip( tr("Copy selected text") ); + connect( copyAction, SIGNAL( triggered() ), + this, SLOT( copyEdit() )); + + copyAction->setEnabled(false); + copyAction->setIcon(QIcon(":/Resources/toolbarIcons/editcopy.png")); + toolBar->addAction(copyAction); + + + // PASTE + pasteAction = new QAction( tr("&Paste"), this); + pasteAction->setShortcut( tr("Ctrl+V") ); + pasteAction->setStatusTip( tr("Paste text from clipboard") ); + connect( pasteAction, SIGNAL( triggered() ), + this, SLOT( pasteEdit() )); + + + pasteAction->setIcon(QIcon(":/Resources/toolbarIcons/editpaste.png")); + toolBar->addAction(pasteAction); + + toolBar->addSeparator(); + + + // FIND + findAction = new QAction( tr("&Find"), this); + findAction->setShortcut( tr("Ctrl+F") ); + findAction->setStatusTip( tr("Search through the document") ); + connect( findAction, SIGNAL( triggered() ), + this, SLOT( findEdit() )); + + findAction->setIcon(QIcon(":/Resources/toolbarIcons/find.png")); + toolBar->addAction(findAction); + toolBar->addSeparator(); + + // REPLACE, added 2006-08-24 AF + replaceAction = new QAction( tr("Re&place"), this); + replaceAction->setShortcut( tr("Ctrl+H") ); + replaceAction->setStatusTip( tr("Search through the document and replace") ); + connect( replaceAction, SIGNAL( triggered() ), + this, SLOT( replaceEdit() )); + + + // 2005-10-07 AF, Porting, replaced this + //QAction *showExprAction = new QAction("View Expression", "&View Expression",0, this, "viewexpr"); + //QObject::connect(showExprAction, SIGNAL(toggled(bool)), subject_, SLOT(showHTML(bool))); + showExprAction = new QAction( tr("&View Expression"), this); + showExprAction->setStatusTip( tr("View the expression in the cell") ); + showExprAction->setCheckable(true); + showExprAction->setChecked(false); + connect(showExprAction, SIGNAL(toggled(bool)), subject_, SLOT(showHTML(bool))); + + // 2005-10-07 AF, Porting, new code for creating menu + // 2006-02-03 AF, removed SEARCH from menu, + // because they havn't been implemented yet. + editMenu = menuBar()->addMenu( tr("&Edit") ); + editMenu->addAction( undoAction ); + editMenu->addAction( redoAction ); + editMenu->addSeparator(); + editMenu->addAction( cutAction ); + editMenu->addAction( copyAction ); + editMenu->addAction( pasteAction ); + editMenu->addSeparator(); + editMenu->addAction( findAction ); + editMenu->addAction( replaceAction ); + editMenu->addSeparator(); + editMenu->addAction( showExprAction ); + + + /* Old menu code //AF + editMenu = new Q3PopupMenu(this); + menuBar()->insertItem("&Edit", editMenu); + undoAction->addTo(editMenu); + redoAction->addTo(editMenu); + editMenu->insertSeparator(3); + searchAction->addTo(editMenu); + showExprAction->addTo(editMenu); + */ + + +// QObject::connect(editMenu, SIGNAL(aboutToShow()), //HE 071119 +// this, SLOT(updateEditMenu())); // -''- + } + + /*! + * \author Anders Fernström + * \date 2006-04-27 (update) + * + * \brief Method for creating cell nemu. + * + * Remade the function when porting to QT4. + * + * 2006-04-26 AF, Added UNGROUP and SPLIT CELL + * 2006-04-27 AF, remove cut,copy,paste cell from menu + */ + void NotebookWindow::createCellMenu() + { + // 2005-10-07 AF, Porting, replaced this + //QAction *cutCellAction = new QAction("Cut cell", "&Cut Cell", CTRL+SHIFT+Key_X, this, "cutcell"); + //QObject::connect(cutCellAction, SIGNAL(activated()), this, SLOT(cutCell())); + /* + cutCellAction = new QAction( tr("Cu&t Cell"), this); + cutCellAction->setShortcut( tr("Ctrl+Shift+X") ); + cutCellAction->setStatusTip( tr("Cut selected cell") ); + connect(cutCellAction, SIGNAL(triggered()), this, SLOT(cutCell())); + + // 2005-10-07 AF, Porting, replaced this + //QAction *copyCellAction = new QAction("Copy cell", "&Copy Cell", CTRL+SHIFT+Key_C, this, "copycell"); + //QObject::connect(copyCellAction, SIGNAL(activated()), this, SLOT(copyCell())); + copyCellAction = new QAction( tr("&Copy Cell"), this); + copyCellAction->setShortcut( tr("Ctrl+Shift+C") ); + copyCellAction->setStatusTip( tr("Copy selected cell") ); + connect(copyCellAction, SIGNAL(triggered()), this, SLOT(copyCell())); + + // 2005-10-07 AF, Porting, replaced this + //QAction *pasteCellAction = new QAction("Paste cell", "&Paste Cell", CTRL+SHIFT+Key_V, this, "pastecell"); + //QObject::connect(pasteCellAction, SIGNAL(activated()), this, SLOT(pasteCell())); + pasteCellAction = new QAction( tr("&Paste Cell"), this); + pasteCellAction->setShortcut( tr("Ctrl+Shift+V") ); + pasteCellAction->setStatusTip( tr("Paste in a cell") ); + connect(pasteCellAction, SIGNAL(triggered()), this, SLOT(pasteCell())); + */ + + addCellAction = new QAction( tr("&Add Cell (previus cell style)"), this); + addCellAction->setShortcut( tr("Alt+Enter") ); + addCellAction->setStatusTip( tr("Add a new textcell with the previuos cells style") ); + connect(addCellAction, SIGNAL(triggered()), this, SLOT(createNewCell())); + + inputAction = new QAction( tr("Add &Inputcell"), this); + inputAction->setShortcut( tr("Ctrl+Shift+I") ); + inputAction->setStatusTip( tr("Add an input cell") ); + connect(inputAction, SIGNAL(triggered()), this, SLOT(inputCellsAction())); + /// fjass + textAction = new QAction( tr("Add &Textcell"), this); + textAction->setShortcut( tr("Ctrl+Shift+T") ); + textAction->setStatusTip( tr("Add a text cell") ); + connect(textAction, SIGNAL(triggered()), this, SLOT(textCellsAction())); + // \fjass + + groupAction = new QAction( tr("&Groupcell"), this); + groupAction->setShortcut( tr("Ctrl+Shift+G") ); + groupAction->setStatusTip( tr("Groupcell") ); + connect( groupAction, SIGNAL( triggered() ), + this, SLOT( groupCellsAction() )); + + // 2006-04-26 AF, UNGROUP + ungroupCellAction = new QAction( tr("&Ungroup groupcell"), this); + ungroupCellAction->setShortcut( tr("Ctrl+Shift+U") ); + ungroupCellAction->setStatusTip( tr("Ungroup the selected groupcell in the tree view") ); + connect( ungroupCellAction, SIGNAL( triggered() ), + this, SLOT( ungroupCell() )); + + // 2006-04-26 AF, SPLIT CELL + splitCellAction = new QAction( tr("&Split cell"), this); + splitCellAction->setShortcut( tr("Ctrl+Shift+P") ); + splitCellAction->setStatusTip( tr("Split selected cell") ); + connect( splitCellAction, SIGNAL( triggered() ), + this, SLOT( splitCell() )); + + // 2005-10-07 AF, Porting, replaced this + //QAction *deleteCellAction = new QAction("Delete cell", "&Delete Cell", CTRL+SHIFT+Key_D, this, "deletecell"); + //QObject::connect(deleteCellAction, SIGNAL(activated()), this, SLOT(deleteCurrentCell())); + deleteCellAction = new QAction( tr("&Delete Cell"), this); + deleteCellAction->setShortcut( tr("Ctrl+Shift+D") ); + deleteCellAction->setStatusTip( tr("Delete selected cell") ); + connect(deleteCellAction, SIGNAL(triggered()), this, SLOT(deleteCurrentCell())); + + // 2005-10-07 AF, Porting, replaced this + //QAction *nextCellAction = new QAction("next cell", "&Next Cell", 0, this, "nextcell"); + //QObject::connect(nextCellAction, SIGNAL(activated()), this, SLOT(moveCursorDown())); + nextCellAction = new QAction( tr("&Next Cell"), this); + nextCellAction->setStatusTip( tr("Move to next cell") ); + connect(nextCellAction, SIGNAL(triggered()), this, SLOT(moveCursorDown())); + + // 2005-10-07 AF, Porting, replaced this + //QAction *previousCellAction = new QAction("previous cell", "&Previous Cell", 0, this, "prevoiscell"); + //QObject::connect(previousCellAction, SIGNAL(activated()), this, SLOT(moveCursorUp())); + previousCellAction = new QAction( tr("P&revious Cell"), this); + previousCellAction->setStatusTip( tr("Move to previous cell") ); + connect(previousCellAction, SIGNAL(triggered()), this, SLOT(moveCursorUp())); + + + // 2005-10-07 AF, Porting, new code for creating menu + // 2006-04-27 AF, remove cut,copy,paste cell from menu + cellMenu = menuBar()->addMenu( tr("&Cell") ); + //cellMenu->addAction( cutCellAction ); + //cellMenu->addAction( copyCellAction ); + //cellMenu->addAction( pasteCellAction ); + //cellMenu->addSeparator(); + cellMenu->addAction( addCellAction ); + cellMenu->addAction( inputAction ); + cellMenu->addAction( textAction ); + + cellMenu->addAction( groupAction ); + cellMenu->addAction( ungroupCellAction ); + cellMenu->addAction( splitCellAction ); + cellMenu->addAction( deleteCellAction ); + cellMenu->addSeparator(); + cellMenu->addAction( nextCellAction ); + cellMenu->addAction( previousCellAction ); + + QObject::connect(cellMenu, SIGNAL(aboutToShow()), + this, SLOT(updateCellMenu())); + + + /* Old menu code //AF + cellMenu = new Q3PopupMenu(this); + menuBar()->insertItem("&Cell", cellMenu); + cutCellAction->addTo(cellMenu); + copyCellAction->addTo(cellMenu); + pasteCellAction->addTo(cellMenu); + addCellAction->addTo(cellMenu); + deleteCellAction->addTo(cellMenu); + nextCellAction->addTo(cellMenu); + previousCellAction->addTo(cellMenu); + cellMenu->insertSeparator(3); + cellMenu->insertSeparator(5); + */ + } + + /*! + * \author Anders Fernström + * \date 2005-10-07 + * \date 2005-11-03 (update) + * + * \brief Method for creating format nemu. + * + * Remade the function when porting to QT4. + * + * 2005-11-03 AF, Updated this function with functionality for + * changes text settings. + */ + void NotebookWindow::createFormatMenu() + { + // 2005-10-07 AF, Portin, Removed + //Create style menus. + //Q3ActionGroup *stylesgroup = new Q3ActionGroup(this, 0, true); + + // 2005-10-07 AF, Portin, Removed + //formatMenu = new Q3PopupMenu(this); + + + // 2005-10-03 AF, get the stylesheet instance + Stylesheet *sheet = Stylesheet::instance("stylesheet.xml"); + + // Create the style actions //AF + stylesgroup = new QActionGroup( this ); + formatMenu = menuBar()->addMenu( tr("&Format") ); + styleMenu = formatMenu->addMenu( tr("&Styles") ); + + vector styles = sheet->getAvailableStyleNames(); + vector::iterator i = styles.begin(); + for(;i != styles.end(); ++i) + { + QAction *tmp = new QAction( tr( (*i).toStdString().c_str() ), this ); + tmp->setCheckable( true ); + styleMenu->addAction( tmp ); + stylesgroup->addAction( tmp ); + styles_[(*i)] = tmp; + + /* old action/menu code + QAction *tmp = new QAction((*i),(*i),0, this, (*i)); + tmp->setToggleAction(true); + stylesgroup->add(tmp); + //tmp->addTo(styleMenu); + styles_[(*i)] = tmp; + */ + } + + // 2005-10-07 AF, Porting, replaced this + //QObject::connect(stylesgroup, SIGNAL(selected (QAction*)), this, SLOT(changeStyle(QAction*))); + connect( styleMenu, SIGNAL(triggered(QAction*)), this, SLOT(changeStyle(QAction*))); + + + // 2005-10-07 AF, Portin, Removed + //stylesgroup->setUsesDropDown(true); + //stylesgroup->setMenuText("&Styles"); + + + + // FONT + // ----------------------------------------------------- + // Code for createn the font menu + formatMenu->addSeparator(); + fontsgroup = new QActionGroup( this ); + fontMenu = formatMenu->addMenu( tr("&Font") ); + + QFontDatabase fontDatabase; + QStringList fonts = fontDatabase.families( QFontDatabase::Latin ); + for( int index = 0; index < fonts.count(); ++index ) + { + QAction *tmp = new QAction( fonts[index], this ); + tmp->setCheckable( true ); + fontMenu->addAction( tmp ); + fontsgroup->addAction( tmp ); + fonts_.insert( fonts[index], tmp ); + } + + connect( fontMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeFont(QAction*) )); + connect( fontMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateFontMenu() )); + + // ----------------------------------------------------- + // END: FONT + + + // FACE + // ----------------------------------------------------- + // Code for createn the face menu + faceMenu = formatMenu->addMenu( tr("Fa&ce") ); + + facePlain = new QAction( tr("&Plain"), this); + facePlain->setCheckable( false ); + facePlain->setStatusTip( tr("Set font face to Plain") ); + + faceBold = new QAction( tr("&Bold"), this); + faceBold->setShortcut( tr("Ctrl+B") ); + faceBold->setCheckable( true ); + faceBold->setStatusTip( tr("Set font face to Bold") ); + + faceItalic = new QAction( tr("&Italic"), this); + faceItalic->setShortcut( tr("Ctrl+I") ); + faceItalic->setCheckable( true ); + faceItalic->setStatusTip( tr("Set font face to Italic") ); + + faceUnderline = new QAction( tr("&Underline"), this); + faceUnderline->setShortcut( tr("Ctrl+U") ); + faceUnderline->setCheckable( true ); + faceUnderline->setStatusTip( tr("Set font face to Underline") ); + + + connect( faceMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateFontFaceMenu() )); + connect( faceMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeFontFace(QAction*) )); + + faceMenu->addAction( facePlain ); + faceMenu->addAction( faceBold ); + faceMenu->addAction( faceItalic ); + faceMenu->addAction( faceUnderline ); + + // ----------------------------------------------------- + // END: FONT + + + + // SIZE + // ----------------------------------------------------- + // Code for createn the size menu + + sizeMenu = formatMenu->addMenu( tr("Si&ze") ); + sizesgroup = new QActionGroup( this ); + + sizeSmaller = new QAction( tr("&Smaller"), this); + sizeSmaller->setShortcut( tr("Alt+-") ); + sizeSmaller->setCheckable( false ); + sizeSmaller->setStatusTip( tr("Set font size smaller") ); + + sizeLarger = new QAction( tr("&Larger"), this); + sizeLarger->setShortcut( tr("Alt+=") ); + sizeLarger->setCheckable( false ); + sizeLarger->setStatusTip( tr("Set font size larger") ); + + size8pt = new QAction( tr("8"), this); + size8pt->setCheckable( true ); + sizes_.insert( "8", size8pt ); + sizesgroup->addAction( size8pt ); + + size9pt = new QAction( tr("9"), this); + size9pt->setCheckable( true ); + sizes_.insert( "9", size9pt ); + sizesgroup->addAction( size9pt ); + + size10pt = new QAction( tr("10"), this); + size10pt->setCheckable( true ); + sizes_.insert( "10", size10pt ); + sizesgroup->addAction( size10pt ); + + size12pt = new QAction( tr("12"), this); + size12pt->setCheckable( true ); + sizes_.insert( "12", size12pt ); + sizesgroup->addAction( size12pt ); + + size14pt = new QAction( tr("14"), this); + size14pt->setCheckable( true ); + sizes_.insert( "14", size14pt ); + sizesgroup->addAction( size14pt ); + + size16pt = new QAction( tr("16"), this); + size16pt->setCheckable( true ); + sizes_.insert( "16", size16pt ); + sizesgroup->addAction( size16pt ); + + size18pt = new QAction( tr("18"), this); + size18pt->setCheckable( true ); + sizes_.insert( "18", size18pt ); + sizesgroup->addAction( size18pt ); + + size20pt = new QAction( tr("20"), this); + size20pt->setCheckable( true ); + sizes_.insert( "20", size20pt ); + sizesgroup->addAction( size20pt ); + + size24pt = new QAction( tr("24"), this); + size24pt->setCheckable( true ); + sizes_.insert( "24", size24pt ); + sizesgroup->addAction( size24pt ); + + size36pt = new QAction( tr("36"), this); + size36pt->setCheckable( true ); + sizes_.insert( "36", size36pt ); + sizesgroup->addAction( size36pt ); + + size72pt = new QAction( tr("72"), this); + size72pt->setCheckable( true ); + sizes_.insert( "72", size72pt ); + sizesgroup->addAction( size72pt ); + + sizeOther = new QAction( tr("&Other..."), this); + sizeOther->setCheckable( true ); + sizeOther->setStatusTip( tr("Select font size") ); + + + connect( sizeMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateFontSizeMenu() )); + connect( sizeMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeFontSize(QAction*) )); + + + sizeMenu->addAction( sizeSmaller ); + sizeMenu->addAction( sizeLarger ); + sizeMenu->addSeparator(); + sizeMenu->addAction( size8pt ); + sizeMenu->addAction( size9pt ); + sizeMenu->addAction( size10pt ); + sizeMenu->addAction( size12pt ); + sizeMenu->addAction( size14pt ); + sizeMenu->addAction( size16pt ); + sizeMenu->addAction( size18pt ); + sizeMenu->addAction( size20pt ); + sizeMenu->addAction( size24pt ); + sizeMenu->addAction( size36pt ); + sizeMenu->addAction( size72pt ); + sizeMenu->addSeparator(); + sizeMenu->addAction( sizeOther ); + + // ----------------------------------------------------- + // END: Size + + + + // STRETCH + // ----------------------------------------------------- + // Code for createn the stretch menu + + stretchMenu = formatMenu->addMenu( tr("S&tretch") ); + stretchsgroup = new QActionGroup( this ); + + stretchUltraCondensed = new QAction( tr("U<ra Condensed"), this); + stretchUltraCondensed->setCheckable( true ); + stretchUltraCondensed->setStatusTip( tr("Set font stretech to Ultra Condensed") ); + stretchs_.insert( QFont::UltraCondensed, stretchUltraCondensed ); + stretchsgroup->addAction( stretchUltraCondensed ); + + stretchExtraCondensed = new QAction( tr("E&xtra Condensed"), this); + stretchExtraCondensed->setCheckable( true ); + stretchExtraCondensed->setStatusTip( tr("Set font stretech to Extra Condensed") ); + stretchs_.insert( QFont::ExtraCondensed, stretchExtraCondensed ); + stretchsgroup->addAction( stretchExtraCondensed ); + + stretchCondensed = new QAction( tr("&Condensed"), this); + stretchCondensed->setCheckable( true ); + stretchCondensed->setStatusTip( tr("Set font stretech to Condensed") ); + stretchs_.insert( QFont::Condensed, stretchCondensed ); + stretchsgroup->addAction( stretchCondensed ); + + stretchSemiCondensed = new QAction( tr("S&emi Condensed"), this); + stretchSemiCondensed->setCheckable( true ); + stretchSemiCondensed->setStatusTip( tr("Set font stretech to Semi Condensed") ); + stretchs_.insert( QFont::SemiCondensed, stretchSemiCondensed ); + stretchsgroup->addAction( stretchSemiCondensed ); + + stretchUnstretched = new QAction( tr("&Unstretched"), this); + stretchUnstretched->setCheckable( true ); + stretchUnstretched->setStatusTip( tr("Set font stretech to Unstretched") ); + stretchs_.insert( QFont::Unstretched, stretchUnstretched ); + stretchsgroup->addAction( stretchUnstretched ); + + stretchSemiExpanded = new QAction( tr("&Semi Expanded"), this); + stretchSemiExpanded->setCheckable( true ); + stretchSemiExpanded->setStatusTip( tr("Set font stretech to Semi Expanded") ); + stretchs_.insert( QFont::SemiExpanded, stretchSemiExpanded ); + stretchsgroup->addAction( stretchSemiExpanded ); + + stretchExpanded = new QAction( tr("&Expanded"), this); + stretchExpanded->setCheckable( true ); + stretchExpanded->setStatusTip( tr("Set font stretech to Expanded") ); + stretchs_.insert( QFont::Expanded, stretchExpanded ); + stretchsgroup->addAction( stretchExpanded ); + + stretchExtraExpanded = new QAction( tr("Ex&tra Expanded"), this); + stretchExtraExpanded->setCheckable( true ); + stretchExtraExpanded->setStatusTip( tr("Set font stretech to Extra Expanded") ); + stretchs_.insert( QFont::ExtraExpanded, stretchExtraExpanded ); + stretchsgroup->addAction( stretchExtraExpanded ); + + stretchUltraExpanded = new QAction( tr("Ult&ra Expanded"), this); + stretchUltraExpanded->setCheckable( true ); + stretchUltraExpanded->setStatusTip( tr("Set font stretech to Ultra Expanded") ); + stretchs_.insert( QFont::UltraExpanded, stretchUltraExpanded ); + stretchsgroup->addAction( stretchUltraExpanded ); + + connect( stretchMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateFontStretchMenu() )); + connect( stretchMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeFontStretch(QAction*) )); + + + stretchMenu->addAction( stretchUltraCondensed ); + stretchMenu->addAction( stretchExtraCondensed ); + stretchMenu->addAction( stretchCondensed ); + stretchMenu->addAction( stretchSemiCondensed ); + stretchMenu->addSeparator(); + stretchMenu->addAction( stretchUnstretched ); + stretchMenu->addSeparator(); + stretchMenu->addAction( stretchSemiExpanded ); + stretchMenu->addAction( stretchExpanded ); + stretchMenu->addAction( stretchExtraExpanded ); + stretchMenu->addAction( stretchUltraExpanded ); + + // ----------------------------------------------------- + // END: Stretch + + + + // COLOR + // ----------------------------------------------------- + // Code for createn the color menu + colorMenu = formatMenu->addMenu( tr("&Color") ); + colorsgroup = new QActionGroup( this ); + + colorBlack = new QAction( tr("Blac&k"), this); + colorBlack->setCheckable( true ); + colorBlack->setStatusTip( tr("Set font color to Black") ); + colors_.insert( colorBlack, new QColor(0,0,0) ); + colorsgroup->addAction( colorBlack ); + + colorWhite = new QAction( tr("&White"), this); + colorWhite->setCheckable( true ); + colorWhite->setStatusTip( tr("Set font color to White") ); + colors_.insert( colorWhite, new QColor(255,255,255) ); + colorsgroup->addAction( colorWhite ); + + color10Gray = new QAction( tr("&10% Gray"), this); + color10Gray->setCheckable( true ); + color10Gray->setStatusTip( tr("Set font color to 10% Gray") ); + colors_.insert( color10Gray, new QColor(25,25,25) ); + colorsgroup->addAction( color10Gray ); + + color33Gray = new QAction( tr("&33% Gray"), this); + color33Gray->setCheckable( true ); + color33Gray->setStatusTip( tr("Set font color to 33% Gray") ); + colors_.insert( color33Gray, new QColor(85,85,85) ); + colorsgroup->addAction( color33Gray ); + + color50Gray = new QAction( tr("&50% Gray"), this); + color50Gray->setCheckable( true ); + color50Gray->setStatusTip( tr("Set font color to 50% Gray") ); + colors_.insert( color50Gray, new QColor(128,128,128) ); + colorsgroup->addAction( color50Gray ); + + color66Gray = new QAction( tr("&66% Gray"), this); + color66Gray->setCheckable( true ); + color66Gray->setStatusTip( tr("Set font color to 66% Gray") ); + colors_.insert( color66Gray, new QColor(170,170,170) ); + colorsgroup->addAction( color66Gray ); + + color90Gray = new QAction( tr("&90% Gray"), this); + color90Gray->setCheckable( true ); + color90Gray->setStatusTip( tr("Set font color to 90% Gray") ); + colors_.insert( color90Gray, new QColor(230,230,230) ); + colorsgroup->addAction( color90Gray ); + + colorRed = new QAction( tr("&Red"), this); + colorRed->setCheckable( true ); + colorRed->setStatusTip( tr("Set font color to Red") ); + colors_.insert( colorRed, new QColor(255,0,0) ); + colorsgroup->addAction( colorRed ); + + colorGreen = new QAction( tr("&Green"), this); + colorGreen->setCheckable( true ); + colorGreen->setStatusTip( tr("Set font color to Green") ); + colors_.insert( colorGreen, new QColor(0,255,0) ); + colorsgroup->addAction( colorGreen ); + + colorBlue = new QAction( tr("&Blue"), this); + colorBlue->setCheckable( true ); + colorBlue->setStatusTip( tr("Set font color to Blue") ); + colors_.insert( colorBlue, new QColor(0,0,255) ); + colorsgroup->addAction( colorBlue ); + + colorCyan = new QAction( tr("&Cyan"), this); + colorCyan->setCheckable( true ); + colorCyan->setStatusTip( tr("Set font color to Cyan") ); + colors_.insert( colorCyan, new QColor(0,255,255) ); + colorsgroup->addAction( colorCyan ); + + colorMagenta = new QAction( tr("&Magenta"), this); + colorMagenta->setCheckable( true ); + colorMagenta->setStatusTip( tr("Set font color to Magenta") ); + colors_.insert( colorMagenta, new QColor(255,0,255) ); + colorsgroup->addAction( colorMagenta ); + + colorYellow = new QAction( tr("&Yellow"), this); + colorYellow->setCheckable( true ); + colorYellow->setStatusTip( tr("Set font color to Yellow") ); + colors_.insert( colorYellow, new QColor(255,255,0) ); + colorsgroup->addAction( colorYellow ); + + colorOther = new QAction( tr("&Other..."), this); + colorOther->setCheckable( true ); + colorOther->setStatusTip( tr("Select font color") ); + + + connect( colorMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateFontColorMenu() )); + connect( colorMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeFontColor(QAction*) )); + + + colorMenu->addAction( colorBlack ); + colorMenu->addAction( colorWhite ); + colorMenu->addAction( color10Gray ); + colorMenu->addAction( color33Gray ); + colorMenu->addAction( color50Gray ); + colorMenu->addAction( color66Gray ); + colorMenu->addAction( color90Gray ); + colorMenu->addAction( colorRed ); + colorMenu->addAction( colorGreen ); + colorMenu->addAction( colorBlue ); + colorMenu->addAction( colorCyan ); + colorMenu->addAction( colorMagenta ); + colorMenu->addAction( colorYellow ); + colorMenu->addSeparator(); + colorMenu->addAction( colorOther ); + + // ----------------------------------------------------- + // END: Color + + + // Extra meny for choosing font from a dialog, because all fonts + // can't be displayed in the font menu + chooseFont = new QAction( tr("C&hoose Font..."), this); + chooseFont->setCheckable( false ); + chooseFont->setStatusTip( tr("Select font") ); + connect(chooseFont, SIGNAL(triggered()), this, SLOT(selectFont())); + formatMenu->addAction( chooseFont ); + + + // ALIGNMENT + // ----------------------------------------------------- + // Code for createn the alignment menus + formatMenu->addSeparator(); + + alignmentMenu = formatMenu->addMenu( tr("&Alignment") ); + alignmentsgroup = new QActionGroup( this ); + verticalAlignmentMenu = formatMenu->addMenu( tr("&Vertical Alignment") ); + verticalAlignmentsgroup = new QActionGroup( this ); + + alignmentLeft = new QAction( tr("&Left"), this); + alignmentLeft->setCheckable( true ); + alignmentLeft->setStatusTip( tr("Set text alignment to Left") ); + alignments_.insert( Qt::AlignLeft, alignmentLeft ); + alignmentsgroup->addAction( alignmentLeft ); + + alignmentRight = new QAction( tr("&Right"), this); + alignmentRight->setCheckable( true ); + alignmentRight->setStatusTip( tr("Set text alignment to Right") ); + alignments_.insert( Qt::AlignRight, alignmentRight ); + alignmentsgroup->addAction( alignmentRight ); + + alignmentCenter = new QAction( tr("&Center"), this); + alignmentCenter->setCheckable( true ); + alignmentCenter->setStatusTip( tr("Set text alignment to Center") ); + alignments_.insert( Qt::AlignHCenter, alignmentCenter ); + alignmentsgroup->addAction( alignmentCenter ); + + alignmentJustify = new QAction( tr("&Justify"), this); + alignmentJustify->setCheckable( true ); + alignmentJustify->setStatusTip( tr("Set text alignment to Justify") ); + alignments_.insert( Qt::AlignJustify, alignmentJustify ); + alignmentsgroup->addAction( alignmentJustify ); + + verticalNormal = new QAction( tr("&Normal/Baseline"), this); + verticalNormal->setCheckable( true ); + verticalNormal->setStatusTip( tr("Set vertical text alignment to Normal") ); + verticals_.insert( QTextCharFormat::AlignNormal, verticalNormal ); + verticalAlignmentsgroup->addAction( verticalNormal ); + + verticalSub = new QAction( tr("&Subscript"), this); + verticalSub->setCheckable( true ); + verticalSub->setStatusTip( tr("Set vertical text alignment to Subscript") ); + verticals_.insert( QTextCharFormat::AlignSubScript, verticalSub ); + verticalAlignmentsgroup->addAction( verticalSub ); + + verticalSuper = new QAction( tr("S&uperscript"), this); + verticalSuper->setCheckable( true ); + verticalSuper->setStatusTip( tr("Set vertical text alignment to Superscript") ); + verticals_.insert( QTextCharFormat::AlignSuperScript, verticalSuper ); + verticalAlignmentsgroup->addAction( verticalSuper ); + + connect( alignmentMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateTextAlignmentMenu() )); + connect( alignmentMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeTextAlignment(QAction*) )); + connect( verticalAlignmentMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateVerticalAlignmentMenu() )); + connect( verticalAlignmentMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeVerticalAlignment(QAction*) )); + + + alignmentMenu->addAction( alignmentLeft ); + alignmentMenu->addAction( alignmentRight ); + alignmentMenu->addAction( alignmentCenter ); + alignmentMenu->addAction( alignmentJustify ); + verticalAlignmentMenu->addAction( verticalNormal ); + verticalAlignmentMenu->addAction( verticalSub ); + verticalAlignmentMenu->addAction( verticalSuper ); + + // ----------------------------------------------------- + // END: Text Alignment + + + // BORDER + // ----------------------------------------------------- + // Code for createn the border menu + formatMenu->addSeparator(); + borderMenu = formatMenu->addMenu( tr("&Border") ); + bordersgroup = new QActionGroup( this ); + + int borderSizes[] = { 0,1,2,3,4,5,6,7,8,9,10 }; + for( int i = 0; i < sizeof(borderSizes)/sizeof(int); i++ ) + { + QString name; + name.setNum( borderSizes[i] ); + QAction *tmp = new QAction( name, this ); + tmp->setCheckable( true ); + borders_.insert( borderSizes[i], tmp ); + borderMenu->addAction( tmp ); + bordersgroup->addAction( tmp ); + } + + + connect( borderMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateBorderMenu() )); + connect( borderMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeBorder(QAction*) )); + + + borderMenu->addSeparator(); + borderOther = new QAction( "&Other...", this ); + borderOther->setCheckable( true ); + borderMenu->addAction( borderOther ); + + // ----------------------------------------------------- + // END: Border + + + // MARGIN + // ----------------------------------------------------- + // Code for createn the margin menu + marginMenu = formatMenu->addMenu( tr("&Margin") ); + marginsgroup = new QActionGroup( this ); + + int marginSizes[] = { 0,1,2,3,4,5,6,7,8,9,10,15,20,25,30 }; + for( int i = 0; i < sizeof(marginSizes)/sizeof(int); i++ ) + { + QString name; + name.setNum( marginSizes[i] ); + QAction *tmp = new QAction( name, this ); + tmp->setCheckable( true ); + margins_.insert( marginSizes[i], tmp ); + marginMenu->addAction( tmp ); + marginsgroup->addAction( tmp ); + } + + + connect( marginMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateMarginMenu() )); + connect( marginMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changeMargin(QAction*) )); + + + marginMenu->addSeparator(); + marginOther = new QAction( "&Other...", this ); + marginOther->setCheckable( true ); + marginMenu->addAction( marginOther ); + + // ----------------------------------------------------- + // END: Margin + + + // PADDING + // ----------------------------------------------------- + // Code for createn the padding menu + paddingMenu = formatMenu->addMenu( tr("&Padding") ); + paddingsgroup = new QActionGroup( this ); + + int paddingSizes[] = { 0,2,4,6,8,10,15 }; + for( int i = 0; i < sizeof(paddingSizes)/sizeof(int); i++ ) + { + QString name; + name.setNum( paddingSizes[i] ); + QAction *tmp = new QAction( name, this ); + tmp->setCheckable( true ); + paddings_.insert( paddingSizes[i], tmp ); + paddingMenu->addAction( tmp ); + paddingsgroup->addAction( tmp ); + } + + + connect( paddingMenu, SIGNAL( aboutToShow() ), + this, SLOT( updatePaddingMenu() )); + connect( paddingMenu, SIGNAL( triggered(QAction*) ), + this, SLOT( changePadding(QAction*) )); + + + paddingMenu->addSeparator(); + paddingOther = new QAction( "&Other...", this ); + paddingOther->setCheckable( true ); + paddingMenu->addAction( paddingOther ); + + // ----------------------------------------------------- + // END: Padding + + + /* Old menu code //AF + menuBar()->insertItem("&Format", formatMenu); + stylesgroup->addTo(formatMenu); + groupAction->addTo(formatMenu); + inputAction->addTo(formatMenu); + formatMenu->insertSeparator(1); + */ + + connect(formatMenu, SIGNAL(aboutToShow()), + this, SLOT(updateStyleMenu())); + connect( formatMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateMenus() )); + + formatMenu->addSeparator(); + formatMenu->addAction(toolBar->toggleViewAction()); + + +// showToolBarAction = new QAction(formatMenu, "Show toolbar", true); +// connect(showToolBarAction, SIGNAL(toggled(bool)), toolBar, SLOT(setVisible(bool))); +// connect(toolBar->toggleViewAction(), SIGNAL(toggled(bool)), showToolBarAction + + } + + /*! + * \author Anders Fernström + * \date 2005-11-18 + * + * \brief Method for creating insert nemu. + */ + void NotebookWindow::createInsertMenu() + { + // IMAGE + insertImageAction = new QAction( tr("&Image"), this ); + insertImageAction->setShortcut( tr("Ctrl+Shift+M") ); + insertImageAction->setStatusTip( tr("Insert a image into the cell") ); + connect( insertImageAction, SIGNAL( triggered() ), + this, SLOT( insertImage() )); + insertImageAction->setIcon(QIcon(":/Resources/toolbarIcons/image.png")); + toolBar->addAction(insertImageAction); + + // LINK + insertLinkAction = new QAction( tr("&Link"), this ); + insertLinkAction->setShortcut( tr("Ctrl+Shift+L") ); + insertLinkAction->setStatusTip( tr("Insert a link to the selected text") ); + connect( insertLinkAction, SIGNAL( triggered() ), + this, SLOT( insertLink() )); + insertLinkAction->setIcon(QIcon(":/Resources/toolbarIcons/text_under.png")); + toolBar->addAction(insertLinkAction); + + toolBar->addSeparator(); + + //INDENT + indentAction = new QAction(tr("Indent"), this); + indentAction->setStatusTip(tr("Indent the code in the selected cell")); + indentAction->setIcon(QIcon(":/Resources/toolbarIcons/text_right.png")); + connect(indentAction, SIGNAL(triggered()), this, SLOT(indent())); + + + QToolButton * b = new QToolButton; + b->setDefaultAction(indentAction); + indentMenu = new QMenu(this); + autoIndentAction = new QAction("Autoindent", this); + autoIndentAction->setStatusTip(tr("Tries to move the cursor to the right position when return is pressed")); + autoIndentAction->setCheckable(true); +// autoIndentAction->setChecked(true); + + b->hide(); //Disable indentation button + + QSettings s("PELAB", "OMNotebook"); + autoIndentAction->setChecked(s.value("AutoIndent", true).toBool()); + setAutoIndent(autoIndentAction->isChecked()); + + connect(autoIndentAction, SIGNAL(toggled(bool)), this, SLOT(setAutoIndent(bool))); + + + indentMenu->addAction(autoIndentAction); + b->setMenu(indentMenu); + b->setPopupMode(QToolButton::MenuButtonPopup); + toolBar->addWidget(b); + + + //EVAL + + evalAction = new QAction(tr("Evaluate"), this); + evalAction->setStatusTip(tr("Evaluate the selected cell")); + evalAction->setIcon(QIcon(":/Resources/toolbarIcons/apply.png")); + connect(evalAction, SIGNAL(triggered()), this, SLOT(eval())); + toolBar->addAction(evalAction); + + // MENU + insertMenu = menuBar()->addMenu( tr("&Insert") ); + insertMenu->addAction( insertImageAction ); + insertMenu->addAction( insertLinkAction ); + + connect( insertMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateMenus() )); + } + + /*! + * \author Anders Fernström + * \date 2006-01-27 + * + * \brief Method for creating window nemu. + */ + void NotebookWindow::createWindowMenu() + { + windowMenu = menuBar()->addMenu( tr("&Window") ); + + connect( windowMenu, SIGNAL( triggered(QAction *) ), + this, SLOT( changeWindow(QAction *) )); + connect( windowMenu, SIGNAL( aboutToShow() ), + this, SLOT( updateWindowMenu() )); + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 (update) + * + * \brief Method for creating about nemu. + * + * 2005-10-07 AF, Remade the function when porting to QT4. + * 2006-02-03 AF, added help action. + */ + void NotebookWindow::createAboutMenu() + { + // 2005-10-07 AF, Porting, replaced this + //QAction *aboutAction = new QAction("About", "&About", 0, this, "about"); + //QObject::connect(aboutAction, SIGNAL(activated()), this, SLOT(aboutQTNotebook())); + aboutAction = new QAction( tr("&About OMNotebook"), this ); + aboutAction->setStatusTip( tr("Display OMNotebook's About dialog") ); + connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutQTNotebook())); + + // 2006-02-03 AF, Added a help action + helpAction = new QAction( tr("&Help Text"), this ); + helpAction->setShortcut( tr("F1") ); + helpAction->setStatusTip( tr("Open help document") ); + connect( helpAction, SIGNAL( triggered() ), + this, SLOT( helpText() )); + + // 2006-02-21 AF, Added a about qt action + aboutQtAction = new QAction( tr("About &Qt"), this ); + aboutQtAction->setStatusTip( tr("Display information about Qt") ); + connect( aboutQtAction, SIGNAL( triggered() ), + this, SLOT( aboutQT() )); + + + // 2005-10-07 AF, Porting, new code for creating menu + aboutMenu = menuBar()->addMenu( tr("&Help") ); + aboutMenu->addAction( aboutAction ); + aboutMenu->addAction( aboutQtAction ); + aboutMenu->addSeparator(); + aboutMenu->addAction( helpAction ); + + /* Old menu code //AF + aboutMenu = new Q3PopupMenu(this); + menuBar()->insertItem("&Help", aboutMenu); + aboutAction->addTo(aboutMenu); + */ + } + + /*! + * \author Anders Fernström + * \date 2005-11-11 + * + * \brief Check if the currentCell is editable + */ + bool NotebookWindow::cellEditable() + { + return subject_->getCursor()->currentCell()->isEditable(); + } + + /*! + * \author Anders Fernström + * \date 2006-02-14 + * + * \brief eval all selected cell + */ + void NotebookWindow::evalCells() + { + application()->commandCenter()->executeCommand( + new EvalSelectedCells( subject_ )); + } + + /*! + * \author Ingemar Axelsson + */ /* - void NotebookWindow::createSavingTimer() - { - //start a saving timer. - savingTimer_ = new QTimer(); - savingTimer_->start(30000); - - connect(savingTimer_, SIGNAL(timeout()), - this, SLOT(save())); - } + void NotebookWindow::createSavingTimer() + { + //start a saving timer. + savingTimer_ = new QTimer(); + savingTimer_->start(30000); + + connect(savingTimer_, SIGNAL(timeout()), + this, SLOT(save())); + } */ - /*! - * \author Anders Fernström - * \date 2005-11-07 - * \date 2005-11-15 (update) - * - * \brief Method for enabling/disabling the menus depended on what have - * been selected in the mainwindow - * - * 2005-11-15 AF, implemented the function - */ - void NotebookWindow::updateMenus() - { - bool editable = false; - - - if( cellEditable() || - (subject_->getCursor()->currentCell()->hasChilds() && - subject_->getCursor()->currentCell()->isClosed() && - subject_->getCursor()->currentCell()->child()->isEditable()) ) - { - editable = true; - } - - styleMenu->setEnabled( editable ); - fontMenu->setEnabled( editable ); - faceMenu->setEnabled( editable ); - sizeMenu->setEnabled( editable ); - stretchMenu->setEnabled( editable ); - colorMenu->setEnabled( editable ); - alignmentMenu->setEnabled( editable ); - verticalAlignmentMenu->setEnabled( editable ); - borderMenu->setEnabled( editable ); - marginMenu->setEnabled( editable ); - paddingMenu->setEnabled( editable ); - - chooseFont->setEnabled( editable ); - insertImageAction->setEnabled( editable ); - insertLinkAction->setEnabled( editable ); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-11-02 (update) - * - * \brief Method for unpdating the style menu - * - * 2005-10-28 AF, changed style from QString to CellStyle. - * 2005-11-02 AF, changed from '->toggle()' to '->setChevked(true)' - */ - void NotebookWindow::updateStyleMenu() - { - CellStyle style = *subject_->getCursor()->currentCell()->style(); - map::iterator cs = styles_.find(style.name()); - - if(cs != styles_.end()) - { - (*cs).second->setChecked( true ); - } - else - { - qDebug("No styles found"); - cs = styles_.begin(); - for(;cs != styles_.end(); ++cs) - { - (*cs).second->setChecked(false); - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-02 - * \date 2006-04-27 (update) - * - * \brief Method for updating the edit menu - * - * 2006-02-03 AF, check if undo/redo is available. - * 2006-04-27 AF, check if copied cells exsists. - */ - void NotebookWindow::updateEditMenu() - { - QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); - if( editor ) - { - // undo - if( editor->document()->isUndoAvailable() ) - undoAction->setEnabled( true ); - else - undoAction->setEnabled( false ); - - // redo - if( editor->document()->isRedoAvailable() ) - redoAction->setEnabled( true ); - else - redoAction->setEnabled( false ); - - // cut & copy (specialfall för input) - Cell *cell = document()->getCursor()->currentCell(); - if( cell ) - { - QTextCursor in_cursor; - - if( typeid(InputCell) == typeid(*cell) ) - { - InputCell *inputcell = dynamic_cast(cell); - if( inputcell->textEditOutput()->hasFocus() && - inputcell->isEvaluated() ) - { - - in_cursor = inputcell->textEditOutput()->textCursor(); - } - else - { - in_cursor = inputcell->textEdit()->textCursor(); - } - } - else if( typeid(GraphCell) == typeid(*cell) ) //fjass - { - GraphCell *graphcell = dynamic_cast(cell); - if( graphcell->textEditOutput()->hasFocus() && - graphcell->isEvaluated() ) - { - - in_cursor = graphcell->textEditOutput()->textCursor(); - } - else - { - in_cursor = graphcell->textEdit()->textCursor(); - - - } - } - - else - { - in_cursor = editor->textCursor(); - } - - if( in_cursor.hasSelection() || - subject_->getSelection().size() > 0 ) - { - cutAction->setEnabled( true ); - copyAction->setEnabled( true ); - } - else - { - cutAction->setEnabled( false ); - copyAction->setEnabled( false ); - } - } - else - { - cutAction->setEnabled( false ); - copyAction->setEnabled( false ); - } - - // paste - if( !qApp->clipboard()->text().isEmpty() || - application()->pasteboard().size() > 0 ) - pasteAction->setEnabled( true ); - else - pasteAction->setEnabled( false ); - } - else - { - undoAction->setEnabled( false ); - redoAction->setEnabled( false ); - cutAction->setEnabled( false ); - copyAction->setEnabled( false ); - pasteAction->setEnabled( false ); - } - - showExprAction->setChecked( subject_->getCursor()->currentCell()->isViewExpression() ); - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * \date 2006-04-26 (update) - * - * \brief Method for updating the cell menu - * - * 2006-04-26 AF, update UNGROUP, SLIT CELL - */ - void NotebookWindow::updateCellMenu() - { - Cell *cell = subject_->getCursor()->currentCell(); - - // GROUPCELL & DELETE - if( cell ) - { - if( cell->treeView()->isHidden() ) - { - groupAction->setEnabled( false ); - deleteCellAction->setEnabled( false ); - } - else - { - groupAction->setEnabled( true ); - deleteCellAction->setEnabled( true ); - } - } - else - { - groupAction->setEnabled( false ); - deleteCellAction->setEnabled( false ); - } - - // UNGROUP - if( subject_->getSelection().size() > 0 ) - ungroupCellAction->setEnabled( true ); - else - ungroupCellAction->setEnabled( false ); - - // SLIT CELL - if( cell ) - { - if( typeid( *cell ) == typeid( TextCell ) || - typeid( *cell ) == typeid( InputCell ) ) - { - splitCellAction->setEnabled( true ); - } - else - splitCellAction->setEnabled( false ); - } - else - splitCellAction->setEnabled( false ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Method for updating the font menu - */ - void NotebookWindow::updateFontMenu() - { - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - QString family = cursor.charFormat().fontFamily(); - if( fonts_.contains( family )) - { - fonts_[family]->setChecked( true ); - } - else - { - cout << "No font found" << endl; - QHash::iterator f_iter = fonts_.begin(); - while( f_iter != fonts_.end() ) - { - f_iter.value()->setChecked( false ); - ++f_iter; - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Method for updating the face menu - */ - void NotebookWindow::updateFontFaceMenu() - { - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - if( cursor.charFormat().fontWeight() > QFont::Normal ) - faceBold->setChecked( true ); - else - faceBold->setChecked( false ); - - if( cursor.charFormat().fontItalic() ) - faceItalic->setChecked( true ); - else - faceItalic->setChecked( false ); - - if( cursor.charFormat().fontUnderline() ) - faceUnderline->setChecked( true ); - else - faceUnderline->setChecked( false ); - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-04 - * - * \brief Method for updating the size menu - */ - void NotebookWindow::updateFontSizeMenu() - { - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - int size = cursor.charFormat().font().pointSize(); - if( size > 0 ) - { - QString txt; - txt.setNum( size ); - - if( sizes_.contains( txt )) - { - sizes_[txt]->setChecked( true ); - sizeOther->setChecked( false ); - } - else - { - cout << "No size found" << endl; - sizeOther->setChecked( true ); - - QHash::iterator s_iter = sizes_.begin(); - while( s_iter != sizes_.end() ) - { - s_iter.value()->setChecked( false ); - ++s_iter; - } - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-04 - * - * \brief Method for updating the stretch menu - */ - void NotebookWindow::updateFontStretchMenu() - { - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - int stretch = cursor.charFormat().font().stretch(); - if( stretchs_.contains( stretch )) - stretchs_[stretch]->setChecked( true ); - else - { - cout << "No stretch found" << endl; - QHash::iterator s_iter = stretchs_.begin(); - while( s_iter != stretchs_.end() ) - { - s_iter.value()->setChecked( false ); - ++s_iter; - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for updating the color menu - */ - void NotebookWindow::updateFontColorMenu() - { - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - QColor color = cursor.charFormat().foreground().color(); - - QHash::iterator c_iter = colors_.begin(); - while( c_iter != colors_.end() ) - { - if( (*c_iter.value()) == color ) - { - c_iter.key()->setChecked( true ); - colorOther->setChecked( false ); - break; - } - else - c_iter.key()->setChecked( false ); - - ++c_iter; - } - - - if( c_iter == colors_.end() ) - colorOther->setChecked( true ); - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for updating the alignment menu - */ - void NotebookWindow::updateTextAlignmentMenu() - { - QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); - - if( editor ) - { - int alignment = editor->alignment(); - if( alignments_.contains( alignment )) - alignments_[alignment]->setChecked( true ); - else - { - cout << "No alignment found" << endl; - QHash::iterator a_iter = alignments_.begin(); - while( a_iter != alignments_.end() ) - { - a_iter.value()->setChecked( false ); - ++a_iter; - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for updating the vertical alignment menu - */ - void NotebookWindow::updateVerticalAlignmentMenu() - { - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - int alignment = cursor.charFormat().verticalAlignment(); - if( verticals_.contains( alignment )) - verticals_[alignment]->setChecked( true ); - else - { - cout << "No vertical alignment found" << endl; - QHash::iterator v_iter = verticals_.begin(); - while( v_iter != verticals_.end() ) - { - v_iter.value()->setChecked( false ); - ++v_iter; - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for updating the border menu - */ - void NotebookWindow::updateBorderMenu() - { - QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); - - if( editor ) - { - int border = editor->document()->rootFrame()->frameFormat().border(); - if( borders_.contains( border )) - { - borders_[border]->setChecked( true ); - borderOther->setChecked( false ); - } - else - { - cout << "No border found" << endl; - borderOther->setChecked( true ); - - QHash::iterator b_iter = borders_.begin(); - while( b_iter != borders_.end() ) - { - b_iter.value()->setChecked( false ); - ++b_iter; - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for updating the margin menu - */ - void NotebookWindow::updateMarginMenu() - { - QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); - - if( editor ) - { - int margin = editor->document()->rootFrame()->frameFormat().margin(); - if( margins_.contains( margin )) - { - margins_[margin]->setChecked( true ); - marginOther->setChecked( false ); - } - else - { - cout << "No margin found" << endl; - marginOther->setChecked( true ); - - QHash::iterator m_iter = margins_.begin(); - while( m_iter != margins_.end() ) - { - m_iter.value()->setChecked( false ); - ++m_iter; - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for updating the padding menu - */ - void NotebookWindow::updatePaddingMenu() - { - QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); - - if( editor ) - { - int padding = editor->document()->rootFrame()->frameFormat().padding(); - if( paddings_.contains( padding )) - { - paddings_[padding]->setChecked( true ); - paddingOther->setChecked( false ); - } - else - { - cout << "No padding found" << endl; - paddingOther->setChecked( true ); - - QHash::iterator p_iter = paddings_.begin(); - while( p_iter != paddings_.end() ) - { - p_iter.value()->setChecked( false ); - ++p_iter; - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-27 - * - * \brief Method for updating the window menu - */ - void NotebookWindow::updateWindowMenu() - { - // remove old windows - windows_.clear(); - windowMenu->clear(); - - // add new menu items - vector windowViews = application()->documentViewList(); - vector::iterator v_iter = windowViews.begin(); - while( v_iter != windowViews.end() ) - { - QString title = (*v_iter)->windowTitle(); - title.remove( "OMNotebook: " ); - - QAction *action = new QAction( title, windowMenu ); - windows_[action] = (*v_iter); - windowMenu->addAction( action ); - ++v_iter; - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-17 - * - * \brief Method for updateing the window title - */ - void NotebookWindow::updateWindowTitle() - { - // QT functionality to stripp the filepath and only keep - // the filename. - QString title = QFileInfo( subject_->getFilename() ).fileName(); - title.remove( "\n" ); - - // if no name, set name to '(untitled)' - if( title.isEmpty() ) - title = "(untitled)"; - - title = QString( "OMNotebook: " ) + title; - - if( subject_->hasChanged() ) - title.append( "*" ); - - setWindowTitle( title ); - } - - /*! - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief Method for updateing the chapter counters - */ - void NotebookWindow::updateChapterCounters() - { - application()->commandCenter()->executeCommand( - new UpdateChapterCounters( subject_ )); - } - - /*! - * \author Anders Fernström - * \date 2006-02-10 - * - * \brief Set the status message to msg, if msg is empty the default - * status message 'Ready' is set. - * - * \param msg A QString containing the status message - */ - void NotebookWindow::setStatusMessage( QString msg ) - { - if( msg.isEmpty() ) - statusBar()->showMessage("Ready"); - else - statusBar()->showMessage( msg ); - } - - void NotebookWindow::setPosition(int r, int c) - { - posIndicator->setText(QString("Ln %1, Col %2").arg(r).arg(c)); - } - - void NotebookWindow::setState(QString s) - { - stateIndicator->setText(s); - } - - void NotebookWindow::setStatusMenu(QList l) - { - QList a = stateIndicator->actions(); - qDeleteAll(a.begin(), a.end()); - - if(!l.size()) - stateIndicator->setContextMenuPolicy(Qt::NoContextMenu); - else - { - stateIndicator->setContextMenuPolicy(Qt::ActionsContextMenu); - stateIndicator->addActions(l); - } - - } - /*! - * \author Anders Fernström - * \date 2006-04-27 - * - * \brief handles forwarded actions - */ - void NotebookWindow::forwardedAction( int action ) - { - - switch( action ) - { - case 1: //COPY - copyEdit(); - break; - case 2: //CUT - cutEdit(); - break; - case 3: //PASTE - pasteEdit(); - break; - default: - break; - } - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * - */ - void NotebookWindow::keyPressEvent(QKeyEvent *event) - { - // 2006-01-30 AF, check if 'Alt+Enter' - if( event->modifiers() == Qt::AltModifier ) - { - if( event->key() == Qt::Key_Enter || - event->key() == Qt::Key_Return ) - { - createNewCell(); - } - else - QMainWindow::keyPressEvent(event); - } - // 2006-02-14 AF, check id 'Shift+Enter' - else if( event->modifiers() == Qt::ShiftModifier && - ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )) - { - evalCells(); - } - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-11-22 (update) - * - * \brief Method for catching some keyevent, and given them - * new functionality - * - * 2005-11-22 AF, Added support for deleting cells with 'DEL' - * key. - */ - void NotebookWindow::keyReleaseEvent(QKeyEvent *event) - { - // if Ctrl is pressed - if(event->modifiers() == Qt::ControlModifier) - { - if(event->key() == Qt::Key_Up) - { - moveCursorUp(); - event->accept(); - } - else if(event->key() == Qt::Key_Down) - { - moveCursorDown(); - event->accept(); - } - else - QMainWindow::keyReleaseEvent(event); - } - else - { - // 2005-11-22 AF, Support for deleting cells with 'DEL' key. - if( event->key() == Qt::Key_Delete ) - { - vector cells = subject_->getSelection(); - if( !cells.empty() ) - { - subject_->cursorDeleteCell(); - event->setAccepted( true ); - - updateChapterCounters(); - } - else - QMainWindow::keyReleaseEvent(event); - } - else - QMainWindow::keyReleaseEvent(event); - } - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * - * \todo Fix the code, when the window dosen't have any file open, - * the command should create the new document, not this function //AF - */ - void NotebookWindow::newFile() - { - /* - application()->commandCenter()->executeCommand(new NewFileCommand()); - - closeFile(); - - createSavingTimer(); - - subject_ = new CellDocument(this); - - connect(subject_, SIGNAL(cursorChanged()), - this, SLOT(setSelectedStyle())); - - setCentralWidget(subject_); - - subject_->show(); - */ - - // AF - if( subject_->isOpen() ) - { - // a file is open, open a new window with the new file //AF - application()->commandCenter()->executeCommand(new OpenFileCommand(QString::null)); - } - else - { - if(subject_->hasChanged()) - { - int res = QMessageBox::question(this, QString("Save document?"), QString("The document has been modified. Do you want to save the changes?"), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel); - if(res == QMessageBox::Yes) - { - - save(); - if(subject_->getFilename().isNull()) - return; - } - else if(res == QMessageBox::Cancel) - return; - } - - subject_ = new CellDocument(app_, QString::null); - dynamic_cast(subject_)->autoIndent = autoIndentAction->isChecked(); - subject_->executeCommand(new NewFileCommand()); - subject_->attach(this); - - update(); - updateWindowTitle(); - } - } - - void NotebookWindow::updateRecentFiles(QString filename) - { - QSettings s("PELAB", "OMNotebook"); - QStringList tmpLst; - QString tmp; - for(int i = 0; i < 4; ++i) - { - if((tmp = s.value(QString("Recent") + QString(i), QString()).toString()) != QString()) - tmpLst.push_back(tmp); - else - break; - } - - if(tmpLst.indexOf(filename) != -1) - tmpLst.move(tmpLst.indexOf(filename), 0); - else - tmpLst.push_front(filename); - - for(int i = 0; i < 4 && i < tmpLst.size(); ++i) - s.setValue(QString("Recent") + QString(i), tmpLst[i]); - - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * - * \brief Open a file. Shows a file dialog. - */ - void NotebookWindow::openFile(const QString filename) - { - try - { - //Open a new document - if(filename.isEmpty()) - { - //Show a dialog for choosing a file. - filename_ = QFileDialog::getOpenFileName( - this, - "OMNotebook -- File Open", - openDir_, - "Notebooks (*.onb *.onbz *.nb)" ); - } - else - { - filename_ = filename; - } - - if(!filename_.isEmpty()) - { - // 2006-03-01 AF, Update openDir_ - openDir_ = QFileInfo( filename_ ).absolutePath(); - - - updateRecentFiles(filename_); - - - if(subject_->isOpen()) - application()->commandCenter()->executeCommand(new OpenFileCommand(filename_)); - else - { - subject_ = new CellDocument(app_, QString::null); - - subject_->executeCommand(new OpenFileCommand(filename_)); - subject_->attach(this); - - } - } - else - { - //Cancel pushed. Do nothing - } - } - catch(exception &e) - { - QString msg = QString("In OpenFile(), Exception: \n") + e.what(); - QMessageBox::warning( 0, "Warning", msg, "OK" ); - openFile(); - } - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * - */ - void NotebookWindow::closeFile() - { - // TODO: the function isn't used correctly, this funciton - // should also close the window, if it isn't the last window - //subject_->executeCommand(new CloseFileCommand()); - - close(); - - //application()-> - - // if(savingTimer_) - // { - // savingTimer_->stop(); - // delete savingTimer_; - // } - //delete subject_; - } - - /*! - * \author Anders Fernström - * \date 2006-01-19 - * - * \brief Reimplemented closeEvent so all close event are handled - * correctly. If the document is unsaved, the applicaiton will ask - * the user if he/she wants to save before closing the document. - */ - void NotebookWindow::closeEvent( QCloseEvent *event ) - { - QString filename = QFileInfo( subject_->getFilename() ).fileName(); - filename.remove( "\n" ); - - // if no name, set name to '(untitled)' - if( filename.isEmpty() ) - filename = "(untitled)"; - - // if the document have been changed, ask if the - // user wants to save the document - while( subject_->hasChanged() ) - { - int res = QMessageBox::question(this, "Document is unsaved", QString("The document \"") + filename + QString("\" is unsaved, do you want to save the document?"), - QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel); + /*! + * \author Anders Fernström + * \date 2005-11-07 + * \date 2005-11-15 (update) + * + * \brief Method for enabling/disabling the menus depended on what have + * been selected in the mainwindow + * + * 2005-11-15 AF, implemented the function + */ + void NotebookWindow::updateMenus() + { + bool editable = false; + + + if( cellEditable() || + (subject_->getCursor()->currentCell()->hasChilds() && + subject_->getCursor()->currentCell()->isClosed() && + subject_->getCursor()->currentCell()->child()->isEditable()) ) + { + editable = true; + } + + styleMenu->setEnabled( editable ); + fontMenu->setEnabled( editable ); + faceMenu->setEnabled( editable ); + sizeMenu->setEnabled( editable ); + stretchMenu->setEnabled( editable ); + colorMenu->setEnabled( editable ); + alignmentMenu->setEnabled( editable ); + verticalAlignmentMenu->setEnabled( editable ); + borderMenu->setEnabled( editable ); + marginMenu->setEnabled( editable ); + paddingMenu->setEnabled( editable ); + + chooseFont->setEnabled( editable ); + insertImageAction->setEnabled( editable ); + insertLinkAction->setEnabled( editable ); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-11-02 (update) + * + * \brief Method for unpdating the style menu + * + * 2005-10-28 AF, changed style from QString to CellStyle. + * 2005-11-02 AF, changed from '->toggle()' to '->setChevked(true)' + */ + void NotebookWindow::updateStyleMenu() + { + CellStyle style = *subject_->getCursor()->currentCell()->style(); + map::iterator cs = styles_.find(style.name()); + + if(cs != styles_.end()) + { + (*cs).second->setChecked( true ); + } + else + { + qDebug("No styles found"); + cs = styles_.begin(); + for(;cs != styles_.end(); ++cs) + { + (*cs).second->setChecked(false); + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-02 + * \date 2006-04-27 (update) + * + * \brief Method for updating the edit menu + * + * 2006-02-03 AF, check if undo/redo is available. + * 2006-04-27 AF, check if copied cells exsists. + */ + void NotebookWindow::updateEditMenu() + { + QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); + if( editor ) + { + // undo + if( editor->document()->isUndoAvailable() ) + undoAction->setEnabled( true ); + else + undoAction->setEnabled( false ); + + // redo + if( editor->document()->isRedoAvailable() ) + redoAction->setEnabled( true ); + else + redoAction->setEnabled( false ); + + // cut & copy (specialfall för input) + Cell *cell = document()->getCursor()->currentCell(); + if( cell ) + { + QTextCursor in_cursor; + + if( typeid(InputCell) == typeid(*cell) ) + { + InputCell *inputcell = dynamic_cast(cell); + if( inputcell->textEditOutput()->hasFocus() && + inputcell->isEvaluated() ) + { + + in_cursor = inputcell->textEditOutput()->textCursor(); + } + else + { + in_cursor = inputcell->textEdit()->textCursor(); + } + } + else if( typeid(GraphCell) == typeid(*cell) ) //fjass + { + GraphCell *graphcell = dynamic_cast(cell); + if( graphcell->textEditOutput()->hasFocus() && + graphcell->isEvaluated() ) + { + + in_cursor = graphcell->textEditOutput()->textCursor(); + } + else + { + in_cursor = graphcell->textEdit()->textCursor(); + + + } + } + + else + { + in_cursor = editor->textCursor(); + } + + if( in_cursor.hasSelection() || + subject_->getSelection().size() > 0 ) + { + cutAction->setEnabled( true ); + copyAction->setEnabled( true ); + } + else + { + cutAction->setEnabled( false ); + copyAction->setEnabled( false ); + } + } + else + { + cutAction->setEnabled( false ); + copyAction->setEnabled( false ); + } + + // paste + if( !qApp->clipboard()->text().isEmpty() || + application()->pasteboard().size() > 0 ) + pasteAction->setEnabled( true ); + else + pasteAction->setEnabled( false ); + } + else + { + undoAction->setEnabled( false ); + redoAction->setEnabled( false ); + cutAction->setEnabled( false ); + copyAction->setEnabled( false ); + pasteAction->setEnabled( false ); + } + + showExprAction->setChecked( subject_->getCursor()->currentCell()->isViewExpression() ); + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * \date 2006-04-26 (update) + * + * \brief Method for updating the cell menu + * + * 2006-04-26 AF, update UNGROUP, SLIT CELL + */ + void NotebookWindow::updateCellMenu() + { + Cell *cell = subject_->getCursor()->currentCell(); + + // GROUPCELL & DELETE + if( cell ) + { + if( cell->treeView()->isHidden() ) + { + groupAction->setEnabled( false ); + deleteCellAction->setEnabled( false ); + } + else + { + groupAction->setEnabled( true ); + deleteCellAction->setEnabled( true ); + } + } + else + { + groupAction->setEnabled( false ); + deleteCellAction->setEnabled( false ); + } + + // UNGROUP + if( subject_->getSelection().size() > 0 ) + ungroupCellAction->setEnabled( true ); + else + ungroupCellAction->setEnabled( false ); + + // SLIT CELL + if( cell ) + { + if( typeid( *cell ) == typeid( TextCell ) || + typeid( *cell ) == typeid( InputCell ) ) + { + splitCellAction->setEnabled( true ); + } + else + splitCellAction->setEnabled( false ); + } + else + splitCellAction->setEnabled( false ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Method for updating the font menu + */ + void NotebookWindow::updateFontMenu() + { + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + QString family = cursor.charFormat().fontFamily(); + if( fonts_.contains( family )) + { + fonts_[family]->setChecked( true ); + } + else + { + cout << "No font found" << endl; + QHash::iterator f_iter = fonts_.begin(); + while( f_iter != fonts_.end() ) + { + f_iter.value()->setChecked( false ); + ++f_iter; + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Method for updating the face menu + */ + void NotebookWindow::updateFontFaceMenu() + { + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + if( cursor.charFormat().fontWeight() > QFont::Normal ) + faceBold->setChecked( true ); + else + faceBold->setChecked( false ); + + if( cursor.charFormat().fontItalic() ) + faceItalic->setChecked( true ); + else + faceItalic->setChecked( false ); + + if( cursor.charFormat().fontUnderline() ) + faceUnderline->setChecked( true ); + else + faceUnderline->setChecked( false ); + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-04 + * + * \brief Method for updating the size menu + */ + void NotebookWindow::updateFontSizeMenu() + { + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + int size = cursor.charFormat().font().pointSize(); + if( size > 0 ) + { + QString txt; + txt.setNum( size ); + + if( sizes_.contains( txt )) + { + sizes_[txt]->setChecked( true ); + sizeOther->setChecked( false ); + } + else + { + cout << "No size found" << endl; + sizeOther->setChecked( true ); + + QHash::iterator s_iter = sizes_.begin(); + while( s_iter != sizes_.end() ) + { + s_iter.value()->setChecked( false ); + ++s_iter; + } + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-04 + * + * \brief Method for updating the stretch menu + */ + void NotebookWindow::updateFontStretchMenu() + { + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + int stretch = cursor.charFormat().font().stretch(); + if( stretchs_.contains( stretch )) + stretchs_[stretch]->setChecked( true ); + else + { + cout << "No stretch found" << endl; + QHash::iterator s_iter = stretchs_.begin(); + while( s_iter != stretchs_.end() ) + { + s_iter.value()->setChecked( false ); + ++s_iter; + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for updating the color menu + */ + void NotebookWindow::updateFontColorMenu() + { + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + QColor color = cursor.charFormat().foreground().color(); + + QHash::iterator c_iter = colors_.begin(); + while( c_iter != colors_.end() ) + { + if( (*c_iter.value()) == color ) + { + c_iter.key()->setChecked( true ); + colorOther->setChecked( false ); + break; + } + else + c_iter.key()->setChecked( false ); + + ++c_iter; + } + + + if( c_iter == colors_.end() ) + colorOther->setChecked( true ); + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for updating the alignment menu + */ + void NotebookWindow::updateTextAlignmentMenu() + { + QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); + + if( editor ) + { + int alignment = editor->alignment(); + if( alignments_.contains( alignment )) + alignments_[alignment]->setChecked( true ); + else + { + cout << "No alignment found" << endl; + QHash::iterator a_iter = alignments_.begin(); + while( a_iter != alignments_.end() ) + { + a_iter.value()->setChecked( false ); + ++a_iter; + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for updating the vertical alignment menu + */ + void NotebookWindow::updateVerticalAlignmentMenu() + { + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + int alignment = cursor.charFormat().verticalAlignment(); + if( verticals_.contains( alignment )) + verticals_[alignment]->setChecked( true ); + else + { + cout << "No vertical alignment found" << endl; + QHash::iterator v_iter = verticals_.begin(); + while( v_iter != verticals_.end() ) + { + v_iter.value()->setChecked( false ); + ++v_iter; + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for updating the border menu + */ + void NotebookWindow::updateBorderMenu() + { + QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); + + if( editor ) + { + int border = editor->document()->rootFrame()->frameFormat().border(); + if( borders_.contains( border )) + { + borders_[border]->setChecked( true ); + borderOther->setChecked( false ); + } + else + { + cout << "No border found" << endl; + borderOther->setChecked( true ); + + QHash::iterator b_iter = borders_.begin(); + while( b_iter != borders_.end() ) + { + b_iter.value()->setChecked( false ); + ++b_iter; + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for updating the margin menu + */ + void NotebookWindow::updateMarginMenu() + { + QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); + + if( editor ) + { + int margin = editor->document()->rootFrame()->frameFormat().margin(); + if( margins_.contains( margin )) + { + margins_[margin]->setChecked( true ); + marginOther->setChecked( false ); + } + else + { + cout << "No margin found" << endl; + marginOther->setChecked( true ); + + QHash::iterator m_iter = margins_.begin(); + while( m_iter != margins_.end() ) + { + m_iter.value()->setChecked( false ); + ++m_iter; + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for updating the padding menu + */ + void NotebookWindow::updatePaddingMenu() + { + QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); + + if( editor ) + { + int padding = editor->document()->rootFrame()->frameFormat().padding(); + if( paddings_.contains( padding )) + { + paddings_[padding]->setChecked( true ); + paddingOther->setChecked( false ); + } + else + { + cout << "No padding found" << endl; + paddingOther->setChecked( true ); + + QHash::iterator p_iter = paddings_.begin(); + while( p_iter != paddings_.end() ) + { + p_iter.value()->setChecked( false ); + ++p_iter; + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-27 + * + * \brief Method for updating the window menu + */ + void NotebookWindow::updateWindowMenu() + { + // remove old windows + windows_.clear(); + windowMenu->clear(); + + // add new menu items + vector windowViews = application()->documentViewList(); + vector::iterator v_iter = windowViews.begin(); + while( v_iter != windowViews.end() ) + { + QString title = (*v_iter)->windowTitle(); + title.remove( "OMNotebook: " ); + + QAction *action = new QAction( title, windowMenu ); + windows_[action] = (*v_iter); + windowMenu->addAction( action ); + ++v_iter; + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-17 + * + * \brief Method for updateing the window title + */ + void NotebookWindow::updateWindowTitle() + { + // QT functionality to stripp the filepath and only keep + // the filename. + QString title = QFileInfo( subject_->getFilename() ).fileName(); + title.remove( "\n" ); + + // if no name, set name to '(untitled)' + if( title.isEmpty() ) + title = "(untitled)"; + + title = QString( "OMNotebook: " ) + title; + + if( subject_->hasChanged() ) + title.append( "*" ); + + setWindowTitle( title ); + } + + /*! + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief Method for updateing the chapter counters + */ + void NotebookWindow::updateChapterCounters() + { + application()->commandCenter()->executeCommand( + new UpdateChapterCounters( subject_ )); + } + + /*! + * \author Anders Fernström + * \date 2006-02-10 + * + * \brief Set the status message to msg, if msg is empty the default + * status message 'Ready' is set. + * + * \param msg A QString containing the status message + */ + void NotebookWindow::setStatusMessage( QString msg ) + { + if( msg.isEmpty() ) + statusBar()->showMessage("Ready"); + else + statusBar()->showMessage( msg ); + } + + void NotebookWindow::setPosition(int r, int c) + { + posIndicator->setText(QString("Ln %1, Col %2").arg(r).arg(c)); + } + + void NotebookWindow::setState(QString s) + { + stateIndicator->setText(s); + } + + void NotebookWindow::setStatusMenu(QList l) + { + QList a = stateIndicator->actions(); + qDeleteAll(a.begin(), a.end()); + + if(!l.size()) + stateIndicator->setContextMenuPolicy(Qt::NoContextMenu); + else + { + stateIndicator->setContextMenuPolicy(Qt::ActionsContextMenu); + stateIndicator->addActions(l); + } + + } + /*! + * \author Anders Fernström + * \date 2006-04-27 + * + * \brief handles forwarded actions + */ + void NotebookWindow::forwardedAction( int action ) + { + + switch( action ) + { + case 1: //COPY + copyEdit(); + break; + case 2: //CUT + cutEdit(); + break; + case 3: //PASTE + pasteEdit(); + break; + default: + break; + } + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * + */ + void NotebookWindow::keyPressEvent(QKeyEvent *event) + { + // 2006-01-30 AF, check if 'Alt+Enter' + if( event->modifiers() == Qt::AltModifier ) + { + if( event->key() == Qt::Key_Enter || + event->key() == Qt::Key_Return ) + { + createNewCell(); + } + else + QMainWindow::keyPressEvent(event); + } + // 2006-02-14 AF, check id 'Shift+Enter' + else if( event->modifiers() == Qt::ShiftModifier && + ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )) + { + evalCells(); + } + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-11-22 (update) + * + * \brief Method for catching some keyevent, and given them + * new functionality + * + * 2005-11-22 AF, Added support for deleting cells with 'DEL' + * key. + */ + void NotebookWindow::keyReleaseEvent(QKeyEvent *event) + { + // if Ctrl is pressed + if(event->modifiers() == Qt::ControlModifier) + { + if(event->key() == Qt::Key_Up) + { + moveCursorUp(); + event->accept(); + } + else if(event->key() == Qt::Key_Down) + { + moveCursorDown(); + event->accept(); + } + else + QMainWindow::keyReleaseEvent(event); + } + else + { + // 2005-11-22 AF, Support for deleting cells with 'DEL' key. + if( event->key() == Qt::Key_Delete ) + { + vector cells = subject_->getSelection(); + if( !cells.empty() ) + { + subject_->cursorDeleteCell(); + event->setAccepted( true ); + + updateChapterCounters(); + } + else + QMainWindow::keyReleaseEvent(event); + } + else + QMainWindow::keyReleaseEvent(event); + } + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * + * \todo Fix the code, when the window dosen't have any file open, + * the command should create the new document, not this function //AF + */ + void NotebookWindow::newFile() + { + /* + application()->commandCenter()->executeCommand(new NewFileCommand()); + + closeFile(); + + createSavingTimer(); + + subject_ = new CellDocument(this); + + connect(subject_, SIGNAL(cursorChanged()), + this, SLOT(setSelectedStyle())); + + setCentralWidget(subject_); + + subject_->show(); + */ + + // AF + if( subject_->isOpen() ) + { + // a file is open, open a new window with the new file //AF + application()->commandCenter()->executeCommand(new OpenFileCommand(QString::null)); + } + else + { + if(subject_->hasChanged()) + { + int res = QMessageBox::question(this, QString("Save document?"), QString("The document has been modified. Do you want to save the changes?"), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel); + if(res == QMessageBox::Yes) + { + + save(); + if(subject_->getFilename().isNull()) + return; + } + else if(res == QMessageBox::Cancel) + return; + } + + subject_ = new CellDocument(app_, QString::null); + dynamic_cast(subject_)->autoIndent = autoIndentAction->isChecked(); + subject_->executeCommand(new NewFileCommand()); + subject_->attach(this); + + update(); + updateWindowTitle(); + } + } + + void NotebookWindow::updateRecentFiles(QString filename) + { + QSettings s("PELAB", "OMNotebook"); + QStringList tmpLst; + QString tmp; + for(int i = 0; i < 4; ++i) + { + if((tmp = s.value(QString("Recent") + QString(i), QString()).toString()) != QString()) + tmpLst.push_back(tmp); + else + break; + } + + if(tmpLst.indexOf(filename) != -1) + tmpLst.move(tmpLst.indexOf(filename), 0); + else + tmpLst.push_front(filename); + + for(int i = 0; i < 4 && i < tmpLst.size(); ++i) + s.setValue(QString("Recent") + QString(i), tmpLst[i]); + + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * + * \brief Open a file. Shows a file dialog. + */ + void NotebookWindow::openFile(const QString filename) + { + try + { + //Open a new document + if(filename.isEmpty()) + { + //Show a dialog for choosing a file. + filename_ = QFileDialog::getOpenFileName( + this, + "OMNotebook -- File Open", + openDir_, + "Notebooks (*.onb *.onbz *.nb)" ); + } + else + { + filename_ = filename; + } + + if(!filename_.isEmpty()) + { + // 2006-03-01 AF, Update openDir_ + openDir_ = QFileInfo( filename_ ).absolutePath(); + + + updateRecentFiles(filename_); + + + if(subject_->isOpen()) + application()->commandCenter()->executeCommand(new OpenFileCommand(filename_)); + else + { + subject_ = new CellDocument(app_, QString::null); + + subject_->executeCommand(new OpenFileCommand(filename_)); + subject_->attach(this); + + } + } + else + { + //Cancel pushed. Do nothing + } + } + catch(exception &e) + { + QString msg = QString("In OpenFile(), Exception: \n") + e.what(); + QMessageBox::warning( 0, "Warning", msg, "OK" ); + openFile(); + } + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * + */ + void NotebookWindow::closeFile() + { + // TODO: the function isn't used correctly, this funciton + // should also close the window, if it isn't the last window + //subject_->executeCommand(new CloseFileCommand()); + + close(); + + //application()-> + + // if(savingTimer_) + // { + // savingTimer_->stop(); + // delete savingTimer_; + // } + //delete subject_; + } + + /*! + * \author Anders Fernström + * \date 2006-01-19 + * + * \brief Reimplemented closeEvent so all close event are handled + * correctly. If the document is unsaved, the applicaiton will ask + * the user if he/she wants to save before closing the document. + */ + void NotebookWindow::closeEvent( QCloseEvent *event ) + { + QString filename = QFileInfo( subject_->getFilename() ).fileName(); + filename.remove( "\n" ); + + // if no name, set name to '(untitled)' + if( filename.isEmpty() ) + filename = "(untitled)"; + + // if the document have been changed, ask if the + // user wants to save the document + while( subject_->hasChanged() ) + { + int res = QMessageBox::question(this, "Document is unsaved", QString("The document \"") + filename + QString("\" is unsaved, do you want to save the document?"), + QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel); /* - int res = QMessageBox::question( this, "Document is unsaved", - QString( "The document \"") + filename + - QString( "\" is unsaved, do you want to save the document" ), - QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No, QMessageBox::NoButton ); + int res = QMessageBox::question( this, "Document is unsaved", + QString( "The document \"") + filename + + QString( "\" is unsaved, do you want to save the document" ), + QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No, QMessageBox::NoButton ); */ - if( res == QMessageBox::No ) - break; - else if(res == QMessageBox::Yes) - save(); - else if(res == QMessageBox::Cancel) - { - event->ignore(); - return; - } - } - - - // 2006-02-09 AF, if last window, ask if OMC also should be closed - if( application()->documentViewList().size() == 1 || closing_ ) - { - try - { + if( res == QMessageBox::No ) + break; + else if(res == QMessageBox::Yes) + save(); + else if(res == QMessageBox::Cancel) + { + event->ignore(); + return; + } + } + + + // 2006-02-09 AF, if last window, ask if OMC also should be closed + if( application()->documentViewList().size() == 1 || closing_ ) + { + try + { OmcInteractiveEnvironment *omc = OmcInteractiveEnvironment::getInstance(); - int result = QMessageBox::question( 0, tr("Close OMC"), - "OK to quit running OpenModelica Compiler process at exit?\n(Answer No if other OMShell/OMNotebook/Graphic editor is still running)", - QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No, QMessageBox::Cancel ); - - if( result == QMessageBox::Yes ) - { - QString quit = "quit()"; - omc->evalExpression( quit ); - } - else if(result == QMessageBox::Cancel) - { - event->ignore(); - return; - } - } - catch( exception &e ) - { + int result = QMessageBox::question( 0, tr("Close OMC"), + "OK to quit running OpenModelica Compiler process at exit?\n(Answer No if other OMShell/OMNotebook/Graphic editor is still running)", + QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No, QMessageBox::Cancel ); + + if( result == QMessageBox::Yes ) + { + QString quit = "quit()"; + omc->evalExpression( quit ); + } + else if(result == QMessageBox::Cancel) + { + event->ignore(); + return; + } + } + catch( exception &e ) + { e.what(); - } - } - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * - * \brief display an ABOUT message box with information about - * OMNotebook. - */ - void NotebookWindow::aboutQTNotebook() - { + } + } + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * + * \brief display an ABOUT message box with information about + * OMNotebook. + */ + void NotebookWindow::aboutQTNotebook() + { const char* dateStr = __DATE__; // "Mmm dd yyyy", so dateStr+7 = "yyyy" - QString version = OmcInteractiveEnvironment::OMCVersion(); - QString abouttext = QString("OMNotebook 3.0 Copyright 2004-") + QString(dateStr+7) + " Link" + QString(QChar(246, 0)) + + QString version = OmcInteractiveEnvironment::OMCVersion(); + QString abouttext = QString("OMNotebook 3.0 Copyright 2004-") + QString(dateStr+7) + " Link" + QString(QChar(246, 0)) + "ping University\nDistributed under OMSC-PL and GPL, see www.openmodelica.org\n\n" + "Connected to OpenModelica " + version + "\n" + - "Created by Ingemar Axelsson (2004-2005), Anders Fernstr" + QString(QChar(246, 0)) +"m (2005-2006) and Henrik Eriksson (2006-2007) as part of their final theses."; - - QMessageBox::about( this, "OMNotebook", abouttext ); - } - - /*! - * \author Anders Fernström - * - * \brief display an ABOUT message box with information about - * Qt. - */ - void NotebookWindow::aboutQT() - { - QMessageBox::aboutQt( this ); - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * - * \brief open the help document, if it exists - */ - void NotebookWindow::helpText() - { - try - { - QDir dir; - QString help = OmcInteractiveEnvironment::OpenModelicaHome(); - if( help.isEmpty() ) - QMessageBox::critical( 0, "OpenModelica Error", "NotebookWindow::helpText could not find environment variable OPENMODELICAHOME; OMNotebook will therefore not work correctly" ); - - if( !help.endsWith("/") && !help.endsWith( "\\") ) - help += "/"; + "Created by Ingemar Axelsson (2004-2005), Anders Fernstr" + QString(QChar(246, 0)) +"m (2005-2006) and Henrik Eriksson (2006-2007) as part of their final theses."; + + QMessageBox::about( this, "OMNotebook", abouttext ); + } + + /*! + * \author Anders Fernström + * + * \brief display an ABOUT message box with information about + * Qt. + */ + void NotebookWindow::aboutQT() + { + QMessageBox::aboutQt( this ); + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * + * \brief open the help document, if it exists + */ + void NotebookWindow::helpText() + { + try + { + QDir dir; + QString help = OmcInteractiveEnvironment::OpenModelicaHome(); + if( help.isEmpty() ) + QMessageBox::critical( 0, "OpenModelica Error", "NotebookWindow::helpText could not find environment variable OPENMODELICAHOME; OMNotebook will therefore not work correctly" ); + + if( !help.endsWith("/") && !help.endsWith( "\\") ) + help += "/"; help += "share/omnotebook/"; - QString helpFile = "OMNotebookHelp.onb"; - dir.setPath( help ); - if( dir.exists( helpFile ) ) - { - application()->commandCenter()->executeCommand( - new OpenFileCommand( help + helpFile )); - } - else - { - QString msg = QString( "Could not find the help doucment: OMNotebookHelp.onb in path: " ) + dir.path(); - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - catch(exception &e) - { - QString msg = QString("In HelpText(), Exception: \n") + e.what(); - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2005-09-30 (update) - * - * \breif Save As function - * - * 2005-09-22 AF, added code for updating window title - * 2005-09-30 AF, add check for fileend when saving. - * - * - * \todo Some of this code should be moved to CellDocument - * instead. The filename should be connected to the document, not - * to the window for example.(Ingemar Axelsson) - */ - void NotebookWindow::saveas() - { - // if a filename exists, use that filename as default - QString filename; -/* don't work correctly. - if( !subject_->getFilename().isEmpty() ) - { - // open save as dialog - filename = QFileDialog::getSaveFileName( - this, - "Choose a filename to save under", - subject_->getFilename(), - "OpenModelica Notebooks (*.onb)"); - } - else - {*/ - // open save as dialog - filename = QFileDialog::getSaveFileName( - this, - "Choose a filename to save under", - saveDir_, - "OpenModelica Notebooks (*.onb);;Compressed OM Notebooks (*.onbz)"); - //} - - if(!filename.isEmpty()) - { - // 2005-09-30 AF, add check for fileend when saving. - if( !filename.endsWith( ".onb", Qt::CaseInsensitive ) && !filename.endsWith( ".onbz", Qt::CaseInsensitive ) ) - { - qDebug( ".onb not found" ); - filename.append( ".onb" ); - } - - statusBar()->showMessage("Saving file"); - application()->commandCenter()->executeCommand(new SaveDocumentCommand(subject_, filename)); - - filename_ = filename; - statusBar()->showMessage("Ready"); - - updateRecentFiles(filename_); - - - // 2006-03-01 AF, Update saveDir_ - saveDir_ = QFileInfo( filename_ ).absolutePath(); - - // 2005-09-22 AF, update window title - updateWindowTitle(); - } - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * - * Added a check that controlls if the user have saved before, - * if not the function saveas should be used insted. //AF - */ - void NotebookWindow::save() - { - // Added a check to see if the document have been saved before, - // if the document havn't been saved before - call saveas() insted. - if( !subject_->isSaved() ) - { - saveas(); - } - else - { - statusBar()->showMessage("Saving file"); - application()->commandCenter()->executeCommand(new SaveDocumentCommand(subject_)); - statusBar()->showMessage("Ready"); - - updateWindowTitle(); - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-18 - * - * \brief Quit OMNotebook - */ - void NotebookWindow::quitOMNotebook() - { - closing_ = true; - qApp->closeAllWindows(); - } - - /*! - * \author Anders Fernström - * \date 2005-12-19 - * \date 2006-02-23 (update) - * - * \brief Open printdialog and print the document - * - * 2006-02-23 AF, display message box after printing is done. - */ - void NotebookWindow::print() - { - QPrinter printer( QPrinter::HighResolution ); - //printer.setFullPage( true ); - -// printer.setColorMode( QPrinter::GrayScale ); - - - QPrintDialog *dlg = new QPrintDialog(&printer, this); - if( dlg->exec() == QDialog::Accepted ) - { - // 2006-03-03 AF, make sure that chapter numbers are updated - updateChapterCounters(); - - application()->commandCenter()->executeCommand( - new PrintDocumentCommand(subject_, &printer)); - - //currentEditor->document()->print(&printer); - - // 2006-02-23 AF, display message box after printing document - QString title = QFileInfo( subject_->getFilename() ).fileName(); - title.remove( "\n" ); - if( title.isEmpty() ) - title = "(untitled)"; - - QString msg = QString( "The document " ) + title + - QString( " have been printed on " ) + - printer.printerName() + QString( "." ); - QMessageBox::information( 0, "Document printed", msg, "OK" ); - } - - delete dlg; - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for changing the font - */ - void NotebookWindow::selectFont() - { - if( !cellEditable() ) - return; - - bool ok; - QFont font = QFontDialog::getFont(&ok, QFont("Times New Roman", 12), this); - - if( ok ) - { - subject_->textcursorChangeFontFamily( font.family() ); - subject_->textcursorChangeFontSize( font.pointSize() ); - - // sätt först plain text - subject_->textcursorChangeFontFace( 0 ); - - if( font.underline() ) - subject_->textcursorChangeFontFace( 3 ); - - if( font.italic() ) - subject_->textcursorChangeFontFace( 2 ); - - if( font.weight() > QFont::Normal ) - subject_->textcursorChangeFontFace( 1 ); - - if( font.strikeOut() ) - subject_->textcursorChangeFontFace( 4 ); - } - } - - /*! - * \author Ingemar Axelsson - */ - void NotebookWindow::changeStyle(QAction *action) - { - // 2005-10-28 changed here because style changed from QString - // to CellStyle /AF - //subject_->cursorChangeStyle(action->text()); - - Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); - CellStyle style = sheet->getStyle( action->text() ); - - if( style.name() != "null" ) - subject_->cursorChangeStyle( style ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Not a valid style name: " + action->text(); - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - - updateChapterCounters(); - } - - /*! - * \author Ingemar Axelsson (and Anders Fernström) - */ - void NotebookWindow::changeStyle() - { - // 2005-10-28 changed in the funtion here because style changed - // from QString to CellStyle /AF - map::iterator cs = styles_.begin(); - Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); //AF - for(;cs != styles_.end(); ++cs) - { - if( (*cs).second->isChecked( )) - { - // look up style /AF - CellStyle style = sheet->getStyle( (*cs).first ); - if( style.name() != "null" ) - subject_->cursorChangeStyle( style ); - - } - } - - updateChapterCounters(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Method for changing font on selected text - */ - void NotebookWindow::changeFont(QAction *action) - { - if( !cellEditable() ) - return; - - subject_->textcursorChangeFontFamily( action->text() ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-03 - * - * \brief Method for changing face on selected text - */ - void NotebookWindow::changeFontFace( QAction *action ) - { - if( !cellEditable() ) - return; - - if( action->text() == "&Plain" ) - subject_->textcursorChangeFontFace( 0 ); - else if( action->text() == "&Bold" ) - subject_->textcursorChangeFontFace( 1 ); - else if( action->text() == "&Italic" ) - subject_->textcursorChangeFontFace( 2 ); - else if( action->text() == "&Underline" ) - subject_->textcursorChangeFontFace( 3 ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-04 - * - * \brief Method for changing size on selected text - */ - void NotebookWindow::changeFontSize( QAction *action ) - { - if( !cellEditable() ) - return; - - if( action->text() == "&Smaller" ) - { // SMALLER - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - int size = cursor.charFormat().font().pointSize(); - if( size < 2 ) - size = 2; - - subject_->textcursorChangeFontSize( size - 1 ); - } - } - else if( action->text() == "&Larger" ) - { // LARGER - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - int size = cursor.charFormat().fontPointSize(); - subject_->textcursorChangeFontSize( size + 1 ); - } - - } - else if( action->text() == "&Other..." ) - { // OTHER - OtherDlg other(this, 6, 200); - if( QDialog::Accepted == other.exec() ) - { - int size = other.value(); - if( size > 0 ) - subject_->textcursorChangeFontSize( size ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Not a value between 6 and 200"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - else - { // MISC - bool ok; - int size = action->text().toInt(&ok); - - if( ok ) - subject_->textcursorChangeFontSize( size ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Not a correct font size"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-04 - * - * \brief Method for changing stretch on selected text - */ - void NotebookWindow::changeFontStretch( QAction *action ) - { - if( !cellEditable() ) - return; - - if( action->text() == "U<ra Condensed" ) - subject_->textcursorChangeFontStretch( QFont::UltraCondensed ); - else if( action->text() == "E&xtra Condensed" ) - subject_->textcursorChangeFontStretch( QFont::ExtraCondensed ); - else if( action->text() == "&Condensed" ) - subject_->textcursorChangeFontStretch( QFont::Condensed ); - else if( action->text() == "S&emi Condensed" ) - subject_->textcursorChangeFontStretch( QFont::SemiCondensed ); - else if( action->text() == "&Unstretched" ) - subject_->textcursorChangeFontStretch( QFont::Unstretched ); - else if( action->text() == "&Semi Expanded" ) - subject_->textcursorChangeFontStretch( QFont::SemiExpanded ); - else if( action->text() == "&Expanded" ) - subject_->textcursorChangeFontStretch( QFont::Expanded ); - else if( action->text() == "Ex&tra Expanded" ) - subject_->textcursorChangeFontStretch( QFont::ExtraExpanded ); - else if( action->text() == "Ult&ra Expanded" ) - subject_->textcursorChangeFontStretch( QFont::UltraExpanded ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for changing color on selected text - */ - void NotebookWindow::changeFontColor( QAction *action ) - { - if( !cellEditable() ) - return; - - if( colors_.contains( action )) - { - subject_->textcursorChangeFontColor( (*colors_[action]) ); - } - else - { - QColor color; - QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - color = cursor.charFormat().foreground().color(); - else - color = Qt::black; + QString helpFile = "OMNotebookHelp.onb"; + dir.setPath( help ); + if( dir.exists( helpFile ) ) + { + application()->commandCenter()->executeCommand( + new OpenFileCommand( help + helpFile )); + } + else + { + QString msg = QString( "Could not find the help doucment: OMNotebookHelp.onb in path: " ) + dir.path(); + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + catch(exception &e) + { + QString msg = QString("In HelpText(), Exception: \n") + e.what(); + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2005-09-30 (update) + * + * \breif Save As function + * + * 2005-09-22 AF, added code for updating window title + * 2005-09-30 AF, add check for fileend when saving. + * + * + * \todo Some of this code should be moved to CellDocument + * instead. The filename should be connected to the document, not + * to the window for example.(Ingemar Axelsson) + */ + void NotebookWindow::saveas() + { + // if a filename exists, use that filename as default + QString filename; +/* don't work correctly. + if( !subject_->getFilename().isEmpty() ) + { + // open save as dialog + filename = QFileDialog::getSaveFileName( + this, + "Choose a filename to save under", + subject_->getFilename(), + "OpenModelica Notebooks (*.onb)"); + } + else + {*/ + // open save as dialog + filename = QFileDialog::getSaveFileName( + this, + "Choose a filename to save under", + saveDir_, + "OpenModelica Notebooks (*.onb);;Compressed OM Notebooks (*.onbz)"); + //} + + if(!filename.isEmpty()) + { + // 2005-09-30 AF, add check for fileend when saving. + if( !filename.endsWith( ".onb", Qt::CaseInsensitive ) && !filename.endsWith( ".onbz", Qt::CaseInsensitive ) ) + { + qDebug( ".onb not found" ); + filename.append( ".onb" ); + } + + statusBar()->showMessage("Saving file"); + application()->commandCenter()->executeCommand(new SaveDocumentCommand(subject_, filename)); + + filename_ = filename; + statusBar()->showMessage("Ready"); + + updateRecentFiles(filename_); + + + // 2006-03-01 AF, Update saveDir_ + saveDir_ = QFileInfo( filename_ ).absolutePath(); + + // 2005-09-22 AF, update window title + updateWindowTitle(); + } + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * + * Added a check that controlls if the user have saved before, + * if not the function saveas should be used insted. //AF + */ + void NotebookWindow::save() + { + // Added a check to see if the document have been saved before, + // if the document havn't been saved before - call saveas() insted. + if( !subject_->isSaved() ) + { + saveas(); + } + else + { + statusBar()->showMessage("Saving file"); + application()->commandCenter()->executeCommand(new SaveDocumentCommand(subject_)); + statusBar()->showMessage("Ready"); + + updateWindowTitle(); + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-18 + * + * \brief Quit OMNotebook + */ + void NotebookWindow::quitOMNotebook() + { + closing_ = true; + qApp->closeAllWindows(); + } + + /*! + * \author Anders Fernström + * \date 2005-12-19 + * \date 2006-02-23 (update) + * + * \brief Open printdialog and print the document + * + * 2006-02-23 AF, display message box after printing is done. + */ + void NotebookWindow::print() + { + QPrinter printer( QPrinter::HighResolution ); + //printer.setFullPage( true ); + +// printer.setColorMode( QPrinter::GrayScale ); + + + QPrintDialog *dlg = new QPrintDialog(&printer, this); + if( dlg->exec() == QDialog::Accepted ) + { + // 2006-03-03 AF, make sure that chapter numbers are updated + updateChapterCounters(); + + application()->commandCenter()->executeCommand( + new PrintDocumentCommand(subject_, &printer)); + + //currentEditor->document()->print(&printer); + + // 2006-02-23 AF, display message box after printing document + QString title = QFileInfo( subject_->getFilename() ).fileName(); + title.remove( "\n" ); + if( title.isEmpty() ) + title = "(untitled)"; + + QString msg = QString( "The document " ) + title + + QString( " have been printed on " ) + + printer.printerName() + QString( "." ); + QMessageBox::information( 0, "Document printed", msg, "OK" ); + } + + delete dlg; + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for changing the font + */ + void NotebookWindow::selectFont() + { + if( !cellEditable() ) + return; + + bool ok; + QFont font = QFontDialog::getFont(&ok, QFont("Times New Roman", 12), this); + + if( ok ) + { + subject_->textcursorChangeFontFamily( font.family() ); + subject_->textcursorChangeFontSize( font.pointSize() ); + + // sätt först plain text + subject_->textcursorChangeFontFace( 0 ); + + if( font.underline() ) + subject_->textcursorChangeFontFace( 3 ); + + if( font.italic() ) + subject_->textcursorChangeFontFace( 2 ); + + if( font.weight() > QFont::Normal ) + subject_->textcursorChangeFontFace( 1 ); + + if( font.strikeOut() ) + subject_->textcursorChangeFontFace( 4 ); + } + } + + /*! + * \author Ingemar Axelsson + */ + void NotebookWindow::changeStyle(QAction *action) + { + // 2005-10-28 changed here because style changed from QString + // to CellStyle /AF + //subject_->cursorChangeStyle(action->text()); + + Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); + CellStyle style = sheet->getStyle( action->text() ); + + if( style.name() != "null" ) + subject_->cursorChangeStyle( style ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Not a valid style name: " + action->text(); + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + + updateChapterCounters(); + } + + /*! + * \author Ingemar Axelsson (and Anders Fernström) + */ + void NotebookWindow::changeStyle() + { + // 2005-10-28 changed in the funtion here because style changed + // from QString to CellStyle /AF + map::iterator cs = styles_.begin(); + Stylesheet *sheet = Stylesheet::instance( "stylesheet.xml" ); //AF + for(;cs != styles_.end(); ++cs) + { + if( (*cs).second->isChecked( )) + { + // look up style /AF + CellStyle style = sheet->getStyle( (*cs).first ); + if( style.name() != "null" ) + subject_->cursorChangeStyle( style ); + + } + } + + updateChapterCounters(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Method for changing font on selected text + */ + void NotebookWindow::changeFont(QAction *action) + { + if( !cellEditable() ) + return; + + subject_->textcursorChangeFontFamily( action->text() ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-03 + * + * \brief Method for changing face on selected text + */ + void NotebookWindow::changeFontFace( QAction *action ) + { + if( !cellEditable() ) + return; + + if( action->text() == "&Plain" ) + subject_->textcursorChangeFontFace( 0 ); + else if( action->text() == "&Bold" ) + subject_->textcursorChangeFontFace( 1 ); + else if( action->text() == "&Italic" ) + subject_->textcursorChangeFontFace( 2 ); + else if( action->text() == "&Underline" ) + subject_->textcursorChangeFontFace( 3 ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-04 + * + * \brief Method for changing size on selected text + */ + void NotebookWindow::changeFontSize( QAction *action ) + { + if( !cellEditable() ) + return; + + if( action->text() == "&Smaller" ) + { // SMALLER + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + int size = cursor.charFormat().font().pointSize(); + if( size < 2 ) + size = 2; + + subject_->textcursorChangeFontSize( size - 1 ); + } + } + else if( action->text() == "&Larger" ) + { // LARGER + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + int size = cursor.charFormat().fontPointSize(); + subject_->textcursorChangeFontSize( size + 1 ); + } + + } + else if( action->text() == "&Other..." ) + { // OTHER + OtherDlg other(this, 6, 200); + if( QDialog::Accepted == other.exec() ) + { + int size = other.value(); + if( size > 0 ) + subject_->textcursorChangeFontSize( size ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Not a value between 6 and 200"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + else + { // MISC + bool ok; + int size = action->text().toInt(&ok); + + if( ok ) + subject_->textcursorChangeFontSize( size ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Not a correct font size"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-04 + * + * \brief Method for changing stretch on selected text + */ + void NotebookWindow::changeFontStretch( QAction *action ) + { + if( !cellEditable() ) + return; + + if( action->text() == "U<ra Condensed" ) + subject_->textcursorChangeFontStretch( QFont::UltraCondensed ); + else if( action->text() == "E&xtra Condensed" ) + subject_->textcursorChangeFontStretch( QFont::ExtraCondensed ); + else if( action->text() == "&Condensed" ) + subject_->textcursorChangeFontStretch( QFont::Condensed ); + else if( action->text() == "S&emi Condensed" ) + subject_->textcursorChangeFontStretch( QFont::SemiCondensed ); + else if( action->text() == "&Unstretched" ) + subject_->textcursorChangeFontStretch( QFont::Unstretched ); + else if( action->text() == "&Semi Expanded" ) + subject_->textcursorChangeFontStretch( QFont::SemiExpanded ); + else if( action->text() == "&Expanded" ) + subject_->textcursorChangeFontStretch( QFont::Expanded ); + else if( action->text() == "Ex&tra Expanded" ) + subject_->textcursorChangeFontStretch( QFont::ExtraExpanded ); + else if( action->text() == "Ult&ra Expanded" ) + subject_->textcursorChangeFontStretch( QFont::UltraExpanded ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for changing color on selected text + */ + void NotebookWindow::changeFontColor( QAction *action ) + { + if( !cellEditable() ) + return; + + if( colors_.contains( action )) + { + subject_->textcursorChangeFontColor( (*colors_[action]) ); + } + else + { + QColor color; + QTextCursor cursor( subject_->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + color = cursor.charFormat().foreground().color(); + else + color = Qt::black; QColor newColor = QColorDialog::getColor( color, this ); - if( newColor.isValid() ) - subject_->textcursorChangeFontColor( newColor ); - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for changing alignment on selected paragraf - */ - void NotebookWindow::changeTextAlignment( QAction *action ) - { - if( !cellEditable() ) - return; - - QHash::iterator a_iter = alignments_.begin(); - while( a_iter != alignments_.end() ) - { - if( a_iter.value() == action ) - { - subject_->textcursorChangeTextAlignment( a_iter.key() ); - break; - } - - ++a_iter; - } - - if( a_iter == alignments_.end() ) - { - // 2006-01-30 AF, add message box - QString msg = "Unable to find the correct alignment"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for changing vertical alignment on selected text - */ - void NotebookWindow::changeVerticalAlignment( QAction *action ) - { - if( !cellEditable() ) - return; - - QHash::iterator v_iter = verticals_.begin(); - while( v_iter != verticals_.end() ) - { - if( v_iter.value() == action ) - { - subject_->textcursorChangeVerticalAlignment( v_iter.key() ); - break; - } - - ++v_iter; - } - - if( v_iter == verticals_.end() ) - { - // 2006-01-30 AF, add message box - QString msg = "Unable to find the correct vertical alignment"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for changing border on selected cell - */ - void NotebookWindow::changeBorder( QAction *action ) - { - if( !cellEditable() ) - return; - - if( action->text() == "&Other..." ) - { - OtherDlg other(this, 0, 30); - if( QDialog::Accepted == other.exec() ) - { - int border = other.value(); - if( border > 0 ) - subject_->textcursorChangeBorder( border ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Not a value between 0 and 30"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - else - { - bool ok; - int border = action->text().toInt( &ok ); - - if( ok ) - subject_->textcursorChangeBorder( border ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Error converting QString to Int (border)"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for changing margin on selected cell - */ - void NotebookWindow::changeMargin( QAction *action ) - { - if( !cellEditable() ) - return; - - if( action->text() == "&Other..." ) - { - OtherDlg other(this, 0, 80); - if( QDialog::Accepted == other.exec() ) - { - int margin = other.value(); - if( margin > 0 ) - subject_->textcursorChangeMargin( margin ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Not a value between 0 and 80."; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - else - { - bool ok; - int margin = action->text().toInt( &ok ); - - if( ok ) - subject_->textcursorChangeMargin( margin ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Error converting QString to Int (margin)"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-07 - * - * \brief Method for changing padding on selected cell - */ - void NotebookWindow::changePadding( QAction *action ) - { - if( !cellEditable() ) - return; - - if( action->text() == "&Other..." ) - { - OtherDlg other(this, 0, 60); - if( QDialog::Accepted == other.exec() ) - { - int padding = other.value(); - if( padding > 0 ) - subject_->textcursorChangePadding( padding ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Not a value between 0 and 60."; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - else - { - bool ok; - int padding = action->text().toInt( &ok ); - - if( ok ) - subject_->textcursorChangePadding( padding ); - else - { - // 2006-01-30 AF, add message box - QString msg = "Error converting QString to Int (padding)"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - - /*! - * \author Anders Fernström - * \date 2006-01-27 - * - * \brief Method for changing the current notebook window - */ - void NotebookWindow::changeWindow(QAction *action) - { - if( !windows_[action]->isActiveWindow() ) - { - windows_[action]->activateWindow(); - windows_[action]->showNormal(); - } - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * - * \brief Method for doing undo on text - */ - void NotebookWindow::undoEdit() - { - QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); - if( editor ) - { - editor->document()->undo(); - } - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * - * \brief Method for doing redo on text - */ - void NotebookWindow::redoEdit() - { - QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); - if( editor ) - { - editor->document()->redo(); - } - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * \date 2006-04-27 (update) - * - * \brief Method for cuting text - * - * 2006-04-27 AF, if cells are selected in the treeview cut - * them instead of the text. - */ - void NotebookWindow::cutEdit() - { - if( subject_ ) - { - if( subject_->getSelection().size() > 0 ) - cutCell(); - else - subject_->textcursorCutText(); - } - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * \date 2006-04-27 (update) - * - * \brief Method for copying text - * - * 2006-04-27 AF, if cells are selected in the treeview copy - * them instead of the text. - */ - void NotebookWindow::copyEdit() - { - if( subject_ ) - { - if( subject_->getSelection().size() > 0 ) - copyCell(); - else - subject_->textcursorCopyText(); - } - } - - /*! - * \author Anders Fernström - * \date 2006-02-03 - * \date 2006-04-27 (update) - * - * \brief Method for pasteing text - * - * 2006-04-27 AF, if the cell cursor is selected, paste - * cell instead of text. - */ - void NotebookWindow::pasteEdit() - { - if( subject_ ) - { - if( subject_->getCursor()->isClickedOn() ) - pasteCell(); - else - subject_->textcursorPasteText(); - } - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Menu function, perform find - */ - void NotebookWindow::findEdit() - { - if( subject_ ) - { - // initiate findform, check if it is already visible, or set the current document - if( !findForm_ ) - findForm_ = new SearchForm( this, subject_ ); - else - findForm_->setDocument( subject_ ); - - // show/start find form - if( !findForm_->isVisible() ) - findForm_->show(); - } - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Menu function, perform replace - */ - void NotebookWindow::replaceEdit() - { - if( subject_ ) - { - // initiate findform(replace), check if it is already visible, or set the current document - if( !findForm_ ) - findForm_ = new SearchForm( this, subject_, true ); - else - findForm_->setDocument( subject_ ); - - // show/start find form - if( !findForm_->isVisible() ) - findForm_->show(); - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-18 - * - * \brief Method for inserting an image into the cell - */ - void NotebookWindow::insertImage() - { - if( !cellEditable() ) - return; - - QString imageformat = "Images ("; - QList list = QImageReader::supportedImageFormats(); - for( int i = 0; i < list.size(); ++i ) - imageformat += QString("*.") + QString(list.at(i)) + " "; - imageformat += ")"; - - QString filepath = QFileDialog::getOpenFileName( - this, "Insert Image - Select Image", imageDir_, - imageformat ); - - if( !filepath.isNull() ) - { - QImage image( filepath ); - if( !image.isNull() ) - { - ImageSizeDlg imageSize( this, &image ); - if( QDialog::Accepted == imageSize.exec() ) - { - QSize size = imageSize.value(); - if( size.isValid() ) - subject_->textcursorInsertImage( filepath, size ); - else - cout << "Not a valid image size" << endl; - } - } - - // 2006-03-01 AF, Update imageDir_ - imageDir_ = QFileInfo( filepath ).absolutePath(); - } - } - - /*! - * \author Anders Fernström - * \date 2005-12-05 - * - * \brief Method for inserting an link to the selected cell - */ - void NotebookWindow::insertLink() - { - if( !cellEditable() ) - return; - - // check if text is selected - QTextCursor cursor = subject_->getCursor()->currentCell()->textCursor(); - if( !cursor.isNull() ) - { - if( cursor.hasSelection() ) - { - QString filepath = QFileDialog::getOpenFileName( - this, "Insert Link - Select Document", linkDir_, - "Notebooks (*.onb *.nb)" ); - - if( !filepath.isNull() ) - { - // 2006-03-01 AF, Update linkDir_ - linkDir_ = QFileInfo( filepath ).absolutePath(); - - subject_->textcursorInsertLink( filepath, cursor ); - } - } - else - { - QMessageBox::warning( this, "- No text is selected -", - "A text that should make up the link, must be selected", - "OK" ); - } - } - } - - void NotebookWindow::indent() - { - GraphCell* g; - if(g = dynamic_cast(subject_->getCursor()->currentCell())) - { - g->input_->indentText(); - } - - } - - /*! - * \author Anders Fernström - * \date 2005-12-01 - * - * \brief Method for opening an old file, saved with OMNotebook (QT3) - */ - void NotebookWindow::openOldFile() - { - try - { - QString filename = QFileDialog::getOpenFileName( - this, - "OMNotebook -- Open old OMNotebook file", - openDir_, - "Old OMNotebook (*.xml)" ); - - if( !filename.isEmpty() ) - { - // 2006-03-01 AF, Update openDir_ - openDir_ = QFileInfo( filename ).absolutePath(); - - application()->commandCenter()->executeCommand( - new OpenOldFileCommand( filename, READMODE_OLD )); - } - } - catch( exception &e ) - { - QString msg = QString("In NotebookWindow(), Exception:\r\n") + e.what(); - QMessageBox::warning( 0, "Warning", msg, "OK" ); - openOldFile(); - } - } - - /*! - * \author Anders Fernström - * \date 2005-11-21 - * \date 2006-03-24 (update) - * - * \brief Method for exporting the document content to a file with - * pure text only - * - * 2006-03-24 AF, Added message box to inform the user when export - * is done. - */ - void NotebookWindow::pureText() - { - QString filename = QFileDialog::getSaveFileName( - this, - "Choose a filename to export text to", - saveDir_, - "Textfile (*.txt)"); - - if( !filename.isEmpty() ) - { - if( !filename.endsWith( ".txt", Qt::CaseInsensitive ) ) - { - qDebug( ".txt not found" ); - filename.append( ".txt" ); - } - - // 2006-03-01 AF, Update saveDir_ - saveDir_ = QFileInfo( filename_ ).absolutePath(); - - // 2006-03-03 AF, make sure that chapter numbers are updated - updateChapterCounters(); - - application()->commandCenter()->executeCommand( - new ExportToPureText(subject_, filename) ); - - // 2006-03-24 AF, added message box - so user know when - // export is done - QString title = QFileInfo( subject_->getFilename() ).fileName(); - title.remove( "\n" ); - if( title.isEmpty() ) - title = "(untitled)"; - - QString msg = QString( "The document " ) + title + - QString( " have been exported as pure text to " ) + - filename + QString( "." ); - QMessageBox::information( 0, "Document exported", msg, "OK" ); - } - } - - /*! - * \author Ingemar Axelsson - */ - void NotebookWindow::createNewCell() - { - subject_->cursorAddCell(); - updateChapterCounters(); - } - - /*! - * \author Ingemar Axelsson - */ - void NotebookWindow::deleteCurrentCell() - { - subject_->cursorDeleteCell(); - updateChapterCounters(); - } - - /*! - * \author Ingemar Axelsson - */ - void NotebookWindow::cutCell() - { - subject_->cursorCutCell(); - updateChapterCounters(); - } - - /*! - * \author Ingemar Axelsson - */ - void NotebookWindow::copyCell() - { - subject_->cursorCopyCell(); - } - - /*! - * \author Ingemar Axelsson - */ - void NotebookWindow::pasteCell() - { - subject_->cursorPasteCell(); - updateChapterCounters(); - } - - /*! - * \author Anders Fernström - * \date 2006-04-26 - * - * \brief Ungroup all selected groupcells - */ - void NotebookWindow::ungroupCell() - { - if( subject_->getSelection().size() == 1 ) - subject_->cursorUngroupCell(); - else - QMessageBox::information( this, "Information", "Ungroup can only be done on one cell at the time. Please select only one cell" ); - } - - /*! - * \author Anders Fernström - * \date 2006-04-26 - * - * \brief Split current cell - */ - void NotebookWindow::splitCell() - { - subject_->cursorSplitCell(); - } - - /*! - * \author Ingemar Axelsson - */ - void NotebookWindow::moveCursorDown() - { - subject_->cursorStepDown(); - } - - /*! - * \author Ingemar Axelsson - */ - void NotebookWindow::moveCursorUp() - { - subject_->cursorStepUp(); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-11-29 (update) - * - * 2005-11-29 AF, addad call to updateScrollArea, so the scrollarea - * are updated when new cell is added. - */ - void NotebookWindow::groupCellsAction() - { - Cell *cell = subject_->getCursor()->currentCell(); - if( cell ) - { - if( cell->treeView()->isHidden() ) - { - QMessageBox::information( 0, "Can make groupcell", - "A textcell or inputcell must first be added, before a groupcell can be done" ); - } - else - { - subject_->executeCommand(new MakeGroupCellCommand()); - subject_->updateScrollArea(); - } - } - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-11-29 (update) - * - * 2005-11-29 AF, addad call to updateScrollArea, so the scrollarea - * are updated when new cell is added. - */ - void NotebookWindow::inputCellsAction() - { - subject_->executeCommand(new CreateNewCellCommand("Graph")); - subject_->updateScrollArea(); - updateChapterCounters(); - } - - void NotebookWindow::textCellsAction() - { - subject_->executeCommand(new CreateNewCellCommand("Text")); - subject_->updateScrollArea(); - updateChapterCounters(); - } - - void NotebookWindow::recentTriggered() //Should only be called from the submenu "recent files" - { - QObject* s = QObject::sender(); - if(s) - emit openFile(static_cast(s)->text()); - } - - void NotebookWindow::setAutoIndent(bool b) - { - // if(CellDocument* d = dynamic_cast(subject_)) - subject_->setAutoIndent2(b); - - QSettings s("PELAB", "OMNotebook"); - s.setValue("AutoIndent", b); - - } - - void NotebookWindow::eval() - { - if(GraphCell *g = dynamic_cast(subject_->getCursor()->currentCell())) - g->eval(); - else if(InputCell *g = dynamic_cast(subject_->getCursor()->currentCell())) - g->eval(); - - - } + if( newColor.isValid() ) + subject_->textcursorChangeFontColor( newColor ); + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for changing alignment on selected paragraf + */ + void NotebookWindow::changeTextAlignment( QAction *action ) + { + if( !cellEditable() ) + return; + + QHash::iterator a_iter = alignments_.begin(); + while( a_iter != alignments_.end() ) + { + if( a_iter.value() == action ) + { + subject_->textcursorChangeTextAlignment( a_iter.key() ); + break; + } + + ++a_iter; + } + + if( a_iter == alignments_.end() ) + { + // 2006-01-30 AF, add message box + QString msg = "Unable to find the correct alignment"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for changing vertical alignment on selected text + */ + void NotebookWindow::changeVerticalAlignment( QAction *action ) + { + if( !cellEditable() ) + return; + + QHash::iterator v_iter = verticals_.begin(); + while( v_iter != verticals_.end() ) + { + if( v_iter.value() == action ) + { + subject_->textcursorChangeVerticalAlignment( v_iter.key() ); + break; + } + + ++v_iter; + } + + if( v_iter == verticals_.end() ) + { + // 2006-01-30 AF, add message box + QString msg = "Unable to find the correct vertical alignment"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for changing border on selected cell + */ + void NotebookWindow::changeBorder( QAction *action ) + { + if( !cellEditable() ) + return; + + if( action->text() == "&Other..." ) + { + OtherDlg other(this, 0, 30); + if( QDialog::Accepted == other.exec() ) + { + int border = other.value(); + if( border > 0 ) + subject_->textcursorChangeBorder( border ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Not a value between 0 and 30"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + else + { + bool ok; + int border = action->text().toInt( &ok ); + + if( ok ) + subject_->textcursorChangeBorder( border ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Error converting QString to Int (border)"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for changing margin on selected cell + */ + void NotebookWindow::changeMargin( QAction *action ) + { + if( !cellEditable() ) + return; + + if( action->text() == "&Other..." ) + { + OtherDlg other(this, 0, 80); + if( QDialog::Accepted == other.exec() ) + { + int margin = other.value(); + if( margin > 0 ) + subject_->textcursorChangeMargin( margin ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Not a value between 0 and 80."; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + else + { + bool ok; + int margin = action->text().toInt( &ok ); + + if( ok ) + subject_->textcursorChangeMargin( margin ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Error converting QString to Int (margin)"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-07 + * + * \brief Method for changing padding on selected cell + */ + void NotebookWindow::changePadding( QAction *action ) + { + if( !cellEditable() ) + return; + + if( action->text() == "&Other..." ) + { + OtherDlg other(this, 0, 60); + if( QDialog::Accepted == other.exec() ) + { + int padding = other.value(); + if( padding > 0 ) + subject_->textcursorChangePadding( padding ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Not a value between 0 and 60."; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + else + { + bool ok; + int padding = action->text().toInt( &ok ); + + if( ok ) + subject_->textcursorChangePadding( padding ); + else + { + // 2006-01-30 AF, add message box + QString msg = "Error converting QString to Int (padding)"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + + /*! + * \author Anders Fernström + * \date 2006-01-27 + * + * \brief Method for changing the current notebook window + */ + void NotebookWindow::changeWindow(QAction *action) + { + if( !windows_[action]->isActiveWindow() ) + { + windows_[action]->activateWindow(); + windows_[action]->showNormal(); + } + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * + * \brief Method for doing undo on text + */ + void NotebookWindow::undoEdit() + { + QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); + if( editor ) + { + editor->document()->undo(); + } + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * + * \brief Method for doing redo on text + */ + void NotebookWindow::redoEdit() + { + QTextEdit *editor = subject_->getCursor()->currentCell()->textEdit(); + if( editor ) + { + editor->document()->redo(); + } + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * \date 2006-04-27 (update) + * + * \brief Method for cuting text + * + * 2006-04-27 AF, if cells are selected in the treeview cut + * them instead of the text. + */ + void NotebookWindow::cutEdit() + { + if( subject_ ) + { + if( subject_->getSelection().size() > 0 ) + cutCell(); + else + subject_->textcursorCutText(); + } + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * \date 2006-04-27 (update) + * + * \brief Method for copying text + * + * 2006-04-27 AF, if cells are selected in the treeview copy + * them instead of the text. + */ + void NotebookWindow::copyEdit() + { + if( subject_ ) + { + if( subject_->getSelection().size() > 0 ) + copyCell(); + else + subject_->textcursorCopyText(); + } + } + + /*! + * \author Anders Fernström + * \date 2006-02-03 + * \date 2006-04-27 (update) + * + * \brief Method for pasteing text + * + * 2006-04-27 AF, if the cell cursor is selected, paste + * cell instead of text. + */ + void NotebookWindow::pasteEdit() + { + if( subject_ ) + { + if( subject_->getCursor()->isClickedOn() ) + pasteCell(); + else + subject_->textcursorPasteText(); + } + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Menu function, perform find + */ + void NotebookWindow::findEdit() + { + if( subject_ ) + { + // initiate findform, check if it is already visible, or set the current document + if( !findForm_ ) + findForm_ = new SearchForm( this, subject_ ); + else + findForm_->setDocument( subject_ ); + + // show/start find form + if( !findForm_->isVisible() ) + findForm_->show(); + } + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Menu function, perform replace + */ + void NotebookWindow::replaceEdit() + { + if( subject_ ) + { + // initiate findform(replace), check if it is already visible, or set the current document + if( !findForm_ ) + findForm_ = new SearchForm( this, subject_, true ); + else + findForm_->setDocument( subject_ ); + + // show/start find form + if( !findForm_->isVisible() ) + findForm_->show(); + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-18 + * + * \brief Method for inserting an image into the cell + */ + void NotebookWindow::insertImage() + { + if( !cellEditable() ) + return; + + QString imageformat = "Images ("; + QList list = QImageReader::supportedImageFormats(); + for( int i = 0; i < list.size(); ++i ) + imageformat += QString("*.") + QString(list.at(i)) + " "; + imageformat += ")"; + + QString filepath = QFileDialog::getOpenFileName( + this, "Insert Image - Select Image", imageDir_, + imageformat ); + + if( !filepath.isNull() ) + { + QImage image( filepath ); + if( !image.isNull() ) + { + ImageSizeDlg imageSize( this, &image ); + if( QDialog::Accepted == imageSize.exec() ) + { + QSize size = imageSize.value(); + if( size.isValid() ) + subject_->textcursorInsertImage( filepath, size ); + else + cout << "Not a valid image size" << endl; + } + } + + // 2006-03-01 AF, Update imageDir_ + imageDir_ = QFileInfo( filepath ).absolutePath(); + } + } + + /*! + * \author Anders Fernström + * \date 2005-12-05 + * + * \brief Method for inserting an link to the selected cell + */ + void NotebookWindow::insertLink() + { + if( !cellEditable() ) + return; + + // check if text is selected + QTextCursor cursor = subject_->getCursor()->currentCell()->textCursor(); + if( !cursor.isNull() ) + { + if( cursor.hasSelection() ) + { + QString filepath = QFileDialog::getOpenFileName( + this, "Insert Link - Select Document", linkDir_, + "Notebooks (*.onb *.nb)" ); + + if( !filepath.isNull() ) + { + // 2006-03-01 AF, Update linkDir_ + linkDir_ = QFileInfo( filepath ).absolutePath(); + + subject_->textcursorInsertLink( filepath, cursor ); + } + } + else + { + QMessageBox::warning( this, "- No text is selected -", + "A text that should make up the link, must be selected", + "OK" ); + } + } + } + + void NotebookWindow::indent() + { + GraphCell* g; + if(g = dynamic_cast(subject_->getCursor()->currentCell())) + { + g->input_->indentText(); + } + + } + + /*! + * \author Anders Fernström + * \date 2005-12-01 + * + * \brief Method for opening an old file, saved with OMNotebook (QT3) + */ + void NotebookWindow::openOldFile() + { + try + { + QString filename = QFileDialog::getOpenFileName( + this, + "OMNotebook -- Open old OMNotebook file", + openDir_, + "Old OMNotebook (*.xml)" ); + + if( !filename.isEmpty() ) + { + // 2006-03-01 AF, Update openDir_ + openDir_ = QFileInfo( filename ).absolutePath(); + + application()->commandCenter()->executeCommand( + new OpenOldFileCommand( filename, READMODE_OLD )); + } + } + catch( exception &e ) + { + QString msg = QString("In NotebookWindow(), Exception:\r\n") + e.what(); + QMessageBox::warning( 0, "Warning", msg, "OK" ); + openOldFile(); + } + } + + /*! + * \author Anders Fernström + * \date 2005-11-21 + * \date 2006-03-24 (update) + * + * \brief Method for exporting the document content to a file with + * pure text only + * + * 2006-03-24 AF, Added message box to inform the user when export + * is done. + */ + void NotebookWindow::pureText() + { + QString filename = QFileDialog::getSaveFileName( + this, + "Choose a filename to export text to", + saveDir_, + "Textfile (*.txt)"); + + if( !filename.isEmpty() ) + { + if( !filename.endsWith( ".txt", Qt::CaseInsensitive ) ) + { + qDebug( ".txt not found" ); + filename.append( ".txt" ); + } + + // 2006-03-01 AF, Update saveDir_ + saveDir_ = QFileInfo( filename_ ).absolutePath(); + + // 2006-03-03 AF, make sure that chapter numbers are updated + updateChapterCounters(); + + application()->commandCenter()->executeCommand( + new ExportToPureText(subject_, filename) ); + + // 2006-03-24 AF, added message box - so user know when + // export is done + QString title = QFileInfo( subject_->getFilename() ).fileName(); + title.remove( "\n" ); + if( title.isEmpty() ) + title = "(untitled)"; + + QString msg = QString( "The document " ) + title + + QString( " have been exported as pure text to " ) + + filename + QString( "." ); + QMessageBox::information( 0, "Document exported", msg, "OK" ); + } + } + + /*! + * \author Ingemar Axelsson + */ + void NotebookWindow::createNewCell() + { + subject_->cursorAddCell(); + updateChapterCounters(); + } + + /*! + * \author Ingemar Axelsson + */ + void NotebookWindow::deleteCurrentCell() + { + subject_->cursorDeleteCell(); + updateChapterCounters(); + } + + /*! + * \author Ingemar Axelsson + */ + void NotebookWindow::cutCell() + { + subject_->cursorCutCell(); + updateChapterCounters(); + } + + /*! + * \author Ingemar Axelsson + */ + void NotebookWindow::copyCell() + { + subject_->cursorCopyCell(); + } + + /*! + * \author Ingemar Axelsson + */ + void NotebookWindow::pasteCell() + { + subject_->cursorPasteCell(); + updateChapterCounters(); + } + + /*! + * \author Anders Fernström + * \date 2006-04-26 + * + * \brief Ungroup all selected groupcells + */ + void NotebookWindow::ungroupCell() + { + if( subject_->getSelection().size() == 1 ) + subject_->cursorUngroupCell(); + else + QMessageBox::information( this, "Information", "Ungroup can only be done on one cell at the time. Please select only one cell" ); + } + + /*! + * \author Anders Fernström + * \date 2006-04-26 + * + * \brief Split current cell + */ + void NotebookWindow::splitCell() + { + subject_->cursorSplitCell(); + } + + /*! + * \author Ingemar Axelsson + */ + void NotebookWindow::moveCursorDown() + { + subject_->cursorStepDown(); + } + + /*! + * \author Ingemar Axelsson + */ + void NotebookWindow::moveCursorUp() + { + subject_->cursorStepUp(); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-11-29 (update) + * + * 2005-11-29 AF, addad call to updateScrollArea, so the scrollarea + * are updated when new cell is added. + */ + void NotebookWindow::groupCellsAction() + { + Cell *cell = subject_->getCursor()->currentCell(); + if( cell ) + { + if( cell->treeView()->isHidden() ) + { + QMessageBox::information( 0, "Can make groupcell", + "A textcell or inputcell must first be added, before a groupcell can be done" ); + } + else + { + subject_->executeCommand(new MakeGroupCellCommand()); + subject_->updateScrollArea(); + } + } + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-11-29 (update) + * + * 2005-11-29 AF, addad call to updateScrollArea, so the scrollarea + * are updated when new cell is added. + */ + void NotebookWindow::inputCellsAction() + { + subject_->executeCommand(new CreateNewCellCommand("Graph")); + subject_->updateScrollArea(); + updateChapterCounters(); + } + + void NotebookWindow::textCellsAction() + { + subject_->executeCommand(new CreateNewCellCommand("Text")); + subject_->updateScrollArea(); + updateChapterCounters(); + } + + void NotebookWindow::recentTriggered() //Should only be called from the submenu "recent files" + { + QObject* s = QObject::sender(); + if(s) + emit openFile(static_cast(s)->text()); + } + + void NotebookWindow::setAutoIndent(bool b) + { + // if(CellDocument* d = dynamic_cast(subject_)) + subject_->setAutoIndent2(b); + + QSettings s("PELAB", "OMNotebook"); + s.setValue("AutoIndent", b); + + } + + void NotebookWindow::eval() + { + if(GraphCell *g = dynamic_cast(subject_->getCursor()->currentCell())) + g->eval(); + else if(InputCell *g = dynamic_cast(subject_->getCursor()->currentCell())) + g->eval(); + + + } } diff --git a/OMNotebook/OMNotebookQT4/notebook.h b/OMNotebook/OMNotebookQT4/notebook.h index b1f4da6ae8b..2a55d598287 100644 --- a/OMNotebook/OMNotebookQT4/notebook.h +++ b/OMNotebook/OMNotebookQT4/notebook.h @@ -64,297 +64,297 @@ class QLabel; namespace IAEX { - // forward declaration - class SearchForm; - - class NotebookWindow : public DocumentView - { - Q_OBJECT - - public: - NotebookWindow(Document *subject, const QString filename=0, - QWidget *parent=0); - virtual ~NotebookWindow(); - - virtual void update(); - virtual Document* document(); - CellApplication *application(); - - public slots: - void updateMenus(); // Added 2005-11-07 AF - void updateStyleMenu(); - void updateEditMenu(); // Added 2005-11-02 AF - void updateCellMenu(); // Added 2006-02-03 AF - void updateFontMenu(); // Added 2005-11-03 AF - void updateFontFaceMenu(); // Added 2005-11-03 AF - void updateFontSizeMenu(); // Added 2005-11-04 AF - void updateFontStretchMenu(); // Added 2005-11-04 AF - void updateFontColorMenu(); // Added 2005-11-07 AF - void updateTextAlignmentMenu(); // Added 2005-11-07 AF - void updateVerticalAlignmentMenu(); // Added 2005-11-07 AF - void updateBorderMenu(); // Added 2005-11-07 AF - void updateMarginMenu(); // Added 2005-11-07 AF - void updatePaddingMenu(); // Added 2005-11-07 AF - void updateWindowMenu(); // Added 2006-01-27 AF - void updateWindowTitle(); // Added 2006-01-17 AF - void updateChapterCounters(); // Added 2006-03-02 AF - void setStatusMessage( QString msg ); // Added 2006-02-10 AF - void forwardedAction( int action ); // Added 2006-04-27 AF - void setPosition(int r, int c); - void setState(QString); - void setStatusMenu(QList); - void recentTriggered(); - protected: - void keyPressEvent(QKeyEvent *event); - void keyReleaseEvent(QKeyEvent *event); - - private slots: - void newFile(); - void openFile(const QString filename=""); - void closeFile(); - void closeEvent( QCloseEvent *event ); // Added 2006-01-19 AF - void aboutQTNotebook(); - void aboutQT(); // Added 2006-02-21 AF - void helpText(); // Added 2006-02-03 AF - void saveas(); - void save(); - void quitOMNotebook(); // Added 2006-01-18 AF - void print(); // Added 2005-12-19 AF - void selectFont(); // Added 2005-11-07 AF - void changeStyle(QAction *action); - void changeStyle(); - void changeFont(QAction *action); // Added 2005-11-03 AF - void changeFontFace(QAction *action); // Added 2005-11-03 AF - void changeFontSize(QAction *action); // Added 2005-11-04 AF - void changeFontStretch(QAction *action); // Added 2005-11-04 AF - void changeFontColor(QAction *action); // Added 2005-11-07 AF - void changeTextAlignment(QAction *action); // Added 2005-11-07 AF - void changeVerticalAlignment(QAction *action); // Added 2005-11-07 AF - void changeBorder(QAction *action); // Added 2005-11-07 AF - void changeMargin(QAction *action); // Added 2005-11-07 AF - void changePadding(QAction *action); // Added 2005-11-07 AF - void changeWindow(QAction *action); // Added 2006-01-27 AF - - void undoEdit(); // Added 2006-02-03 AF - void redoEdit(); // Added 2006-02-03 AF - void cutEdit(); // Added 2006-02-03 AF - void copyEdit(); // Added 2006-02-03 AF - void pasteEdit(); // Added 2006-02-03 AF - void findEdit(); // Added 2006-08-24 AF - void replaceEdit(); // Added 2006-08-24 AF - - void insertImage(); // Added 2005-11-18 AF - void insertLink(); // Added 2005-12-05 AF - void openOldFile(); // Added 2005-12-01 AF - void pureText(); // Added 2005-11-21 AF - - void createNewCell(); - void deleteCurrentCell(); - void cutCell(); - void copyCell(); - void pasteCell(); - void ungroupCell(); // Added 2006-04-26 AF - void splitCell(); // Added 2006-04-26 AF - void moveCursorUp(); - void moveCursorDown(); - void groupCellsAction(); - void inputCellsAction(); - void textCellsAction(); - void updateRecentFiles(QString); - - void indent(); - void setAutoIndent(bool); - void eval(); - private: - void createFileMenu(); - void createEditMenu(); - void createCellMenu(); - void createFormatMenu(); - void createInsertMenu(); - void createWindowMenu(); //Added 2006-01-27 AF - void createAboutMenu(); - - bool cellEditable(); //Added 2005-11-11 AF - void evalCells(); //Added 2006-02-14 AF - //void createSavingTimer(); - - private: - QToolBar* toolBar; - // 2005-10-07 AF, Porting, Added this menus - QMenu *fileMenu; - QMenu *recentMenu; - QMenu *editMenu; - QMenu *cellMenu; - QMenu *formatMenu; - QMenu *insertMenu; // Added 2005-11-18 AF - QMenu *windowMenu; // Added 2006-01-27 AF - QMenu *aboutMenu; - - // 2005-11-03/04/07 AF, Added some more for text setting changes - QMenu *styleMenu; - QMenu *fontMenu; - QMenu *faceMenu; - QMenu *sizeMenu; - QMenu *stretchMenu; - QMenu *colorMenu; - QMenu *alignmentMenu; - QMenu *verticalAlignmentMenu; - QMenu *borderMenu; - QMenu *marginMenu; - QMenu *paddingMenu; - // 2005-12-01 AF, added for import old omnotebook file - QMenu *importMenu; - // 2005-11-21 AF, added for export pure text - QMenu *exportMenu; - - QMenu *indentMenu; - // 2005-10-07 AF, Porting, Added this actions - // 2005-11-03/04/07 AF, Added some more for text setting changes - QActionGroup *stylesgroup; - QActionGroup *fontsgroup; - QActionGroup *sizesgroup; - QActionGroup *stretchsgroup; - QActionGroup *colorsgroup; - QActionGroup *alignmentsgroup; - QActionGroup *verticalAlignmentsgroup; - QActionGroup *bordersgroup; - QActionGroup *marginsgroup; - QActionGroup *paddingsgroup; - - QAction *newAction; - QAction *openFileAction; - QAction *saveAsAction; - QAction *saveAction; - QAction *printAction; // Added 2005-12-19 AF - QAction *closeFileAction; - QAction *quitWindowAction; - QAction *indentAction; - QAction *autoIndentAction; - QAction *evalAction; + // forward declaration + class SearchForm; + + class NotebookWindow : public DocumentView + { + Q_OBJECT + + public: + NotebookWindow(Document *subject, const QString filename=0, + QWidget *parent=0); + virtual ~NotebookWindow(); + + virtual void update(); + virtual Document* document(); + CellApplication *application(); + + public slots: + void updateMenus(); // Added 2005-11-07 AF + void updateStyleMenu(); + void updateEditMenu(); // Added 2005-11-02 AF + void updateCellMenu(); // Added 2006-02-03 AF + void updateFontMenu(); // Added 2005-11-03 AF + void updateFontFaceMenu(); // Added 2005-11-03 AF + void updateFontSizeMenu(); // Added 2005-11-04 AF + void updateFontStretchMenu(); // Added 2005-11-04 AF + void updateFontColorMenu(); // Added 2005-11-07 AF + void updateTextAlignmentMenu(); // Added 2005-11-07 AF + void updateVerticalAlignmentMenu(); // Added 2005-11-07 AF + void updateBorderMenu(); // Added 2005-11-07 AF + void updateMarginMenu(); // Added 2005-11-07 AF + void updatePaddingMenu(); // Added 2005-11-07 AF + void updateWindowMenu(); // Added 2006-01-27 AF + void updateWindowTitle(); // Added 2006-01-17 AF + void updateChapterCounters(); // Added 2006-03-02 AF + void setStatusMessage( QString msg ); // Added 2006-02-10 AF + void forwardedAction( int action ); // Added 2006-04-27 AF + void setPosition(int r, int c); + void setState(QString); + void setStatusMenu(QList); + void recentTriggered(); + protected: + void keyPressEvent(QKeyEvent *event); + void keyReleaseEvent(QKeyEvent *event); + + private slots: + void newFile(); + void openFile(const QString filename=""); + void closeFile(); + void closeEvent( QCloseEvent *event ); // Added 2006-01-19 AF + void aboutQTNotebook(); + void aboutQT(); // Added 2006-02-21 AF + void helpText(); // Added 2006-02-03 AF + void saveas(); + void save(); + void quitOMNotebook(); // Added 2006-01-18 AF + void print(); // Added 2005-12-19 AF + void selectFont(); // Added 2005-11-07 AF + void changeStyle(QAction *action); + void changeStyle(); + void changeFont(QAction *action); // Added 2005-11-03 AF + void changeFontFace(QAction *action); // Added 2005-11-03 AF + void changeFontSize(QAction *action); // Added 2005-11-04 AF + void changeFontStretch(QAction *action); // Added 2005-11-04 AF + void changeFontColor(QAction *action); // Added 2005-11-07 AF + void changeTextAlignment(QAction *action); // Added 2005-11-07 AF + void changeVerticalAlignment(QAction *action); // Added 2005-11-07 AF + void changeBorder(QAction *action); // Added 2005-11-07 AF + void changeMargin(QAction *action); // Added 2005-11-07 AF + void changePadding(QAction *action); // Added 2005-11-07 AF + void changeWindow(QAction *action); // Added 2006-01-27 AF + + void undoEdit(); // Added 2006-02-03 AF + void redoEdit(); // Added 2006-02-03 AF + void cutEdit(); // Added 2006-02-03 AF + void copyEdit(); // Added 2006-02-03 AF + void pasteEdit(); // Added 2006-02-03 AF + void findEdit(); // Added 2006-08-24 AF + void replaceEdit(); // Added 2006-08-24 AF + + void insertImage(); // Added 2005-11-18 AF + void insertLink(); // Added 2005-12-05 AF + void openOldFile(); // Added 2005-12-01 AF + void pureText(); // Added 2005-11-21 AF + + void createNewCell(); + void deleteCurrentCell(); + void cutCell(); + void copyCell(); + void pasteCell(); + void ungroupCell(); // Added 2006-04-26 AF + void splitCell(); // Added 2006-04-26 AF + void moveCursorUp(); + void moveCursorDown(); + void groupCellsAction(); + void inputCellsAction(); + void textCellsAction(); + void updateRecentFiles(QString); + + void indent(); + void setAutoIndent(bool); + void eval(); + private: + void createFileMenu(); + void createEditMenu(); + void createCellMenu(); + void createFormatMenu(); + void createInsertMenu(); + void createWindowMenu(); //Added 2006-01-27 AF + void createAboutMenu(); + + bool cellEditable(); //Added 2005-11-11 AF + void evalCells(); //Added 2006-02-14 AF + //void createSavingTimer(); + + private: + QToolBar* toolBar; + // 2005-10-07 AF, Porting, Added this menus + QMenu *fileMenu; + QMenu *recentMenu; + QMenu *editMenu; + QMenu *cellMenu; + QMenu *formatMenu; + QMenu *insertMenu; // Added 2005-11-18 AF + QMenu *windowMenu; // Added 2006-01-27 AF + QMenu *aboutMenu; + + // 2005-11-03/04/07 AF, Added some more for text setting changes + QMenu *styleMenu; + QMenu *fontMenu; + QMenu *faceMenu; + QMenu *sizeMenu; + QMenu *stretchMenu; + QMenu *colorMenu; + QMenu *alignmentMenu; + QMenu *verticalAlignmentMenu; + QMenu *borderMenu; + QMenu *marginMenu; + QMenu *paddingMenu; + // 2005-12-01 AF, added for import old omnotebook file + QMenu *importMenu; + // 2005-11-21 AF, added for export pure text + QMenu *exportMenu; + + QMenu *indentMenu; + // 2005-10-07 AF, Porting, Added this actions + // 2005-11-03/04/07 AF, Added some more for text setting changes + QActionGroup *stylesgroup; + QActionGroup *fontsgroup; + QActionGroup *sizesgroup; + QActionGroup *stretchsgroup; + QActionGroup *colorsgroup; + QActionGroup *alignmentsgroup; + QActionGroup *verticalAlignmentsgroup; + QActionGroup *bordersgroup; + QActionGroup *marginsgroup; + QActionGroup *paddingsgroup; + + QAction *newAction; + QAction *openFileAction; + QAction *saveAsAction; + QAction *saveAction; + QAction *printAction; // Added 2005-12-19 AF + QAction *closeFileAction; + QAction *quitWindowAction; + QAction *indentAction; + QAction *autoIndentAction; + QAction *evalAction; public: - QAction *undoAction; - QAction *redoAction; - QAction *cutAction; - QAction *copyAction; + QAction *undoAction; + QAction *redoAction; + QAction *cutAction; + QAction *copyAction; private: - QAction *pasteAction; - QAction *findAction; // Changed 2006-08-24 AF - QAction *replaceAction; // Added 2006-08-24 AF - QAction *showExprAction; - - //QAction *cutCellAction; - //QAction *copyCellAction; - //QAction *pasteCellAction; - QAction *addCellAction; - QAction *ungroupCellAction; // Added 2006-04-26 AF - QAction *splitCellAction; // Added 2006-04-26 AF - QAction *deleteCellAction; - QAction *nextCellAction; - QAction *previousCellAction; - - QAction *groupAction; - QAction *inputAction; - QAction *textAction; - - QAction *aboutAction; - QAction *helpAction; // Added 2006-02-03 AF - QAction *aboutQtAction; // Added 2006-02-21 AF - - QAction *facePlain; - QAction *faceBold; - QAction *faceItalic; - QAction *faceUnderline; - - QAction *sizeSmaller; - QAction *sizeLarger; - QAction *size8pt; - QAction *size9pt; - QAction *size10pt; - QAction *size12pt; - QAction *size14pt; - QAction *size16pt; - QAction *size18pt; - QAction *size20pt; - QAction *size24pt; - QAction *size36pt; - QAction *size72pt; - QAction *sizeOther; - - QAction *stretchUltraCondensed; - QAction *stretchExtraCondensed; - QAction *stretchCondensed; - QAction *stretchSemiCondensed; - QAction *stretchUnstretched; - QAction *stretchSemiExpanded; - QAction *stretchExpanded; - QAction *stretchExtraExpanded; - QAction *stretchUltraExpanded; - - QAction *colorBlack; - QAction *colorWhite; - QAction *color10Gray; - QAction *color33Gray; - QAction *color50Gray; - QAction *color66Gray; - QAction *color90Gray; - QAction *colorRed; - QAction *colorGreen; - QAction *colorBlue; - QAction *colorCyan; - QAction *colorMagenta; - QAction *colorYellow; - QAction *colorOther; - - QAction *chooseFont; - - QAction *alignmentLeft; - QAction *alignmentRight; - QAction *alignmentCenter; - QAction *alignmentJustify; - QAction *verticalNormal; - QAction *verticalSub; - QAction *verticalSuper; - - QAction *borderOther; - QAction *marginOther; - QAction *paddingOther; - - QAction *insertImageAction; // Added 2005-11-18 AF - QAction *insertLinkAction; // Added 2005-12-05 AF - QAction *importOldFile; // Added 2005-12-01 AF - QAction *exportPureText; // Added 2005-11-21 AF - - // 2005-11-03/04/07 AF, Added for the new menus (for text changes) - QHash fonts_; - QHash sizes_; - QHash stretchs_; - QHash colors_; - QHash alignments_; - QHash verticals_; - QHash borders_; - QHash margins_; - QHash paddings_; - QHash windows_; - - //Change to Document. - CellApplication *app_; - Document *subject_; - - //list opendocs_; - QString filename_; - - // QTimer *savingTimer_; - map styles_; - - SearchForm* findForm_; // added 2006-08-24 AF - bool closing_; // Added 2006-02-09 AF - - static QString openDir_; // Added 2006-03-01 AF - static QString saveDir_; // Added 2006-03-01 AF - static QString imageDir_; // Added 2006-03-01 AF - static QString linkDir_; // Added 2006-03-01 AF - - QLabel* posIndicator, *stateIndicator; - }; + QAction *pasteAction; + QAction *findAction; // Changed 2006-08-24 AF + QAction *replaceAction; // Added 2006-08-24 AF + QAction *showExprAction; + + //QAction *cutCellAction; + //QAction *copyCellAction; + //QAction *pasteCellAction; + QAction *addCellAction; + QAction *ungroupCellAction; // Added 2006-04-26 AF + QAction *splitCellAction; // Added 2006-04-26 AF + QAction *deleteCellAction; + QAction *nextCellAction; + QAction *previousCellAction; + + QAction *groupAction; + QAction *inputAction; + QAction *textAction; + + QAction *aboutAction; + QAction *helpAction; // Added 2006-02-03 AF + QAction *aboutQtAction; // Added 2006-02-21 AF + + QAction *facePlain; + QAction *faceBold; + QAction *faceItalic; + QAction *faceUnderline; + + QAction *sizeSmaller; + QAction *sizeLarger; + QAction *size8pt; + QAction *size9pt; + QAction *size10pt; + QAction *size12pt; + QAction *size14pt; + QAction *size16pt; + QAction *size18pt; + QAction *size20pt; + QAction *size24pt; + QAction *size36pt; + QAction *size72pt; + QAction *sizeOther; + + QAction *stretchUltraCondensed; + QAction *stretchExtraCondensed; + QAction *stretchCondensed; + QAction *stretchSemiCondensed; + QAction *stretchUnstretched; + QAction *stretchSemiExpanded; + QAction *stretchExpanded; + QAction *stretchExtraExpanded; + QAction *stretchUltraExpanded; + + QAction *colorBlack; + QAction *colorWhite; + QAction *color10Gray; + QAction *color33Gray; + QAction *color50Gray; + QAction *color66Gray; + QAction *color90Gray; + QAction *colorRed; + QAction *colorGreen; + QAction *colorBlue; + QAction *colorCyan; + QAction *colorMagenta; + QAction *colorYellow; + QAction *colorOther; + + QAction *chooseFont; + + QAction *alignmentLeft; + QAction *alignmentRight; + QAction *alignmentCenter; + QAction *alignmentJustify; + QAction *verticalNormal; + QAction *verticalSub; + QAction *verticalSuper; + + QAction *borderOther; + QAction *marginOther; + QAction *paddingOther; + + QAction *insertImageAction; // Added 2005-11-18 AF + QAction *insertLinkAction; // Added 2005-12-05 AF + QAction *importOldFile; // Added 2005-12-01 AF + QAction *exportPureText; // Added 2005-11-21 AF + + // 2005-11-03/04/07 AF, Added for the new menus (for text changes) + QHash fonts_; + QHash sizes_; + QHash stretchs_; + QHash colors_; + QHash alignments_; + QHash verticals_; + QHash borders_; + QHash margins_; + QHash paddings_; + QHash windows_; + + //Change to Document. + CellApplication *app_; + Document *subject_; + + //list opendocs_; + QString filename_; + + // QTimer *savingTimer_; + map styles_; + + SearchForm* findForm_; // added 2006-08-24 AF + bool closing_; // Added 2006-02-09 AF + + static QString openDir_; // Added 2006-03-01 AF + static QString saveDir_; // Added 2006-03-01 AF + static QString imageDir_; // Added 2006-03-01 AF + static QString linkDir_; // Added 2006-03-01 AF + + QLabel* posIndicator, *stateIndicator; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/notebookcommands.h b/OMNotebook/OMNotebookQT4/notebookcommands.h index 92fddbcce7a..d1ee637dd41 100644 --- a/OMNotebook/OMNotebookQT4/notebookcommands.h +++ b/OMNotebook/OMNotebookQT4/notebookcommands.h @@ -163,8 +163,8 @@ namespace IAEX // UTF-8, otherwise swedish letters didn't work. // 2005-10-07 AF, Porting, changed from 'toCString()' // to 'toByteArray()' - // QTextStream filestream(&file); - // QDataStream filestream(&file); + // QTextStream filestream(&file); + // QDataStream filestream(&file); if (file.isOpen()) file.close(); diff --git a/OMNotebook/OMNotebookQT4/notebooksocket.cpp b/OMNotebook/OMNotebookQT4/notebooksocket.cpp index 053c62325fa..394a5e0d25f 100644 --- a/OMNotebook/OMNotebookQT4/notebooksocket.cpp +++ b/OMNotebook/OMNotebookQT4/notebooksocket.cpp @@ -39,7 +39,7 @@ * modified to fit OMNotebook */ -#define IAEX_SOCKET_PORT 7777 +#define IAEX_SOCKET_PORT 7777 // STD Headers #include @@ -59,274 +59,274 @@ using namespace std; namespace IAEX { - /*! - * \class NotebookSocket - * \author Anders Fernström - * \date 2006-05-03 - * + /*! + * \class NotebookSocket + * \author Anders Fernström + * \date 2006-05-03 + * * \brief Handles communication with other instances (processes) - * of the application using tcp sockets. - */ - NotebookSocket::NotebookSocket( CellApplication* application ) - : application_( application ), - server_( 0 ), - foundServer_( false ) - { - socket_ = new QTcpSocket(); - - //connection - connect( socket_, SIGNAL( readyRead() ), - this, SLOT( receiveNewSocketMsg() )); - } - - /*! - * \author Anders Fernström - * \date 2006-05-03 - * - * \brief The class destructor - */ - NotebookSocket::~NotebookSocket() - { - if( socket_ || server_ ) - closeNotebookSocket(); - } - - - // NOTEBOOK SOCKET CORE FUNCTIONS - // ------------------------------------------------------------------ - - /*! - * \author Anders Fernström - * \date 2006-05-03 - * - * \brief Try to connect with other notebook instance, if - * succesfull the function will return true. If unable to - * connect the function trys to start a server (that waits - * for incomming communiction). Returns false if successful - * in setting up the loop. If both attemps fails the function - * throws an exception. - */ - bool NotebookSocket::connectToNotebook() - { - // first try to connect to existing notebook process/application + * of the application using tcp sockets. + */ + NotebookSocket::NotebookSocket( CellApplication* application ) + : application_( application ), + server_( 0 ), + foundServer_( false ) + { + socket_ = new QTcpSocket(); + + //connection + connect( socket_, SIGNAL( readyRead() ), + this, SLOT( receiveNewSocketMsg() )); + } + + /*! + * \author Anders Fernström + * \date 2006-05-03 + * + * \brief The class destructor + */ + NotebookSocket::~NotebookSocket() + { + if( socket_ || server_ ) + closeNotebookSocket(); + } + + + // NOTEBOOK SOCKET CORE FUNCTIONS + // ------------------------------------------------------------------ + + /*! + * \author Anders Fernström + * \date 2006-05-03 + * + * \brief Try to connect with other notebook instance, if + * succesfull the function will return true. If unable to + * connect the function trys to start a server (that waits + * for incomming communiction). Returns false if successful + * in setting up the loop. If both attemps fails the function + * throws an exception. + */ + bool NotebookSocket::connectToNotebook() + { + // first try to connect to existing notebook process/application if( tryToConnect() ) - return true; - - // unable to connect, try to start server - if( startServer() ) - return false; - - // something is wrong, throw exception - throw runtime_error( "Unable to connect OR start server" ); - } - - /*! - * \author Anders Fernström - * \date 2006-05-03 - * - * \brief Closes socket and dose clean up. - */ - bool NotebookSocket::closeNotebookSocket() - { - // socket - if( socket_ ) - { - if( socket_->state() == QAbstractSocket::ConnectedState ) - { - socket_->disconnectFromHost(); - - if( socket_->state() == QAbstractSocket::ConnectedState ) - if( !socket_->waitForDisconnected( 5000 )) - throw runtime_error( "Unable to disconnect socket from host" ); - } - - delete socket_; - socket_ = 0; - } - - // server - if( server_ ) - { - if( server_->isListening() ) - server_->close(); - - delete server_; - server_ = 0; - } - - return true; - } - - /*! - * \author Anders Fernström - * \date 2006-05-03 - * - * \brief Sends a filename to the main/correct process, - * returns true on success - otherwise false - */ - bool NotebookSocket::sendFilename( QString filename ) - { - cout << "sendFilename()" << endl; - - // connected socket to correct server - if( foundServer_ ) - { - QString file = "FILE: " + filename; - if( socket_->write( file.toStdString().c_str(), file.size() ) == -1 ) - { - cout << "[Socket Error] Socket->sendFilename(): " << - socket_->errorString().toStdString() << endl; - return false; - } - - if( !socket_->waitForBytesWritten( 5000 )) - return false; - - // sucess - return true; - } - - throw runtime_error( "Didn't found correct server" ); - } - - - // PRIVATE SLOTS - // ------------------------------------------------------------------ - - /*! - * \author Anders Fernström - * \date 2006-05-03 - * - * \brief Handles incomming connections - */ - void NotebookSocket::receiveNewConnection() - { - if( server_->hasPendingConnections() ) - { - cout << "NotebookSocket: {new Connection}" << endl; - QTcpSocket* socket = server_->nextPendingConnection(); - - // write, ask if OMNNotebook - if( socket->write( "Hello! OMNNotebook?", 25 ) == -1 ) - { - cout << "[Socket Error] Server->receiveNewConnection(): " << - socket->errorString().toStdString() << endl; - return; - } - - // wait and see if receive filepath from socket, if not - // asume that it isn't correct notebook. - socket->waitForBytesWritten( 5000 ); - if( socket->waitForReadyRead( 8000 )) - { - // read socket data - QByteArray msg = socket->readAll(); - QString filename( msg ); - - // check if correkt data - if( filename.startsWith( "FILE: " )) - { - // exstract filename - filename = filename.mid( 6, filename.size() - 6 ); - cout << "Received filename: <" << filename.toStdString() << ">" << endl; - - // tell applicaiton to open filename - application_->open( filename ); - } - else - cout << "[Socket Error] Server->receiveNewConnection(): " << - "Received wrong message." << endl; - } - else - cout << "[Socket Error] Server->receiveNewConnection(): " << - "Didn't receive any message." << endl; - - // close socket - socket->close(); - delete socket; - } - } - - /*! - * \author Anders Fernström - * \date 2006-05-03 - * - * \brief Handles incomming messages - */ - void NotebookSocket::receiveNewSocketMsg() - { - cout << "Socket: Recive new message" << endl; - if( socket_ ) - { - QByteArray msg = socket_->readAll(); - cout << "Message: <" << msg.data() << ">" << endl; - - if( string( msg.data() ) == string( "Hello! OMNNotebook?" )) - foundServer_ = true; - else - cout << "Received worng message." << endl; - } - } - - - // HELP FUNCTIONS - // ------------------------------------------------------------------ - - /*! - * \author Anders Fernström - * \date 2006-05-03 - * - * \brief Trys to connect with another notebook process and recive a - * message from that process, returns true if successful - otherwise - * false. - */ - bool NotebookSocket::tryToConnect() - { - // try to connect - socket_->connectToHost( QHostAddress::LocalHost, IAEX_SOCKET_PORT ); - if( socket_->waitForConnected( 100 )) - { - if( !socket_->waitForReadyRead( 5000 )) - { - cout << "[Socket Error] tryToConnect(): Didn't recevie any message" << endl; - return false; - } - - // success - return true; - } - - // unable to connect - socket_->disconnectFromHost(); - return false; - } - - /*! - * \author Anders Fernström - * \date 2006-05-03 - * - * \brief Trys to setup a server, returns true if successful - - * otherwise false. - */ - bool NotebookSocket::startServer() - { - // setup server - server_ = new QTcpServer(); - server_->setMaxPendingConnections( 5 ); - - // connect server - connect( server_, SIGNAL( newConnection() ), - this, SLOT( receiveNewConnection() )); - - // listen - if( !server_->listen( QHostAddress::LocalHost, IAEX_SOCKET_PORT ) ) - { - cout << "[Socket Error] Server->listen(): " << server_->errorString().toStdString() << endl; - return false; - } - - // success - return true; - } + return true; + + // unable to connect, try to start server + if( startServer() ) + return false; + + // something is wrong, throw exception + throw runtime_error( "Unable to connect OR start server" ); + } + + /*! + * \author Anders Fernström + * \date 2006-05-03 + * + * \brief Closes socket and dose clean up. + */ + bool NotebookSocket::closeNotebookSocket() + { + // socket + if( socket_ ) + { + if( socket_->state() == QAbstractSocket::ConnectedState ) + { + socket_->disconnectFromHost(); + + if( socket_->state() == QAbstractSocket::ConnectedState ) + if( !socket_->waitForDisconnected( 5000 )) + throw runtime_error( "Unable to disconnect socket from host" ); + } + + delete socket_; + socket_ = 0; + } + + // server + if( server_ ) + { + if( server_->isListening() ) + server_->close(); + + delete server_; + server_ = 0; + } + + return true; + } + + /*! + * \author Anders Fernström + * \date 2006-05-03 + * + * \brief Sends a filename to the main/correct process, + * returns true on success - otherwise false + */ + bool NotebookSocket::sendFilename( QString filename ) + { + cout << "sendFilename()" << endl; + + // connected socket to correct server + if( foundServer_ ) + { + QString file = "FILE: " + filename; + if( socket_->write( file.toStdString().c_str(), file.size() ) == -1 ) + { + cout << "[Socket Error] Socket->sendFilename(): " << + socket_->errorString().toStdString() << endl; + return false; + } + + if( !socket_->waitForBytesWritten( 5000 )) + return false; + + // sucess + return true; + } + + throw runtime_error( "Didn't found correct server" ); + } + + + // PRIVATE SLOTS + // ------------------------------------------------------------------ + + /*! + * \author Anders Fernström + * \date 2006-05-03 + * + * \brief Handles incomming connections + */ + void NotebookSocket::receiveNewConnection() + { + if( server_->hasPendingConnections() ) + { + cout << "NotebookSocket: {new Connection}" << endl; + QTcpSocket* socket = server_->nextPendingConnection(); + + // write, ask if OMNNotebook + if( socket->write( "Hello! OMNNotebook?", 25 ) == -1 ) + { + cout << "[Socket Error] Server->receiveNewConnection(): " << + socket->errorString().toStdString() << endl; + return; + } + + // wait and see if receive filepath from socket, if not + // asume that it isn't correct notebook. + socket->waitForBytesWritten( 5000 ); + if( socket->waitForReadyRead( 8000 )) + { + // read socket data + QByteArray msg = socket->readAll(); + QString filename( msg ); + + // check if correkt data + if( filename.startsWith( "FILE: " )) + { + // exstract filename + filename = filename.mid( 6, filename.size() - 6 ); + cout << "Received filename: <" << filename.toStdString() << ">" << endl; + + // tell applicaiton to open filename + application_->open( filename ); + } + else + cout << "[Socket Error] Server->receiveNewConnection(): " << + "Received wrong message." << endl; + } + else + cout << "[Socket Error] Server->receiveNewConnection(): " << + "Didn't receive any message." << endl; + + // close socket + socket->close(); + delete socket; + } + } + + /*! + * \author Anders Fernström + * \date 2006-05-03 + * + * \brief Handles incomming messages + */ + void NotebookSocket::receiveNewSocketMsg() + { + cout << "Socket: Recive new message" << endl; + if( socket_ ) + { + QByteArray msg = socket_->readAll(); + cout << "Message: <" << msg.data() << ">" << endl; + + if( string( msg.data() ) == string( "Hello! OMNNotebook?" )) + foundServer_ = true; + else + cout << "Received worng message." << endl; + } + } + + + // HELP FUNCTIONS + // ------------------------------------------------------------------ + + /*! + * \author Anders Fernström + * \date 2006-05-03 + * + * \brief Trys to connect with another notebook process and recive a + * message from that process, returns true if successful - otherwise + * false. + */ + bool NotebookSocket::tryToConnect() + { + // try to connect + socket_->connectToHost( QHostAddress::LocalHost, IAEX_SOCKET_PORT ); + if( socket_->waitForConnected( 100 )) + { + if( !socket_->waitForReadyRead( 5000 )) + { + cout << "[Socket Error] tryToConnect(): Didn't recevie any message" << endl; + return false; + } + + // success + return true; + } + + // unable to connect + socket_->disconnectFromHost(); + return false; + } + + /*! + * \author Anders Fernström + * \date 2006-05-03 + * + * \brief Trys to setup a server, returns true if successful - + * otherwise false. + */ + bool NotebookSocket::startServer() + { + // setup server + server_ = new QTcpServer(); + server_->setMaxPendingConnections( 5 ); + + // connect server + connect( server_, SIGNAL( newConnection() ), + this, SLOT( receiveNewConnection() )); + + // listen + if( !server_->listen( QHostAddress::LocalHost, IAEX_SOCKET_PORT ) ) + { + cout << "[Socket Error] Server->listen(): " << server_->errorString().toStdString() << endl; + return false; + } + + // success + return true; + } } diff --git a/OMNotebook/OMNotebookQT4/notebooksocket.h b/OMNotebook/OMNotebookQT4/notebooksocket.h index 4773321a075..7b2e53f7e8d 100644 --- a/OMNotebook/OMNotebookQT4/notebooksocket.h +++ b/OMNotebook/OMNotebookQT4/notebooksocket.h @@ -54,42 +54,42 @@ class QTcpSocket; namespace IAEX { - // forward declaration - class CellApplication; + // forward declaration + class CellApplication; - class NotebookSocket : public QObject - { - Q_OBJECT + class NotebookSocket : public QObject + { + Q_OBJECT - public: - NotebookSocket( CellApplication* application ); - ~NotebookSocket(); + public: + NotebookSocket( CellApplication* application ); + ~NotebookSocket(); - // core functions - bool connectToNotebook(); - bool closeNotebookSocket(); - bool sendFilename( QString filename ); + // core functions + bool connectToNotebook(); + bool closeNotebookSocket(); + bool sendFilename( QString filename ); - private slots: - void receiveNewConnection(); - void receiveNewSocketMsg(); + private slots: + void receiveNewConnection(); + void receiveNewSocketMsg(); - private: - // help function - bool tryToConnect(); - bool startServer(); + private: + // help function + bool tryToConnect(); + bool startServer(); - private: - CellApplication* application_; + private: + CellApplication* application_; - QTcpSocket* socket_; - QTcpSocket* incommingSocket_; - QTcpServer* server_; + QTcpSocket* socket_; + QTcpSocket* incommingSocket_; + QTcpServer* server_; - bool foundServer_; - }; + bool foundServer_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/omc_communicator.cpp b/OMNotebook/OMNotebookQT4/omc_communicator.cpp index 3bc91b61cf9..16e8a4b93aa 100644 --- a/OMNotebook/OMNotebookQT4/omc_communicator.cpp +++ b/OMNotebook/OMNotebookQT4/omc_communicator.cpp @@ -159,7 +159,7 @@ bool OmcCommunicator::establishConnection() // } -#else // UNIX environment +#else // UNIX environment char *user = getenv("USER"); if (!user) { user = "nobody"; } @@ -322,7 +322,7 @@ QString OmcCommunicator::callOmc(const QString& fnCall) */ // bool ModeqCommunicator::loadClass(const QString& ref) // { -// QString fnCall("loadModel(" + ref + ")"); +// QString fnCall("loadModel(" + ref + ")"); // QString returnString(callModeq(fnCall)); // if (returnString == "true") { @@ -353,27 +353,27 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::createConnector(const QString& ref, -// const QStringList& baseClassRefs, -// const QString& comment, -// bool encapsulated, -// bool partial) +// const QStringList& baseClassRefs, +// const QString& comment, +// bool encapsulated, +// bool partial) // { -// QString name(ModelicaClassManager::getName(ref)); -// QString parentClassRef(ModelicaClassManager::getPath(ref)); - -// QString fnCall(!parentClassRef.isEmpty() ? "within " + parentClassRef + "; " : ""); -// fnCall += -// QString((encapsulated ? "encapsulated " : "")) + -// QString((partial ? "partial " : "")) + "connector " + name + " \"" + comment + "\""; -// for (QStringList::const_iterator it = baseClassRefs.begin(); it != baseClassRefs.end(); ++it) { -// fnCall += " extends " + *it + ";"; -// } -// fnCall += " end " + name + ";"; -// QString returnString(callModeq(fnCall)); - -// if (returnString.lower() != "ok") { -// throw ModeqError(fnCall, returnString); -// } +// QString name(ModelicaClassManager::getName(ref)); +// QString parentClassRef(ModelicaClassManager::getPath(ref)); + +// QString fnCall(!parentClassRef.isEmpty() ? "within " + parentClassRef + "; " : ""); +// fnCall += +// QString((encapsulated ? "encapsulated " : "")) + +// QString((partial ? "partial " : "")) + "connector " + name + " \"" + comment + "\""; +// for (QStringList::const_iterator it = baseClassRefs.begin(); it != baseClassRefs.end(); ++it) { +// fnCall += " extends " + *it + ";"; +// } +// fnCall += " end " + name + ";"; +// QString returnString(callModeq(fnCall)); + +// if (returnString.lower() != "ok") { +// throw ModeqError(fnCall, returnString); +// } // } /** @@ -381,13 +381,13 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::createModel(const QString& ref, -// const QStringList& baseClassRefs, -// const QString& comment, -// bool encapsulated, -// bool partial) +// const QStringList& baseClassRefs, +// const QString& comment, +// bool encapsulated, +// bool partial) // { -// QString name(ModelicaClassManager::getName(ref)); -// QString parentClassRef(ModelicaClassManager::getPath(ref)); +// QString name(ModelicaClassManager::getName(ref)); +// QString parentClassRef(ModelicaClassManager::getPath(ref)); // QString fnCall(!parentClassRef.isEmpty() ? "within " + parentClassRef + "; " : ""); // fnCall += @@ -409,13 +409,13 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::createBlock(const QString& ref, -// const QStringList& baseClassRefs, -// const QString& comment, -// bool encapsulated, -// bool partial) +// const QStringList& baseClassRefs, +// const QString& comment, +// bool encapsulated, +// bool partial) // { -// QString name(ModelicaClassManager::getName(ref)); -// QString parentClassRef(ModelicaClassManager::getPath(ref)); +// QString name(ModelicaClassManager::getName(ref)); +// QString parentClassRef(ModelicaClassManager::getPath(ref)); // QString fnCall(!parentClassRef.isEmpty() ? "within " + parentClassRef + "; " : ""); // fnCall += @@ -438,13 +438,13 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::createRecord(const QString& ref, -// const QStringList& baseClassRefs, -// const QString& comment, -// bool encapsulated, -// bool partial) +// const QStringList& baseClassRefs, +// const QString& comment, +// bool encapsulated, +// bool partial) // { -// QString name(ModelicaClassManager::getName(ref)); -// QString parentClassRef(ModelicaClassManager::getPath(ref)); +// QString name(ModelicaClassManager::getName(ref)); +// QString parentClassRef(ModelicaClassManager::getPath(ref)); // QString fnCall(!parentClassRef.isEmpty() ? "within " + parentClassRef + "; " : ""); // fnCall += @@ -467,13 +467,13 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::createFunction(const QString& ref, -// const QStringList& baseClassRefs, -// const QString& comment, -// bool encapsulated, -// bool partial) +// const QStringList& baseClassRefs, +// const QString& comment, +// bool encapsulated, +// bool partial) // { -// QString name(ModelicaClassManager::getName(ref)); -// QString parentClassRef(ModelicaClassManager::getPath(ref)); +// QString name(ModelicaClassManager::getName(ref)); +// QString parentClassRef(ModelicaClassManager::getPath(ref)); // QString fnCall(!parentClassRef.isEmpty() ? "within " + parentClassRef + "; " : ""); // fnCall += @@ -496,13 +496,13 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::createPackage(const QString& ref, -// const QStringList& baseClassRefs, -// const QString& comment, -// bool encapsulated, -// bool partial) +// const QStringList& baseClassRefs, +// const QString& comment, +// bool encapsulated, +// bool partial) // { -// QString name(ModelicaClassManager::getName(ref)); -// QString parentClassRef(ModelicaClassManager::getPath(ref)); +// QString name(ModelicaClassManager::getName(ref)); +// QString parentClassRef(ModelicaClassManager::getPath(ref)); // QString fnCall(!parentClassRef.isEmpty() ? "within " + parentClassRef + "; " : ""); // fnCall += @@ -744,12 +744,12 @@ QString OmcCommunicator::callOmc(const QString& fnCall) */ // bool ModeqCommunicator::isPrimitive(const QString& ref) // { -// // Real and Integer are known primitives. No need to ask Modeq. -// if (ref == "Real" || ref == "Integer") { -// return true; -// } +// // Real and Integer are known primitives. No need to ask Modeq. +// if (ref == "Real" || ref == "Integer") { +// return true; +// } -// QString fnCall("isPrimitive(" + ref + ")"); +// QString fnCall("isPrimitive(" + ref + ")"); // QString returnString(callModeq(fnCall)); // if (returnString == "false") { @@ -774,8 +774,8 @@ QString OmcCommunicator::callOmc(const QString& fnCall) // QString fnCall("getClassNames(" + ref + ")"); // QString list(callModeq(fnCall)); -// // Remove the surrounding braces before returning the list. -// return list.mid(1, list.length() - 2); +// // Remove the surrounding braces before returning the list. +// return list.mid(1, list.length() - 2); // } /** @@ -882,9 +882,9 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::addComponent(const QString& name, -// const QString& type, -// const QString& ref, -// const QString& annotation) +// const QString& type, +// const QString& ref, +// const QString& annotation) // { // QString fnCall; // if (annotation.isEmpty()) { @@ -904,21 +904,21 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::updateComponent(const QString& name, -// const QString& type, -// const QString& ref, -// const QString& comment, -// const QString& annotation) +// const QString& type, +// const QString& ref, +// const QString& comment, +// const QString& annotation) // { -// QString temporaryComment(comment); -// temporaryComment.replace("\\", "\\\\").replace("\"", "\\\""); +// QString temporaryComment(comment); +// temporaryComment.replace("\\", "\\\\").replace("\"", "\\\""); -// QString fnCall; +// QString fnCall; // if (annotation.isEmpty()) { // fnCall = "updateComponent(" + name + "," + type + "," + ref + -// ", comment=\"" + temporaryComment + "\")"; +// ", comment=\"" + temporaryComment + "\")"; // } else { // fnCall = "updateComponent(" + name + "," + type + "," + ref + -// ", comment=\"" + temporaryComment + "\",annotate=" + annotation + ")"; +// ", comment=\"" + temporaryComment + "\",annotate=" + annotation + ")"; // } // QString returnString(callModeq(fnCall)); @@ -1000,45 +1000,45 @@ QString OmcCommunicator::callOmc(const QString& fnCall) // std::vector ModeqCommunicator::getComponents(const QString& ref) // { // QString fnCall("getComponents(" + ref + ")"); -// QString returnString(callModeq(fnCall)); - -// std::vector componentDeclarations; -// if (returnString == "{{}}") return componentDeclarations; - -// // Remove surrounding braces. -// QString componentList(returnString.mid(1, returnString.length() - 2)); - -// // Extract each component from the list of components returned from Modeq. -// while (!componentList.isEmpty()) -// { -// int i; - -// // Extract the type. -// i = componentList.find(','); -// if (i == -1) throw ModeqError(fnCall, returnString); // Parse error. -// QString type(componentList.mid(1, i - 1).stripWhiteSpace()); -// componentList = componentList.remove(0, i + 1).stripWhiteSpace(); - -// // Extract the name. -// i = componentList.find(','); -// if (i == -1) throw ModeqError(fnCall, returnString); // Parse error. -// QString name(componentList.left(i).stripWhiteSpace()); -// componentList = componentList.remove(0, i + 1).stripWhiteSpace(); - -// // Extract the comment. -// i = 0; -// do { -// i = componentList.find('"', i + 1); -// } while (componentList.at(i - 1) == '\\'); -// QString comment(componentList.mid(1, i - 1)); -// comment.replace("\\\"", "\"").replace("\\\\", "\\"); -// componentList = componentList.remove(0, i + 3).stripWhiteSpace(); - -// // Create declaration record. -// componentDeclarations.push_back(ComponentDeclaration(type, name, comment)); -// } - -// return componentDeclarations; +// QString returnString(callModeq(fnCall)); + +// std::vector componentDeclarations; +// if (returnString == "{{}}") return componentDeclarations; + +// // Remove surrounding braces. +// QString componentList(returnString.mid(1, returnString.length() - 2)); + +// // Extract each component from the list of components returned from Modeq. +// while (!componentList.isEmpty()) +// { +// int i; + +// // Extract the type. +// i = componentList.find(','); +// if (i == -1) throw ModeqError(fnCall, returnString); // Parse error. +// QString type(componentList.mid(1, i - 1).stripWhiteSpace()); +// componentList = componentList.remove(0, i + 1).stripWhiteSpace(); + +// // Extract the name. +// i = componentList.find(','); +// if (i == -1) throw ModeqError(fnCall, returnString); // Parse error. +// QString name(componentList.left(i).stripWhiteSpace()); +// componentList = componentList.remove(0, i + 1).stripWhiteSpace(); + +// // Extract the comment. +// i = 0; +// do { +// i = componentList.find('"', i + 1); +// } while (componentList.at(i - 1) == '\\'); +// QString comment(componentList.mid(1, i - 1)); +// comment.replace("\\\"", "\"").replace("\\\\", "\\"); +// componentList = componentList.remove(0, i + 3).stripWhiteSpace(); + +// // Create declaration record. +// componentDeclarations.push_back(ComponentDeclaration(type, name, comment)); +// } + +// return componentDeclarations; // } /** @@ -1058,39 +1058,39 @@ QString OmcCommunicator::callOmc(const QString& fnCall) // std::vector ModeqCommunicator::getComponentAnnotations(const QString& ref) // { // QString fnCall("getComponentAnnotations(" + ref + ")"); -// QString returnString(callModeq(fnCall)); - -// std::vector componentAnnotations; - -// // Remove surrounding braces. -// QString annotationList(returnString.mid(1, returnString.length() - 2)); - -// // Remove any whitespace in the string to simplify the extraction of annotations. -// annotationList = annotationList.remove(' '); -// while (!annotationList.isEmpty()) { -// if (annotationList.startsWith("{}")) { -// componentAnnotations.push_back(0); -// annotationList = annotationList.remove(0, 3); -// } else { -// int i(annotationList.find('}')); -// QString annotation(annotationList.mid(0, i + 1)); -// annotationList = annotationList.remove(0, i + 2); -// try { -// componentAnnotations.push_back(compiler_->compilePlacementAnnotation(annotation.latin1())); -// } catch (SyntaxError&) { -// // compilePlacementAnnotation never throws SyntaxError as modeq returns {} if a component has a invalid annotation -// qWarning(QString("[Internal Error] ModeqCommunicator::getComponentAnnotations():\n") + -// "Parsing of placement annotation failed. The annotation is ignored.\n"); -// QMessageBox::critical(0, tr("Modelica Kernel Error"), -// tr(QString("A function call to the Modelica kernel failed.

") + -// "The editor and kernel might be in an inconsistent state.
Please restart the editor.")); - -// componentAnnotations.push_back(0); -// } -// } -// } - -// return componentAnnotations; +// QString returnString(callModeq(fnCall)); + +// std::vector componentAnnotations; + +// // Remove surrounding braces. +// QString annotationList(returnString.mid(1, returnString.length() - 2)); + +// // Remove any whitespace in the string to simplify the extraction of annotations. +// annotationList = annotationList.remove(' '); +// while (!annotationList.isEmpty()) { +// if (annotationList.startsWith("{}")) { +// componentAnnotations.push_back(0); +// annotationList = annotationList.remove(0, 3); +// } else { +// int i(annotationList.find('}')); +// QString annotation(annotationList.mid(0, i + 1)); +// annotationList = annotationList.remove(0, i + 2); +// try { +// componentAnnotations.push_back(compiler_->compilePlacementAnnotation(annotation.latin1())); +// } catch (SyntaxError&) { +// // compilePlacementAnnotation never throws SyntaxError as modeq returns {} if a component has a invalid annotation +// qWarning(QString("[Internal Error] ModeqCommunicator::getComponentAnnotations():\n") + +// "Parsing of placement annotation failed. The annotation is ignored.\n"); +// QMessageBox::critical(0, tr("Modelica Kernel Error"), +// tr(QString("
A function call to the Modelica kernel failed.

") + +// "The editor and kernel might be in an inconsistent state.
Please restart the editor.")); + +// componentAnnotations.push_back(0); +// } +// } +// } + +// return componentAnnotations; // } /** @@ -1109,151 +1109,151 @@ QString OmcCommunicator::callOmc(const QString& fnCall) */ // Modification* ModeqCommunicator::getNthComponentModification(const QString& ref, int index, const QString& name) // { -// QString fnCall("getNthComponentModification(" + ref + "," + QString::number(index) + ")"); -// QString returnString(callModeq(fnCall)); - -// std::vector modifiers; - -// if (returnString == "{Code()}") return 0; - -// // Remove enclosing {Code()}. -// returnString = returnString.mid(6, returnString.length() - 8).stripWhiteSpace(); -// QString modificationString = returnString; -// // qDebug(returnString); -// // qDebug("MODIFICATION: " + modificationString); - -// // = ? -// if (modificationString.startsWith("=")) { -// QString value(modificationString.mid(1)); -// modifiers.push_back(new ComponentModifier("", value)); -// // qDebug(">>> =" + value); -// // qDebug(""); -// return new Modification(name, returnString, modifiers); -// } -// // := ? -// else if (modificationString.startsWith(":=")) { -// QString value(modificationString.mid(2)); -// modifiers.push_back(new ComponentModifier("", value)); -// // qDebug(">>> =" + value); -// // qDebug(""); -// return new Modification(name, returnString, modifiers); -// } else { -// if( modificationString.startsWith("(") && modificationString.endsWith(")") ) -// { -// // Remove surrounding () -// modificationString = modificationString.mid(1, modificationString.length() - 2); -// } - -// } - -// // Redclaration? -// if (modificationString.startsWith("redeclare")) { -// // Skip modifier -// int pDepth(0); -// while (!modificationString.isEmpty()) { -// if (modificationString.startsWith("(")) { -// ++pDepth; -// } else if (modificationString.startsWith(")")) { -// --pDepth; -// } else if (modificationString.startsWith(",") && pDepth == 0) { -// modificationString = modificationString.remove(0, 1).stripWhiteSpace(); -// break; -// } -// modificationString = modificationString.remove(0, 1); -// } -// } -// // Modification. -// else { -// QString componentReference(""); -// QString value(""); - -// while (!modificationString.isEmpty()) { -// // Remove any occurence of each and final. -// while (true) { -// if (modificationString.startsWith("each")) { -// modificationString = modificationString.remove(0,4).stripWhiteSpace(); -// } else if (modificationString.startsWith("final")) { -// modificationString = modificationString.remove(0,5).stripWhiteSpace(); -// } else { -// break; -// } -// } -// int pDepth(0); - -// // Take care of the case (unit="m")=2, (unit="m") is removed -// if( modificationString.startsWith("(") && !modificationString.endsWith(")") ){ - -// while(!modificationString.isEmpty()) -// { -// if (modificationString.startsWith("(")) { ++pDepth; } -// else if (modificationString.startsWith(")")) { --pDepth; } -// else if( modificationString.startsWith("=") && pDepth == 0 ) -// { -// break; -// } -// modificationString = modificationString.remove(0, 1); -// } - -// pDepth = 0; -// } - -// while (!modificationString.isEmpty()) { -// if (modificationString.startsWith("(")) { ++pDepth; } -// else if (modificationString.startsWith(")")) { --pDepth; } -// else if (modificationString.startsWith("=") && pDepth == 0) { -// int bDepth(0), btDepth(0); -// modificationString = modificationString.mid(1).stripWhiteSpace(); -// while (true) { -// // Last modifier? (No comma found). -// if (modificationString.isEmpty()) { -// break; -// } -// else if (modificationString.startsWith("(")) { ++pDepth; } -// else if (modificationString.startsWith(")")) { --pDepth; } -// else if (modificationString.startsWith("{")) { ++bDepth; } -// else if (modificationString.startsWith("}")) { --bDepth; } -// else if (modificationString.startsWith("[")) { ++btDepth; } -// else if (modificationString.startsWith("]")) { --btDepth; } -// else if (modificationString.startsWith(",") && pDepth == 0 && bDepth == 0 && btDepth == 0) { -// modificationString = modificationString.mid(1).stripWhiteSpace(); -// break; -// } -// value += modificationString.at(0); -// modificationString = modificationString.remove(0, 1); -// } -// break; -// } - -// componentReference += modificationString.at(0); -// modificationString = modificationString.remove(0, 1); -// } - -// // Remove any colon at the end of the component reference (happens when := is used). -// if (componentReference.endsWith(":")) { -// componentReference = componentReference.left(componentReference.length() - 1); -// } - -// // Remove any inner modifications from the component reference. -// int i(componentReference.find('(')); -// if (i > 0) { -// componentReference = componentReference.left(i); -// } - -// // Do not store any deep modifiers. -// if (componentReference.find('.') > 0) { -// continue; -// } -// modifiers.push_back(new ComponentModifier(componentReference, value)); - -// // qDebug(">>> " + componentReference + "=" + value); -// // qDebug(modificationString); -// componentReference = ""; -// value = ""; -// } - -// } - -// return new Modification(name, returnString, modifiers); +// QString fnCall("getNthComponentModification(" + ref + "," + QString::number(index) + ")"); +// QString returnString(callModeq(fnCall)); + +// std::vector modifiers; + +// if (returnString == "{Code()}") return 0; + +// // Remove enclosing {Code()}. +// returnString = returnString.mid(6, returnString.length() - 8).stripWhiteSpace(); +// QString modificationString = returnString; +// // qDebug(returnString); +// // qDebug("MODIFICATION: " + modificationString); + +// // = ? +// if (modificationString.startsWith("=")) { +// QString value(modificationString.mid(1)); +// modifiers.push_back(new ComponentModifier("", value)); +// // qDebug(">>> =" + value); +// // qDebug(""); +// return new Modification(name, returnString, modifiers); +// } +// // := ? +// else if (modificationString.startsWith(":=")) { +// QString value(modificationString.mid(2)); +// modifiers.push_back(new ComponentModifier("", value)); +// // qDebug(">>> =" + value); +// // qDebug(""); +// return new Modification(name, returnString, modifiers); +// } else { +// if( modificationString.startsWith("(") && modificationString.endsWith(")") ) +// { +// // Remove surrounding () +// modificationString = modificationString.mid(1, modificationString.length() - 2); +// } + +// } + +// // Redclaration? +// if (modificationString.startsWith("redeclare")) { +// // Skip modifier +// int pDepth(0); +// while (!modificationString.isEmpty()) { +// if (modificationString.startsWith("(")) { +// ++pDepth; +// } else if (modificationString.startsWith(")")) { +// --pDepth; +// } else if (modificationString.startsWith(",") && pDepth == 0) { +// modificationString = modificationString.remove(0, 1).stripWhiteSpace(); +// break; +// } +// modificationString = modificationString.remove(0, 1); +// } +// } +// // Modification. +// else { +// QString componentReference(""); +// QString value(""); + +// while (!modificationString.isEmpty()) { +// // Remove any occurence of each and final. +// while (true) { +// if (modificationString.startsWith("each")) { +// modificationString = modificationString.remove(0,4).stripWhiteSpace(); +// } else if (modificationString.startsWith("final")) { +// modificationString = modificationString.remove(0,5).stripWhiteSpace(); +// } else { +// break; +// } +// } +// int pDepth(0); + +// // Take care of the case (unit="m")=2, (unit="m") is removed +// if( modificationString.startsWith("(") && !modificationString.endsWith(")") ){ + +// while(!modificationString.isEmpty()) +// { +// if (modificationString.startsWith("(")) { ++pDepth; } +// else if (modificationString.startsWith(")")) { --pDepth; } +// else if( modificationString.startsWith("=") && pDepth == 0 ) +// { +// break; +// } +// modificationString = modificationString.remove(0, 1); +// } + +// pDepth = 0; +// } + +// while (!modificationString.isEmpty()) { +// if (modificationString.startsWith("(")) { ++pDepth; } +// else if (modificationString.startsWith(")")) { --pDepth; } +// else if (modificationString.startsWith("=") && pDepth == 0) { +// int bDepth(0), btDepth(0); +// modificationString = modificationString.mid(1).stripWhiteSpace(); +// while (true) { +// // Last modifier? (No comma found). +// if (modificationString.isEmpty()) { +// break; +// } +// else if (modificationString.startsWith("(")) { ++pDepth; } +// else if (modificationString.startsWith(")")) { --pDepth; } +// else if (modificationString.startsWith("{")) { ++bDepth; } +// else if (modificationString.startsWith("}")) { --bDepth; } +// else if (modificationString.startsWith("[")) { ++btDepth; } +// else if (modificationString.startsWith("]")) { --btDepth; } +// else if (modificationString.startsWith(",") && pDepth == 0 && bDepth == 0 && btDepth == 0) { +// modificationString = modificationString.mid(1).stripWhiteSpace(); +// break; +// } +// value += modificationString.at(0); +// modificationString = modificationString.remove(0, 1); +// } +// break; +// } + +// componentReference += modificationString.at(0); +// modificationString = modificationString.remove(0, 1); +// } + +// // Remove any colon at the end of the component reference (happens when := is used). +// if (componentReference.endsWith(":")) { +// componentReference = componentReference.left(componentReference.length() - 1); +// } + +// // Remove any inner modifications from the component reference. +// int i(componentReference.find('(')); +// if (i > 0) { +// componentReference = componentReference.left(i); +// } + +// // Do not store any deep modifiers. +// if (componentReference.find('.') > 0) { +// continue; +// } +// modifiers.push_back(new ComponentModifier(componentReference, value)); + +// // qDebug(">>> " + componentReference + "=" + value); +// // qDebug(modificationString); +// componentReference = ""; +// value = ""; +// } + +// } + +// return new Modification(name, returnString, modifiers); // } /** @@ -1261,9 +1261,9 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::addConnection(const QString& sourceConnectorRef, -// const QString& destinationConnectorRef, -// const QString& ref, -// const QString& annotation) +// const QString& destinationConnectorRef, +// const QString& ref, +// const QString& annotation) // { // QString fnCall = "addConnection(" + sourceConnectorRef + "," + destinationConnectorRef + "," + // ref + "," + annotation + ")"; @@ -1279,9 +1279,9 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::updateConnection(const QString& sourceConnectorRef, -// const QString& destinationConnectorRef, -// const QString& ref, -// const QString& annotation) +// const QString& destinationConnectorRef, +// const QString& ref, +// const QString& annotation) // { // QString fnCall = "updateConnection(" + sourceConnectorRef + "," + destinationConnectorRef + "," + // ref + "," + annotation + ")"; @@ -1297,8 +1297,8 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \throw ModeqConnectionLost if the connection to Modeq is lost. */ // void ModeqCommunicator::deleteConnection(const QString& sourceConnectorRef, -// const QString& destinationConnectorRef, -// const QString& ref) +// const QString& destinationConnectorRef, +// const QString& ref) // { // QString fnCall("deleteConnection(" + sourceConnectorRef + "," + destinationConnectorRef + "," + ref + ")"); // QString returnString(callModeq(fnCall)); @@ -1410,18 +1410,18 @@ QString OmcCommunicator::callOmc(const QString& fnCall) * \see ModelicaClassManager::setClassDefinition() */ // void ModeqCommunicator::updateClassDefinition(const QString& ref, -// const QString& definition) +// const QString& definition) // { -// QString fnCall; -// if (!ModelicaClassManager::getPath(ref).isEmpty()) { -// fnCall += "within " + ModelicaClassManager::getPath(ref) + "; "; -// } -// fnCall += definition; +// QString fnCall; +// if (!ModelicaClassManager::getPath(ref).isEmpty()) { +// fnCall += "within " + ModelicaClassManager::getPath(ref) + "; "; +// } +// fnCall += definition; // QString returnString(callModeq(fnCall)); -// if (returnString != "Ok") { -// throw SyntaxError(returnString); -// } +// if (returnString != "Ok") { +// throw SyntaxError(returnString); +// } // } diff --git a/OMNotebook/OMNotebookQT4/omcinteractiveenvironment.h b/OMNotebook/OMNotebookQT4/omcinteractiveenvironment.h index de75d693365..f9d0ba13b06 100644 --- a/OMNotebook/OMNotebookQT4/omcinteractiveenvironment.h +++ b/OMNotebook/OMNotebookQT4/omcinteractiveenvironment.h @@ -40,29 +40,29 @@ namespace IAEX { - class OmcInteractiveEnvironment : public InputCellDelegate - { + class OmcInteractiveEnvironment : public InputCellDelegate + { private: - OmcInteractiveEnvironment(); - virtual ~OmcInteractiveEnvironment(); + OmcInteractiveEnvironment(); + virtual ~OmcInteractiveEnvironment(); public: static OmcInteractiveEnvironment* getInstance(); - virtual QString getResult(); - virtual QString getError(); - virtual void evalExpression(const QString expr); - virtual void closeConnection(); - virtual void reconnect(); - virtual bool startDelegate(); - static bool startOMC(); - static QString OMCVersion(); + virtual QString getResult(); + virtual QString getError(); + virtual void evalExpression(const QString expr); + virtual void closeConnection(); + virtual void reconnect(); + virtual bool startDelegate(); + static bool startOMC(); + static QString OMCVersion(); static QString OpenModelicaHome(); - private: + private: static OmcInteractiveEnvironment* selfInstance; - OmcCommunicator &comm_; - QString result_; + OmcCommunicator &comm_; + QString result_; QString error_; - }; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/openmodelicahighlighter.cpp b/OMNotebook/OMNotebookQT4/openmodelicahighlighter.cpp index 98e87d83019..f514e0a5aa1 100644 --- a/OMNotebook/OMNotebookQT4/openmodelicahighlighter.cpp +++ b/OMNotebook/OMNotebookQT4/openmodelicahighlighter.cpp @@ -66,491 +66,491 @@ using namespace std; namespace IAEX { - /*! - * \class OpenModelicaHighlighter - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief Implements syntaxhighlightning for Modelica code. - * Implements syntaxhighlightning for Modelica code. To change - * colors edit the modelicacolors.xml - */ - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief The class constructor - */ - OpenModelicaHighlighter::OpenModelicaHighlighter( QString filename, QTextCharFormat standard ) - : filename_(filename), - standardTextFormat_(standard) - { - initializeQTextCharFormat(); - initializeMapping(); - } - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief The class destructor - */ - OpenModelicaHighlighter::~OpenModelicaHighlighter() - { - } - - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * \date 2005-12-29 (update) - * - * \brief Highlights a QTextDocument. The function highlights - * one text block at the time - * - * \param doc The text document that should be highlighted - * - * 2005-12-29 AF, Block signals while highlighting - */ - void OpenModelicaHighlighter::highlight( QTextDocument *doc ) - { - //2005-12-29 AF, add block signal - doc->blockSignals( true ); - - QTextBlock block = doc->begin(); - - insideString_ = false; - insideComment_ = false; - - // loop thought blocks - - while( block.isValid() ) - { - - highlightBlock(block); - block = block.next(); - } - - - - //2005-12-29 AF, add block signal - doc->blockSignals( false ); - } - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief Highlights a block of thext - * - * \param block The text block that should be highlighted - */ - void OpenModelicaHighlighter::highlightBlock( QTextBlock block ) - { - - try //071115 HE, this crashes too often - { - - QTextLayout *layout = block.layout(); - const QString text = block.text(); - QList overrides; - - bool wholeBlock = false; - int startPos = 0; - - if( insideString_ ) - { - - int end = text.indexOf( stringEnd_, startPos ); - - if( end >= 0 ) - { // found end in this block - - startPos = end + stringEnd_.matchedLength(); - insideString_ = false; - - QTextLayout::FormatRange range; - range.start = 0; - range.length = startPos; - range.format = stringFormat_; - overrides << range; - } - else - { // found no end, syntax highlight whole block - wholeBlock = true; - - - QTextLayout::FormatRange range; - range.start = 0; - range.length = block.length(); - range.format = stringFormat_; - overrides << range; - } - } - else if( insideComment_ ) - { - - - int end = text.indexOf( commentEnd_, startPos ); - - if( end >= 0 ) - { // found end in this block - - - startPos = end + commentEnd_.matchedLength(); - insideComment_ = false; - - QTextLayout::FormatRange range; - range.start = 0; - range.length = startPos; - range.format = commentFormat_; - overrides << range; - } - else - { // found no end, syntax highlight whole block - wholeBlock = true; - - - QTextLayout::FormatRange range; - range.start = 0; - range.length = block.length(); - range.format = commentFormat_; - overrides << range; - } - } - - - if( !wholeBlock ) - { - - foreach( QString pattern, mappings_.keys() ) - { - QRegExp expression( pattern ); - int i = text.indexOf( expression, startPos ); - - while( i >= 0 ) - { - QTextLayout::FormatRange range; - range.start = i; - range.length = expression.matchedLength(); - range.format = mappings_[pattern]; - overrides << range; - - i = text.indexOf(expression, i + expression.matchedLength()); - } - } - - - while( true ) - { - int firstString = -1; - int firstComment = -1; - int firstCommentLine = -1; - - - if( !stringStart_.isEmpty() ) - firstString = text.indexOf( stringStart_, startPos ); - if( !commentStart_.isEmpty() ) - firstComment = text.indexOf( commentStart_, startPos ); - if( !commentLine_.isEmpty() ) - firstCommentLine = text.indexOf( commentLine_, startPos ); - - - if( firstString >= 0 && - ( (firstString < firstComment) || (firstComment < 0) ) && - ( (firstString < firstCommentLine) || (firstCommentLine < 0) )) - { - int end = text.indexOf( stringEnd_, - firstString + stringStart_.matchedLength() ); - if( end >= 0 ) - { - startPos = end + stringEnd_.matchedLength(); - - QTextLayout::FormatRange range; - range.start = firstString; - range.length = startPos - firstString; - range.format = stringFormat_; - overrides << range; - } - else - { // found no end, syntax highlight to the end of the block - QTextLayout::FormatRange range; - range.start = firstString; - range.length = block.length() - firstString; - range.format = stringFormat_; - overrides << range; - insideString_ = true; - break; - } - } - else if( firstComment >= 0 && - ( (firstComment < firstString) || (firstString < 0) ) && - ( (firstComment < firstCommentLine) || (firstCommentLine < 0) )) - { - int end = text.indexOf( commentEnd_, - firstComment + commentStart_.matchedLength() ); - if( end >= 0 ) - { - startPos = end + commentEnd_.matchedLength(); - - QTextLayout::FormatRange range; - range.start = firstComment; - range.length = startPos - firstComment; - range.format = commentFormat_; - overrides << range; - } - else - { // found no end, syntax highlight to the end of the block - QTextLayout::FormatRange range; - range.start = firstComment; - range.length = block.length() - firstComment; - range.format = commentFormat_; - overrides << range; - insideComment_ = true; - break; - } - } - else if( firstCommentLine >= 0 && - ( (firstCommentLine < firstString) || (firstString < 0) ) && - ( (firstCommentLine < firstComment) || (firstComment < 0) )) - { - QTextLayout::FormatRange range; - range.start = firstCommentLine; - range.length = (block.length() - firstCommentLine); - range.format = commentFormat_; - overrides << range; - break; - } - else - break; - } - } - - layout->setAdditionalFormats( overrides ); - } - catch(...) - { - qDebug() << "openModelicaHighligter: crash" << endl; - } - - // 2006-05-11 AF, removed - //const_cast(block.document())->markContentsDirty( - //block.position(), block.length()); - } - - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief Initialize the different text formats by reading the - * settings from the file 'modelicacolors.xml'. - */ - void OpenModelicaHighlighter::initializeQTextCharFormat() - { - QDomDocument doc( "ModelicaColors" ); - QFile file( filename_ ); - - if( !file.open(QIODevice::ReadOnly) ) - { - string tmp = "Could not open " + filename_.toStdString(); - throw runtime_error( tmp.c_str() ); - } - - if( !doc.setContent(&file) ) - { - file.close(); - - string tmp = "Could not understand content of " + filename_.toStdString(); - throw runtime_error( tmp.c_str() ); - } - file.close(); - - QDomElement root = doc.documentElement(); - QDomNode node = root.firstChild(); - - - // set all format to standard format to start with... - typeFormat_.merge( standardTextFormat_ ); - keywordFormat_.merge( standardTextFormat_ ); - functionNameFormat_.merge( standardTextFormat_ ); - constantFormat_.merge( standardTextFormat_ ); - warningFormat_.merge( standardTextFormat_ ); - builtInFormat_.merge( standardTextFormat_ ); - variableNameFormat_.merge( standardTextFormat_ ); - stringFormat_.merge( standardTextFormat_ ); - commentFormat_.merge( standardTextFormat_ ); - - - while( !node.isNull() ) - { - QDomElement element = node.toElement(); - if( !element.isNull() ) - { - if( element.tagName() == "type" ) - parseSettings( element, &typeFormat_ ); - else if( element.tagName() == "keyword" ) - parseSettings( element, &keywordFormat_ ); - else if( element.tagName() == "functionName" ) - parseSettings( element, &functionNameFormat_ ); - else if( element.tagName() == "constant" ) - parseSettings( element, &constantFormat_ ); - else if( element.tagName() == "warning" ) - parseSettings( element, &warningFormat_ ); - else if( element.tagName() == "builtIn" ) - parseSettings( element, &builtInFormat_ ); - else if( element.tagName() == "variableName" ) - parseSettings( element, &variableNameFormat_ ); - else if( element.tagName() == "string" ) - parseSettings( element, &stringFormat_ ); - else if( element.tagName() == "comment" ) - parseSettings( element, &commentFormat_ ); - else - { - cout << "settings tag not specified: " << - element.tagName().toStdString(); - } - } - - node = node.nextSibling(); - } - } - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief Initialize the mapping by adding different patterns to - * the highlighter. - */ - void OpenModelicaHighlighter::initializeMapping() - { - // TYPE - mappings_.insert( QString("\\b(block|c(lass|on(nector|stant))|discrete|e(n(capsulated|d)") + - "|xternal)|f(inal|low|unction)|in(ner|put)|model|out(er|put)|pa(ckage|r(tial|ameter))" + - "|re(cord|declare|placeable)|type)\\b", - typeFormat_ ); - - // KEYWORD - // 2006-03-14 AF, added: expandable, enumeration - mappings_.insert( QString("\\b(a(lgorithm|nd)|for|i(f|mport|n)|loop|not|or") + - "|e(lse(if|when)?|quation|numeration|x(tends|pandable))|then" + - "|p(rotected|ublic)|w(h(en|ile)|ithin))\\b", - keywordFormat_ ); - - // FUNCTION NAME - // 2006-01-14 AF, added: der - // 2006-03-01 AF, removed sign, added sin - // 2006-03-14 AF, change function name totaly - mappings_.insert( QString("\\b(der|pre|initial|reinit)\\b"), - functionNameFormat_ ); - - /* - mappings_.insert( QString("\\b(a(bs|nalysisType)|c(ardinality|hange|eil|ross)|d(e(lay|r)") + - "|i(v|agonal))|edge|f(ill|loor)|i(dentity|n(itial|teger))|linspace|ma(trix|x)|min|mod|n(dims" + - "|oEvent)|o(nes|uterProduct)|pr(e|o(duct|mote))|re(init|m)|s(amle|calar|i(n|ze)|kew" + + /*! + * \class OpenModelicaHighlighter + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief Implements syntaxhighlightning for Modelica code. + * Implements syntaxhighlightning for Modelica code. To change + * colors edit the modelicacolors.xml + */ + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief The class constructor + */ + OpenModelicaHighlighter::OpenModelicaHighlighter( QString filename, QTextCharFormat standard ) + : filename_(filename), + standardTextFormat_(standard) + { + initializeQTextCharFormat(); + initializeMapping(); + } + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief The class destructor + */ + OpenModelicaHighlighter::~OpenModelicaHighlighter() + { + } + + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * \date 2005-12-29 (update) + * + * \brief Highlights a QTextDocument. The function highlights + * one text block at the time + * + * \param doc The text document that should be highlighted + * + * 2005-12-29 AF, Block signals while highlighting + */ + void OpenModelicaHighlighter::highlight( QTextDocument *doc ) + { + //2005-12-29 AF, add block signal + doc->blockSignals( true ); + + QTextBlock block = doc->begin(); + + insideString_ = false; + insideComment_ = false; + + // loop thought blocks + + while( block.isValid() ) + { + + highlightBlock(block); + block = block.next(); + } + + + + //2005-12-29 AF, add block signal + doc->blockSignals( false ); + } + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief Highlights a block of thext + * + * \param block The text block that should be highlighted + */ + void OpenModelicaHighlighter::highlightBlock( QTextBlock block ) + { + + try //071115 HE, this crashes too often + { + + QTextLayout *layout = block.layout(); + const QString text = block.text(); + QList overrides; + + bool wholeBlock = false; + int startPos = 0; + + if( insideString_ ) + { + + int end = text.indexOf( stringEnd_, startPos ); + + if( end >= 0 ) + { // found end in this block + + startPos = end + stringEnd_.matchedLength(); + insideString_ = false; + + QTextLayout::FormatRange range; + range.start = 0; + range.length = startPos; + range.format = stringFormat_; + overrides << range; + } + else + { // found no end, syntax highlight whole block + wholeBlock = true; + + + QTextLayout::FormatRange range; + range.start = 0; + range.length = block.length(); + range.format = stringFormat_; + overrides << range; + } + } + else if( insideComment_ ) + { + + + int end = text.indexOf( commentEnd_, startPos ); + + if( end >= 0 ) + { // found end in this block + + + startPos = end + commentEnd_.matchedLength(); + insideComment_ = false; + + QTextLayout::FormatRange range; + range.start = 0; + range.length = startPos; + range.format = commentFormat_; + overrides << range; + } + else + { // found no end, syntax highlight whole block + wholeBlock = true; + + + QTextLayout::FormatRange range; + range.start = 0; + range.length = block.length(); + range.format = commentFormat_; + overrides << range; + } + } + + + if( !wholeBlock ) + { + + foreach( QString pattern, mappings_.keys() ) + { + QRegExp expression( pattern ); + int i = text.indexOf( expression, startPos ); + + while( i >= 0 ) + { + QTextLayout::FormatRange range; + range.start = i; + range.length = expression.matchedLength(); + range.format = mappings_[pattern]; + overrides << range; + + i = text.indexOf(expression, i + expression.matchedLength()); + } + } + + + while( true ) + { + int firstString = -1; + int firstComment = -1; + int firstCommentLine = -1; + + + if( !stringStart_.isEmpty() ) + firstString = text.indexOf( stringStart_, startPos ); + if( !commentStart_.isEmpty() ) + firstComment = text.indexOf( commentStart_, startPos ); + if( !commentLine_.isEmpty() ) + firstCommentLine = text.indexOf( commentLine_, startPos ); + + + if( firstString >= 0 && + ( (firstString < firstComment) || (firstComment < 0) ) && + ( (firstString < firstCommentLine) || (firstCommentLine < 0) )) + { + int end = text.indexOf( stringEnd_, + firstString + stringStart_.matchedLength() ); + if( end >= 0 ) + { + startPos = end + stringEnd_.matchedLength(); + + QTextLayout::FormatRange range; + range.start = firstString; + range.length = startPos - firstString; + range.format = stringFormat_; + overrides << range; + } + else + { // found no end, syntax highlight to the end of the block + QTextLayout::FormatRange range; + range.start = firstString; + range.length = block.length() - firstString; + range.format = stringFormat_; + overrides << range; + insideString_ = true; + break; + } + } + else if( firstComment >= 0 && + ( (firstComment < firstString) || (firstString < 0) ) && + ( (firstComment < firstCommentLine) || (firstCommentLine < 0) )) + { + int end = text.indexOf( commentEnd_, + firstComment + commentStart_.matchedLength() ); + if( end >= 0 ) + { + startPos = end + commentEnd_.matchedLength(); + + QTextLayout::FormatRange range; + range.start = firstComment; + range.length = startPos - firstComment; + range.format = commentFormat_; + overrides << range; + } + else + { // found no end, syntax highlight to the end of the block + QTextLayout::FormatRange range; + range.start = firstComment; + range.length = block.length() - firstComment; + range.format = commentFormat_; + overrides << range; + insideComment_ = true; + break; + } + } + else if( firstCommentLine >= 0 && + ( (firstCommentLine < firstString) || (firstString < 0) ) && + ( (firstCommentLine < firstComment) || (firstComment < 0) )) + { + QTextLayout::FormatRange range; + range.start = firstCommentLine; + range.length = (block.length() - firstCommentLine); + range.format = commentFormat_; + overrides << range; + break; + } + else + break; + } + } + + layout->setAdditionalFormats( overrides ); + } + catch(...) + { + qDebug() << "openModelicaHighligter: crash" << endl; + } + + // 2006-05-11 AF, removed + //const_cast(block.document())->markContentsDirty( + //block.position(), block.length()); + } + + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief Initialize the different text formats by reading the + * settings from the file 'modelicacolors.xml'. + */ + void OpenModelicaHighlighter::initializeQTextCharFormat() + { + QDomDocument doc( "ModelicaColors" ); + QFile file( filename_ ); + + if( !file.open(QIODevice::ReadOnly) ) + { + string tmp = "Could not open " + filename_.toStdString(); + throw runtime_error( tmp.c_str() ); + } + + if( !doc.setContent(&file) ) + { + file.close(); + + string tmp = "Could not understand content of " + filename_.toStdString(); + throw runtime_error( tmp.c_str() ); + } + file.close(); + + QDomElement root = doc.documentElement(); + QDomNode node = root.firstChild(); + + + // set all format to standard format to start with... + typeFormat_.merge( standardTextFormat_ ); + keywordFormat_.merge( standardTextFormat_ ); + functionNameFormat_.merge( standardTextFormat_ ); + constantFormat_.merge( standardTextFormat_ ); + warningFormat_.merge( standardTextFormat_ ); + builtInFormat_.merge( standardTextFormat_ ); + variableNameFormat_.merge( standardTextFormat_ ); + stringFormat_.merge( standardTextFormat_ ); + commentFormat_.merge( standardTextFormat_ ); + + + while( !node.isNull() ) + { + QDomElement element = node.toElement(); + if( !element.isNull() ) + { + if( element.tagName() == "type" ) + parseSettings( element, &typeFormat_ ); + else if( element.tagName() == "keyword" ) + parseSettings( element, &keywordFormat_ ); + else if( element.tagName() == "functionName" ) + parseSettings( element, &functionNameFormat_ ); + else if( element.tagName() == "constant" ) + parseSettings( element, &constantFormat_ ); + else if( element.tagName() == "warning" ) + parseSettings( element, &warningFormat_ ); + else if( element.tagName() == "builtIn" ) + parseSettings( element, &builtInFormat_ ); + else if( element.tagName() == "variableName" ) + parseSettings( element, &variableNameFormat_ ); + else if( element.tagName() == "string" ) + parseSettings( element, &stringFormat_ ); + else if( element.tagName() == "comment" ) + parseSettings( element, &commentFormat_ ); + else + { + cout << "settings tag not specified: " << + element.tagName().toStdString(); + } + } + + node = node.nextSibling(); + } + } + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief Initialize the mapping by adding different patterns to + * the highlighter. + */ + void OpenModelicaHighlighter::initializeMapping() + { + // TYPE + mappings_.insert( QString("\\b(block|c(lass|on(nector|stant))|discrete|e(n(capsulated|d)") + + "|xternal)|f(inal|low|unction)|in(ner|put)|model|out(er|put)|pa(ckage|r(tial|ameter))" + + "|re(cord|declare|placeable)|type)\\b", + typeFormat_ ); + + // KEYWORD + // 2006-03-14 AF, added: expandable, enumeration + mappings_.insert( QString("\\b(a(lgorithm|nd)|for|i(f|mport|n)|loop|not|or") + + "|e(lse(if|when)?|quation|numeration|x(tends|pandable))|then" + + "|p(rotected|ublic)|w(h(en|ile)|ithin))\\b", + keywordFormat_ ); + + // FUNCTION NAME + // 2006-01-14 AF, added: der + // 2006-03-01 AF, removed sign, added sin + // 2006-03-14 AF, change function name totaly + mappings_.insert( QString("\\b(der|pre|initial|reinit)\\b"), + functionNameFormat_ ); + + /* + mappings_.insert( QString("\\b(a(bs|nalysisType)|c(ardinality|hange|eil|ross)|d(e(lay|r)") + + "|i(v|agonal))|edge|f(ill|loor)|i(dentity|n(itial|teger))|linspace|ma(trix|x)|min|mod|n(dims" + + "|oEvent)|o(nes|uterProduct)|pr(e|o(duct|mote))|re(init|m)|s(amle|calar|i(n|ze)|kew" + "|qrt|um|ymmetric)|t(erminal|ranspose)|vector|zeros)\\b", - functionNameFormat_ ); - */ - - // CONSTANT - mappings_.insert( "\\b(false|true)\\b", - constantFormat_ ); - - // WARNING - mappings_.insert( "\\b(assert|terminate)\\b", - warningFormat_ ); - - // BUILT IN - mappings_.insert( "\\b(annotation|connect)\\b", - builtInFormat_ ); - - // VARIABLE NAME - mappings_.insert( "\\b(time)\\b", - variableNameFormat_ ); - - // STRING - // A little diffrent because strings can span over several blocks - stringStart_.setPattern( "\"" ); - stringEnd_.setPattern( "\"" ); - - // COMMENT - // A little diffrent because comments can span over several blocks - commentStart_.setPattern( "/\\*" ); - commentEnd_.setPattern( "\\*/" ); - commentLine_.setPattern( "//.*" ); - } - - /*! - * \author Anders Fernström - * \date 2005-12-17 - * - * \brief Parse "type" settings tags - */ - void OpenModelicaHighlighter::parseSettings( QDomElement e, - QTextCharFormat *format ) - { - QDomNode node = e.firstChild(); - while( !node.isNull() ) - { - QDomElement element = node.toElement(); - if( !element.isNull() ) - { - // FOREGROUND - if( element.tagName() == "foreground" ) - { - bool okRed; - bool okGreen; - bool okBlue; - - int red = element.attribute( "red", "0" ).toInt(&okRed); - int green = element.attribute( "green", "0" ).toInt(&okGreen); - int blue = element.attribute( "blue", "0" ).toInt(&okBlue); - - if( okRed && okGreen && okBlue ) - format->setForeground( QBrush( QColor(red, green, blue) )); - else - format->setForeground( QBrush( QColor(0, 0, 0) )); - } - // BACKGROUND - else if( element.tagName() == "background" ) - { - bool okRed; - bool okGreen; - bool okBlue; - - int red = element.attribute( "red", "200" ).toInt(&okRed); - int green = element.attribute( "green", "200" ).toInt(&okGreen); - int blue = element.attribute( "blue", "255" ).toInt(&okBlue); - - if( okRed && okGreen && okBlue ) - format->setBackground( QBrush( QColor(red, green, blue) )); - else - format->setBackground( QBrush( QColor(200, 200, 255) )); - } - // BOLD - else if( element.tagName() == "bold" ) - { - //This only occur when bold tag is present. - //delete bold tag to disable. - format->setFontWeight( QFont::Bold ); - } - // ITALIC - else if( element.tagName() == "italic" ) - { - //This only occur when italic tag is present. - //delete italic tag to disable. - format->setFontItalic( true ); - } - else - { - cout << "type settings tag not specified: " << - element.tagName().toStdString(); - } - } - - node = node.nextSibling(); - } - } + functionNameFormat_ ); + */ + + // CONSTANT + mappings_.insert( "\\b(false|true)\\b", + constantFormat_ ); + + // WARNING + mappings_.insert( "\\b(assert|terminate)\\b", + warningFormat_ ); + + // BUILT IN + mappings_.insert( "\\b(annotation|connect)\\b", + builtInFormat_ ); + + // VARIABLE NAME + mappings_.insert( "\\b(time)\\b", + variableNameFormat_ ); + + // STRING + // A little diffrent because strings can span over several blocks + stringStart_.setPattern( "\"" ); + stringEnd_.setPattern( "\"" ); + + // COMMENT + // A little diffrent because comments can span over several blocks + commentStart_.setPattern( "/\\*" ); + commentEnd_.setPattern( "\\*/" ); + commentLine_.setPattern( "//.*" ); + } + + /*! + * \author Anders Fernström + * \date 2005-12-17 + * + * \brief Parse "type" settings tags + */ + void OpenModelicaHighlighter::parseSettings( QDomElement e, + QTextCharFormat *format ) + { + QDomNode node = e.firstChild(); + while( !node.isNull() ) + { + QDomElement element = node.toElement(); + if( !element.isNull() ) + { + // FOREGROUND + if( element.tagName() == "foreground" ) + { + bool okRed; + bool okGreen; + bool okBlue; + + int red = element.attribute( "red", "0" ).toInt(&okRed); + int green = element.attribute( "green", "0" ).toInt(&okGreen); + int blue = element.attribute( "blue", "0" ).toInt(&okBlue); + + if( okRed && okGreen && okBlue ) + format->setForeground( QBrush( QColor(red, green, blue) )); + else + format->setForeground( QBrush( QColor(0, 0, 0) )); + } + // BACKGROUND + else if( element.tagName() == "background" ) + { + bool okRed; + bool okGreen; + bool okBlue; + + int red = element.attribute( "red", "200" ).toInt(&okRed); + int green = element.attribute( "green", "200" ).toInt(&okGreen); + int blue = element.attribute( "blue", "255" ).toInt(&okBlue); + + if( okRed && okGreen && okBlue ) + format->setBackground( QBrush( QColor(red, green, blue) )); + else + format->setBackground( QBrush( QColor(200, 200, 255) )); + } + // BOLD + else if( element.tagName() == "bold" ) + { + //This only occur when bold tag is present. + //delete bold tag to disable. + format->setFontWeight( QFont::Bold ); + } + // ITALIC + else if( element.tagName() == "italic" ) + { + //This only occur when italic tag is present. + //delete italic tag to disable. + format->setFontItalic( true ); + } + else + { + cout << "type settings tag not specified: " << + element.tagName().toStdString(); + } + } + + node = node.nextSibling(); + } + } } diff --git a/OMNotebook/OMNotebookQT4/openmodelicahighlighter.h b/OMNotebook/OMNotebookQT4/openmodelicahighlighter.h index effde0f47fc..5b4b880dd2c 100644 --- a/OMNotebook/OMNotebookQT4/openmodelicahighlighter.h +++ b/OMNotebook/OMNotebookQT4/openmodelicahighlighter.h @@ -67,42 +67,42 @@ class QDomElement; namespace IAEX { - class OpenModelicaHighlighter : public SyntaxHighlighter - { - public: - OpenModelicaHighlighter( QString filename, QTextCharFormat standard ); - virtual ~OpenModelicaHighlighter(); - void highlight( QTextDocument *doc ); + class OpenModelicaHighlighter : public SyntaxHighlighter + { + public: + OpenModelicaHighlighter( QString filename, QTextCharFormat standard ); + virtual ~OpenModelicaHighlighter(); + void highlight( QTextDocument *doc ); - private: - void highlightBlock( QTextBlock block ); - void initializeQTextCharFormat(); - void initializeMapping(); - void parseSettings( QDomElement e, QTextCharFormat *format ); + private: + void highlightBlock( QTextBlock block ); + void initializeQTextCharFormat(); + void initializeMapping(); + void parseSettings( QDomElement e, QTextCharFormat *format ); - private: - QString filename_; - QHash mappings_; + private: + QString filename_; + QHash mappings_; - bool insideString_; - bool insideComment_; - QRegExp stringStart_; - QRegExp stringEnd_; - QRegExp commentStart_; - QRegExp commentEnd_; - QRegExp commentLine_; + bool insideString_; + bool insideComment_; + QRegExp stringStart_; + QRegExp stringEnd_; + QRegExp commentStart_; + QRegExp commentEnd_; + QRegExp commentLine_; - QTextCharFormat standardTextFormat_; - QTextCharFormat typeFormat_; - QTextCharFormat keywordFormat_; - QTextCharFormat functionNameFormat_; - QTextCharFormat constantFormat_; - QTextCharFormat warningFormat_; - QTextCharFormat builtInFormat_; - QTextCharFormat variableNameFormat_; - QTextCharFormat stringFormat_; - QTextCharFormat commentFormat_; - }; + QTextCharFormat standardTextFormat_; + QTextCharFormat typeFormat_; + QTextCharFormat keywordFormat_; + QTextCharFormat functionNameFormat_; + QTextCharFormat constantFormat_; + QTextCharFormat warningFormat_; + QTextCharFormat builtInFormat_; + QTextCharFormat variableNameFormat_; + QTextCharFormat stringFormat_; + QTextCharFormat commentFormat_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/otherdlg.h b/OMNotebook/OMNotebookQT4/otherdlg.h index a33c87e7b34..ab2a3527ba2 100644 --- a/OMNotebook/OMNotebookQT4/otherdlg.h +++ b/OMNotebook/OMNotebookQT4/otherdlg.h @@ -46,55 +46,55 @@ namespace IAEX { - /*! - * \class OtherDlg - * \author Anders Fernström - * \date 2005-11-04 - * - * \breif Class of opening a dialog window for entering av value... - */ - class OtherDlg : public QDialog - { - public: - OtherDlg( QWidget *parent, int min, int max) - : QDialog(parent), min_(min), max_(max) - { - ui.setupUi(this); + /*! + * \class OtherDlg + * \author Anders Fernström + * \date 2005-11-04 + * + * \breif Class of opening a dialog window for entering av value... + */ + class OtherDlg : public QDialog + { + public: + OtherDlg( QWidget *parent, int min, int max) + : QDialog(parent), min_(min), max_(max) + { + ui.setupUi(this); - QString minW; - QString maxW; - minW.setNum( min_ ); - maxW.setNum( max_ ); + QString minW; + QString maxW; + minW.setNum( min_ ); + maxW.setNum( max_ ); - QString text = QString("Enter value (") + minW + - QString("-") + maxW + QString(")"); + QString text = QString("Enter value (") + minW + + QString("-") + maxW + QString(")"); - ui.label->setText( text ); + ui.label->setText( text ); - //set fixed size - setMinimumHeight( height() ); - setMaximumHeight( height() ); - setMinimumWidth( width() ); - setMaximumWidth( width() ); - } - virtual ~OtherDlg(){} - int value() - { - bool ok; - int value = ui.lineEdit->text().toInt(&ok); + //set fixed size + setMinimumHeight( height() ); + setMaximumHeight( height() ); + setMinimumWidth( width() ); + setMaximumWidth( width() ); + } + virtual ~OtherDlg(){} + int value() + { + bool ok; + int value = ui.lineEdit->text().toInt(&ok); - if(ok) - if( min_ <= value && value <= max_ ) - return value; + if(ok) + if( min_ <= value && value <= max_ ) + return value; - return -1; - } + return -1; + } - private: - Ui::SelectDialog ui; - int min_; - int max_; - }; + private: + Ui::SelectDialog ui; + int min_; + int max_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/printervisitor.h b/OMNotebook/OMNotebookQT4/printervisitor.h index 6ed3544cfe4..e285ae302a3 100644 --- a/OMNotebook/OMNotebookQT4/printervisitor.h +++ b/OMNotebook/OMNotebookQT4/printervisitor.h @@ -51,40 +51,40 @@ class QPrinter; using namespace std; namespace IAEX { - class PrinterVisitor : public Visitor - { + class PrinterVisitor : public Visitor + { - public: - PrinterVisitor( QTextDocument* doc, QPrinter* printer ); - virtual ~PrinterVisitor(); + public: + PrinterVisitor( QTextDocument* doc, QPrinter* printer ); + virtual ~PrinterVisitor(); - virtual void visitCellNodeBefore(Cell *node); - virtual void visitCellNodeAfter(Cell *node); + virtual void visitCellNodeBefore(Cell *node); + virtual void visitCellNodeAfter(Cell *node); - virtual void visitCellGroupNodeBefore(CellGroup *node); - virtual void visitCellGroupNodeAfter(CellGroup *node); + virtual void visitCellGroupNodeBefore(CellGroup *node); + virtual void visitCellGroupNodeAfter(CellGroup *node); - virtual void visitTextCellNodeBefore(TextCell *node); - virtual void visitTextCellNodeAfter(TextCell *node); + virtual void visitTextCellNodeBefore(TextCell *node); + virtual void visitTextCellNodeAfter(TextCell *node); - virtual void visitInputCellNodeBefore(InputCell *node); - virtual void visitInputCellNodeAfter(InputCell *node); + virtual void visitInputCellNodeBefore(InputCell *node); + virtual void visitInputCellNodeAfter(InputCell *node); - virtual void visitGraphCellNodeBefore(GraphCell *node); - virtual void visitGraphCellNodeAfter(GraphCell *node); + virtual void visitGraphCellNodeBefore(GraphCell *node); + virtual void visitGraphCellNodeAfter(GraphCell *node); - virtual void visitCellCursorNodeBefore(CellCursor *cursor); - virtual void visitCellCursorNodeAfter(CellCursor *cursor); + virtual void visitCellCursorNodeBefore(CellCursor *cursor); + virtual void visitCellCursorNodeAfter(CellCursor *cursor); - private: - QTextEdit *printEditor_; - QTextTable *table_; - bool ignore_; - bool firstChild_; - CellGroup *closedCell_; - QPrinter* printer_; + private: + QTextEdit *printEditor_; + QTextTable *table_; + bool ignore_; + bool firstChild_; + CellGroup *closedCell_; + QPrinter* printer_; - int currentTableRow_; - }; + int currentTableRow_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/puretextvisitor.cpp b/OMNotebook/OMNotebookQT4/puretextvisitor.cpp index 503a389170b..6bfa114cec7 100644 --- a/OMNotebook/OMNotebookQT4/puretextvisitor.cpp +++ b/OMNotebook/OMNotebookQT4/puretextvisitor.cpp @@ -51,136 +51,136 @@ namespace IAEX { - /*! - * \class PureTextVisitor - * \date 2005-11-21 - * - * \brief Export contents in a document to a file as pure text - * - * Traverses the cellstructure and export the text inside textcells - * and inputcells to a file, as pure/plain text. - */ - - /*! - * \author Anders Fernström - * - * \brief The class constructor - */ - PureTextVisitor::PureTextVisitor(QFile *file) - { - ts_ = new QTextStream( file ); - } - - /*! - * \author Anders Fernström - * - * \brief The class deconstructor - */ - PureTextVisitor::~PureTextVisitor() - { - delete ts_; - } - - // CELL - void PureTextVisitor::visitCellNodeBefore(Cell *) - {} - - void PureTextVisitor::visitCellNodeAfter(Cell *) - {} - - // GROUPCELL - void PureTextVisitor::visitCellGroupNodeBefore(CellGroup *node) - {} - - void PureTextVisitor::visitCellGroupNodeAfter(CellGroup *) - {} - - // TEXTCELL - void PureTextVisitor::visitTextCellNodeBefore(TextCell *node) - { - node->viewExpression(false); - - // remove img tag before exporting - int pos = 0; - QString html = node->textHtml(); - while( true ) - { - int start = html.indexOf( "", start, Qt::CaseInsensitive ); - if( 0 <= end ) - { - html.remove( start, (end - start) + 2 ); - pos = start; - } - else - break; - } - else - break; - } - QTextEdit tmp; - tmp.setHtml( html ); - - // 2006-03-03 AF, export chapter counter - if( !node->ChapterCounter().isNull() ) - (*ts_) << node->ChapterCounter() << QString(" "); - - (*ts_) << tmp.toPlainText(); - (*ts_) << "\r\n\r\n\r\n"; - } - - void PureTextVisitor::visitTextCellNodeAfter(TextCell *) - {} - - //INPUTCELL - void PureTextVisitor::visitInputCellNodeBefore(InputCell *node) - { - // 2006-03-03 AF, export chapter counter - if( !node->ChapterCounter().isNull() ) - (*ts_) << node->ChapterCounter() << QString(" "); - - (*ts_) << node->text(); - (*ts_) << QString( "\r\n\r\n" ); - - // 2006-03-03 AF, export output if not an image - if( node->textOutputHtml().indexOf( "ChapterCounter().isNull() ) - (*ts_) << node->ChapterCounter() << QString(" "); - - (*ts_) << node->text(); - (*ts_) << QString( "\r\n\r\n" ); - - // 2006-03-03 AF, export output if not an image - if( node->textOutputHtml().indexOf( "viewExpression(false); + + // remove img tag before exporting + int pos = 0; + QString html = node->textHtml(); + while( true ) + { + int start = html.indexOf( "", start, Qt::CaseInsensitive ); + if( 0 <= end ) + { + html.remove( start, (end - start) + 2 ); + pos = start; + } + else + break; + } + else + break; + } + QTextEdit tmp; + tmp.setHtml( html ); + + // 2006-03-03 AF, export chapter counter + if( !node->ChapterCounter().isNull() ) + (*ts_) << node->ChapterCounter() << QString(" "); + + (*ts_) << tmp.toPlainText(); + (*ts_) << "\r\n\r\n\r\n"; + } + + void PureTextVisitor::visitTextCellNodeAfter(TextCell *) + {} + + //INPUTCELL + void PureTextVisitor::visitInputCellNodeBefore(InputCell *node) + { + // 2006-03-03 AF, export chapter counter + if( !node->ChapterCounter().isNull() ) + (*ts_) << node->ChapterCounter() << QString(" "); + + (*ts_) << node->text(); + (*ts_) << QString( "\r\n\r\n" ); + + // 2006-03-03 AF, export output if not an image + if( node->textOutputHtml().indexOf( "ChapterCounter().isNull() ) + (*ts_) << node->ChapterCounter() << QString(" "); + + (*ts_) << node->text(); + (*ts_) << QString( "\r\n\r\n" ); + + // 2006-03-03 AF, export output if not an image + if( node->textOutputHtml().indexOf( "key() == Qt::Key_Return || event->key() == Qt::Key_Enter ) - { - emit returnPressed(); - } - else - QComboBox::keyPressEvent( event ); - } + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Reimplement what happen when a key event is sent to the combobox + */ + void ComboBoxSearch::keyPressEvent( QKeyEvent* event ) + { + if( event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter ) + { + emit returnPressed(); + } + else + QComboBox::keyPressEvent( event ); + } } diff --git a/OMNotebook/OMNotebookQT4/qcombobox_search.h b/OMNotebook/OMNotebookQT4/qcombobox_search.h index 332b4457d25..6d669d077aa 100644 --- a/OMNotebook/OMNotebookQT4/qcombobox_search.h +++ b/OMNotebook/OMNotebookQT4/qcombobox_search.h @@ -46,21 +46,21 @@ namespace IAEX { - class ComboBoxSearch : public QComboBox - { - Q_OBJECT + class ComboBoxSearch : public QComboBox + { + Q_OBJECT - public: - ComboBoxSearch( QWidget* parent ); - ~ComboBoxSearch(); + public: + ComboBoxSearch( QWidget* parent ); + ~ComboBoxSearch(); - protected: - void keyPressEvent( QKeyEvent* event ); + protected: + void keyPressEvent( QKeyEvent* event ); - signals: - void returnPressed(); + signals: + void returnPressed(); - }; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/qtapp.cpp b/OMNotebook/OMNotebookQT4/qtapp.cpp index e57d7f3b94e..c1066951f9c 100644 --- a/OMNotebook/OMNotebookQT4/qtapp.cpp +++ b/OMNotebook/OMNotebookQT4/qtapp.cpp @@ -53,18 +53,18 @@ using namespace IAEX; int main(int argc, char *argv[]) { - try - { - CellApplication a(argc, argv); - return a.exec(); - } - catch(exception &e) - { - // 2006-01-30 AF, add message box - QString msg = QString("In main(), exception: \n") + e.what(); - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } + try + { + CellApplication a(argc, argv); + return a.exec(); + } + catch(exception &e) + { + // 2006-01-30 AF, add message box + QString msg = QString("In main(), exception: \n") + e.what(); + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } - return 0; + return 0; } diff --git a/OMNotebook/OMNotebookQT4/removehighlightervisitor.h b/OMNotebook/OMNotebookQT4/removehighlightervisitor.h index 5a3f8a0c889..b27c2204f75 100644 --- a/OMNotebook/OMNotebookQT4/removehighlightervisitor.h +++ b/OMNotebook/OMNotebookQT4/removehighlightervisitor.h @@ -51,39 +51,39 @@ using namespace std; namespace IAEX { - class RemoveHighlighterVisitor : public Visitor - { + class RemoveHighlighterVisitor : public Visitor + { - public: - RemoveHighlighterVisitor(){} - virtual ~RemoveHighlighterVisitor(){} + public: + RemoveHighlighterVisitor(){} + virtual ~RemoveHighlighterVisitor(){} - virtual void visitCellNodeBefore(Cell *node){} - virtual void visitCellNodeAfter(Cell *node){} + virtual void visitCellNodeBefore(Cell *node){} + virtual void visitCellNodeAfter(Cell *node){} - virtual void visitCellGroupNodeBefore(CellGroup *node){} - virtual void visitCellGroupNodeAfter(CellGroup *node){} + virtual void visitCellGroupNodeBefore(CellGroup *node){} + virtual void visitCellGroupNodeAfter(CellGroup *node){} - virtual void visitTextCellNodeBefore(TextCell *node){} - virtual void visitTextCellNodeAfter(TextCell *node){} + virtual void visitTextCellNodeBefore(TextCell *node){} + virtual void visitTextCellNodeAfter(TextCell *node){} - virtual void visitInputCellNodeBefore(InputCell *node) - { - HighlighterThread *thread = HighlighterThread::instance(); - thread->removeEditor( node->textEdit() ); - } - virtual void visitInputCellNodeAfter(InputCell *node){} + virtual void visitInputCellNodeBefore(InputCell *node) + { + HighlighterThread *thread = HighlighterThread::instance(); + thread->removeEditor( node->textEdit() ); + } + virtual void visitInputCellNodeAfter(InputCell *node){} - virtual void visitGraphCellNodeBefore(GraphCell *node) - { - HighlighterThread *thread = HighlighterThread::instance(); - thread->removeEditor( node->textEdit() ); - } - virtual void visitGraphCellNodeAfter(GraphCell *node){} + virtual void visitGraphCellNodeBefore(GraphCell *node) + { + HighlighterThread *thread = HighlighterThread::instance(); + thread->removeEditor( node->textEdit() ); + } + virtual void visitGraphCellNodeAfter(GraphCell *node){} - virtual void visitCellCursorNodeBefore(CellCursor *cursor){} - virtual void visitCellCursorNodeAfter(CellCursor *cursor){} - }; + virtual void visitCellCursorNodeBefore(CellCursor *cursor){} + virtual void visitCellCursorNodeAfter(CellCursor *cursor){} + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/replaceallvisitor.h b/OMNotebook/OMNotebookQT4/replaceallvisitor.h index 52406842998..e37b5de4962 100644 --- a/OMNotebook/OMNotebookQT4/replaceallvisitor.h +++ b/OMNotebook/OMNotebookQT4/replaceallvisitor.h @@ -54,128 +54,128 @@ namespace IAEX { - class ReplaceAllVisitor : public Visitor - { - public: - ReplaceAllVisitor( QString findText, QString replaceText, bool matchCase = false, bool matchWord = false, int* count = 0 ) - : findText_( findText ), replaceText_( replaceText ), matchCase_( matchCase ), matchWord_( matchWord ), count_( count ) - {} - ~ReplaceAllVisitor(){} - - // Visitor function - CELL - void visitCellNodeBefore( Cell *node ){} - void visitCellNodeAfter( Cell *node ){} - - // Visitor function - GROUPCELL - void visitCellGroupNodeBefore( CellGroup *node ){} - void visitCellGroupNodeAfter( CellGroup *node ){} - - // Visitor function - TEXTCELL - void visitTextCellNodeBefore( TextCell *node ) - { - if( node->textEdit() ) - { - int options( 0 ); - - // move cursor to start of text - QTextCursor cursor = node->textEdit()->textCursor(); - cursor.movePosition( QTextCursor::Start ); - node->textEdit()->setTextCursor( cursor ); - - // match case & match word - if( matchCase_ && matchWord_ ) - options = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; - else if( matchCase_ ) - options = QTextDocument::FindCaseSensitively; - else if( matchWord_ ) - options = QTextDocument::FindWholeWords; - - // replace all - while( node->textEdit()->find( findText_, (QTextDocument::FindFlag)options )) - { - node->textEdit()->textCursor().insertText( replaceText_ ); - if( count_ ) - (*count_)++; - } - } - } - void visitTextCellNodeAfter( TextCell *node ){} - - // Visitor function - INPUTCELL - void visitInputCellNodeBefore( InputCell *node ) - { - if( node->textEdit() ) - { - int options( 0 ); - - // move cursor to start of text - QTextCursor cursor = node->textEdit()->textCursor(); - cursor.movePosition( QTextCursor::Start ); - node->textEdit()->setTextCursor( cursor ); - - // match case & match word - if( matchCase_ && matchWord_ ) - options = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; - else if( matchCase_ ) - options = QTextDocument::FindCaseSensitively; - else if( matchWord_ ) - options = QTextDocument::FindWholeWords; - - // replace all - while( node->textEdit()->find( findText_, (QTextDocument::FindFlag)options )) - { - node->textEdit()->textCursor().insertText( replaceText_ ); - if( count_ ) - (*count_)++; - } - } - } - void visitInputCellNodeAfter( InputCell *node ){} - - - // Visitor function - GRAPHCELL - void visitGraphCellNodeBefore( GraphCell *node ) - { - if( node->textEdit() ) - { - int options( 0 ); - - // move cursor to start of text - QTextCursor cursor = node->textEdit()->textCursor(); - cursor.movePosition( QTextCursor::Start ); - node->textEdit()->setTextCursor( cursor ); - - // match case & match word - if( matchCase_ && matchWord_ ) - options = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; - else if( matchCase_ ) - options = QTextDocument::FindCaseSensitively; - else if( matchWord_ ) - options = QTextDocument::FindWholeWords; - - // replace all - while( node->textEdit()->find( findText_, (QTextDocument::FindFlag)options )) - { - node->textEdit()->textCursor().insertText( replaceText_ ); - if( count_ ) - (*count_)++; - } - } - } - void visitGraphCellNodeAfter( GraphCell *node ){} - - // Visitor function - CURSORCELL - void visitCellCursorNodeBefore( CellCursor *cursor ){} - void visitCellCursorNodeAfter( CellCursor *cursor ){} - - - private: - QString findText_; - QString replaceText_; - bool matchCase_; - bool matchWord_; - int* count_; - }; + class ReplaceAllVisitor : public Visitor + { + public: + ReplaceAllVisitor( QString findText, QString replaceText, bool matchCase = false, bool matchWord = false, int* count = 0 ) + : findText_( findText ), replaceText_( replaceText ), matchCase_( matchCase ), matchWord_( matchWord ), count_( count ) + {} + ~ReplaceAllVisitor(){} + + // Visitor function - CELL + void visitCellNodeBefore( Cell *node ){} + void visitCellNodeAfter( Cell *node ){} + + // Visitor function - GROUPCELL + void visitCellGroupNodeBefore( CellGroup *node ){} + void visitCellGroupNodeAfter( CellGroup *node ){} + + // Visitor function - TEXTCELL + void visitTextCellNodeBefore( TextCell *node ) + { + if( node->textEdit() ) + { + int options( 0 ); + + // move cursor to start of text + QTextCursor cursor = node->textEdit()->textCursor(); + cursor.movePosition( QTextCursor::Start ); + node->textEdit()->setTextCursor( cursor ); + + // match case & match word + if( matchCase_ && matchWord_ ) + options = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; + else if( matchCase_ ) + options = QTextDocument::FindCaseSensitively; + else if( matchWord_ ) + options = QTextDocument::FindWholeWords; + + // replace all + while( node->textEdit()->find( findText_, (QTextDocument::FindFlag)options )) + { + node->textEdit()->textCursor().insertText( replaceText_ ); + if( count_ ) + (*count_)++; + } + } + } + void visitTextCellNodeAfter( TextCell *node ){} + + // Visitor function - INPUTCELL + void visitInputCellNodeBefore( InputCell *node ) + { + if( node->textEdit() ) + { + int options( 0 ); + + // move cursor to start of text + QTextCursor cursor = node->textEdit()->textCursor(); + cursor.movePosition( QTextCursor::Start ); + node->textEdit()->setTextCursor( cursor ); + + // match case & match word + if( matchCase_ && matchWord_ ) + options = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; + else if( matchCase_ ) + options = QTextDocument::FindCaseSensitively; + else if( matchWord_ ) + options = QTextDocument::FindWholeWords; + + // replace all + while( node->textEdit()->find( findText_, (QTextDocument::FindFlag)options )) + { + node->textEdit()->textCursor().insertText( replaceText_ ); + if( count_ ) + (*count_)++; + } + } + } + void visitInputCellNodeAfter( InputCell *node ){} + + + // Visitor function - GRAPHCELL + void visitGraphCellNodeBefore( GraphCell *node ) + { + if( node->textEdit() ) + { + int options( 0 ); + + // move cursor to start of text + QTextCursor cursor = node->textEdit()->textCursor(); + cursor.movePosition( QTextCursor::Start ); + node->textEdit()->setTextCursor( cursor ); + + // match case & match word + if( matchCase_ && matchWord_ ) + options = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; + else if( matchCase_ ) + options = QTextDocument::FindCaseSensitively; + else if( matchWord_ ) + options = QTextDocument::FindWholeWords; + + // replace all + while( node->textEdit()->find( findText_, (QTextDocument::FindFlag)options )) + { + node->textEdit()->textCursor().insertText( replaceText_ ); + if( count_ ) + (*count_)++; + } + } + } + void visitGraphCellNodeAfter( GraphCell *node ){} + + // Visitor function - CURSORCELL + void visitCellCursorNodeBefore( CellCursor *cursor ){} + void visitCellCursorNodeAfter( CellCursor *cursor ){} + + + private: + QString findText_; + QString replaceText_; + bool matchCase_; + bool matchWord_; + int* count_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/rule.h b/OMNotebook/OMNotebookQT4/rule.h index 8c4f5c0e32f..72aa1a882eb 100644 --- a/OMNotebook/OMNotebookQT4/rule.h +++ b/OMNotebook/OMNotebookQT4/rule.h @@ -63,18 +63,18 @@ namespace IAEX attribute_t attribute() const { - return attribute_; + return attribute_; } value_t value() const { - return value_; + return value_; } - void setValue( value_t val ) - { - value_ = val; - } + void setValue( value_t val ) + { + value_ = val; + } private: attribute_t attribute_; diff --git a/OMNotebook/OMNotebookQT4/searchform.cpp b/OMNotebook/OMNotebookQT4/searchform.cpp index b91fe1a795d..c5801aa35d3 100644 --- a/OMNotebook/OMNotebookQT4/searchform.cpp +++ b/OMNotebook/OMNotebookQT4/searchform.cpp @@ -53,565 +53,565 @@ namespace IAEX { - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Class constructor - */ - SearchForm::SearchForm( QWidget* parent, Document* document, bool viewReplace ) - : QDialog( parent ), - document_( document ), - viewReplace_( viewReplace ) - { - ui.setupUi(this); - - // connections - connect( ui.viewReplaceButton_, SIGNAL( clicked() ), - this, SLOT( showHideReplace() )); - connect( ui.hideReplaceButton_, SIGNAL( clicked() ), - this, SLOT( showHideReplace() )); - connect( ui.searchButton_, SIGNAL( clicked() ), - this, SLOT( search() )); - connect( ui.replaceButton_, SIGNAL( clicked() ), - this, SLOT( replace() )); - connect( ui.replaceAllButton_, SIGNAL( clicked() ), - this, SLOT( replaceAll() )); - connect( ui.searchComboBox_, SIGNAL( returnPressed() ), - this, SLOT( search() )); - connect( ui.closeButton_, SIGNAL( clicked() ), - this, SLOT( closeForm() )); - - // Replace stuff - showOrHideReplace(); - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Class destructor - */ - SearchForm::~SearchForm() - { - - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Function for seting the correct notebook/document - */ - void SearchForm::setDocument( Document* document ) - { - document_ = document; - } - - - // PRIVATE SLOTS / MAIN CORE FUNCTION - // ------------------------------------------------------------------ - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Function for searching a word - */ - void SearchForm::search() - { - if( !document_ ) - { - QMessageBox::information( this, "Information", "This window don't contain a document." ); - return; - } - - // check if document is empty - if( document_->isEmpty() ) - { - QMessageBox::information( this, "Information", "This notebook is empty." ); - return; - } - - // find text - searchText_ = ui.searchComboBox_->currentText(); - if( searchText_.isEmpty() ) - { - QMessageBox::information( this, "Information", "You must enter a text that should be searched for." ); - return; - } - - // add filetext to search box - if( ui.searchComboBox_->findText( searchText_ ) == -1 ) - ui.searchComboBox_->addItem( searchText_ ); - - // match case & match word - int options( 0 ); - matchCase_ = ui.matchCaseBox_->isChecked(); - matchWord_ = ui.matchWord_->isChecked(); - if( matchCase_ && matchWord_ ) - options = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; - else if( matchCase_ ) - options = QTextDocument::FindCaseSensitively; - else if( matchWord_ ) - options = QTextDocument::FindWholeWords; - - // get options (inside group & search direction) and current cell - bool insideClosedCell = ui.insideGroupCellBox_->isChecked(); - bool searchDown = ui.downRadioButton_->isChecked(); - Cell* currentCell = document_->getCursor()->currentCell(); - - // if no currentCell, use first cell in document - if( !currentCell ) - currentCell = document_->getMainCell(); - - if( !currentCell ) - { - QMessageBox::information( this, "Information", "No cell is selected. Please select a cell and try again." ); - return; - } - - // SEARCH - bool foundText( false ); - while( !foundText ) - { - // if cell have a editor, search in it. - QTextEdit* editor; - if( currentCell ) - { - editor = currentCell->textEdit(); - if( editor ) - { - // FIND FUNCTION - if( searchDown ) - { - if( editor->find( searchText_, (QTextDocument::FindFlag)options )) - { - // TODO: Activate Main Window, don't know if it is necessary - //parentWidget()->activateWindow(); - break; - } - } - else - { - if( editor->find( searchText_, (QTextDocument::FindFlag)options | QTextDocument::FindBackward )) - { - // TODO: Activate Main Window, don't know if it is necessary - //parentWidget()->activateWindow(); - break; - } - } - } - - // search inside inputcells - if( typeid( (*currentCell) ) == typeid( InputCell ) ) - { - InputCell* inputcell = dynamic_cast( currentCell ); - if( inputcell ) - { - // only look inside open inputcells - if( !inputcell->isClosed() ) - { - editor = inputcell->textEditOutput(); - if( editor ) - { - // FIND FUNCTION - if( searchDown ) - { - if( editor->find( searchText_, (QTextDocument::FindFlag)options )) - break; - } - else - { - if( editor->find( searchText_, (QTextDocument::FindFlag)options | QTextDocument::FindBackward )) - break; - } - } - } - } - } - } - - // no hit in cell, move to next cell - if( searchDown ) - { - // DOWN - // check if the cell after the current cell is a closed cell, if so open it. - if( insideClosedCell ) - { - if( currentCell ) - { - Cell* nextCell = currentCell->next(); // this cell should be the cellcursor - if( nextCell ) - { - if( typeid( (*nextCell) ) == typeid( CellCursor ) ) - { - Cell* nextCellAgain = nextCell->next(); - if( nextCellAgain ) - { - if( typeid( (*nextCellAgain) ) == typeid( CellGroup ) ) - { - CellGroup* groupcell = dynamic_cast( nextCellAgain ); - if( groupcell ) - { - if( groupcell->isClosed() ) - { - groupcell->setClosed( false, false ); - groupcell->closeChildCells(); - openedCells_.push_back( groupcell ); - } - } - } - else if( typeid( (*nextCellAgain) ) == typeid( InputCell ) ) - { - InputCell* inputcell = dynamic_cast( nextCellAgain ); - if( inputcell ) - { - if( inputcell->isClosed() ) - { - inputcell->setClosed( false, false ); - openedCells_.push_back( inputcell ); - } - } - } - } - } - } - } - } - - // before moving, clear last cursor selection - if( currentCell->textEdit() ) - { - QTextCursor cursor = currentCell->textEdit()->textCursor(); - cursor.clearSelection(); - currentCell->textEdit()->setTextCursor( cursor ); - - // if inputcell, clear output also - if( typeid( (*currentCell) ) == typeid( InputCell ) ) - { - InputCell* inputcell = dynamic_cast( currentCell ); - if( inputcell ) - { - QTextCursor cursor = inputcell->textEditOutput()->textCursor(); - cursor.clearSelection(); - inputcell->textEditOutput()->setTextCursor( cursor ); - } - } - } - - if( document_->getCursor()->moveDown() ) - { - // after move, update scrollarea - document_->updateScrollArea(); - - // moved down one cell, get new currentcell - currentCell = document_->getCursor()->currentCell(); - - // if the new currentCell have a text editor, move the text cursor to pos 'start' - if( currentCell ) - { - editor = currentCell->textEdit(); - if( editor ) - { - QTextCursor cursor = editor->textCursor(); - cursor.movePosition( QTextCursor::Start ); - editor->setTextCursor( cursor ); - } - - // if inputcell, also move the cursor of the output - if( typeid( (*currentCell) ) == typeid( InputCell ) ) - { - InputCell* inputcell = dynamic_cast( currentCell ); - if( inputcell ) - { - editor = inputcell->textEditOutput(); - if( editor ) - { - QTextCursor cursor = editor->textCursor(); - cursor.movePosition( QTextCursor::Start ); - editor->setTextCursor( cursor ); - } - } - } - } - } - else - { - // unable to move down, assume that the cursor have reached end of document - QString msg = QString( "Reached end of document. No more instances of '" ) + - searchText_ + QString( "' found." ); - QMessageBox::information( this, "Information", msg ); - return; - } - } - else - { - // UP - // before moving, clear last cursor selection - if( currentCell->textEdit() ) - { - QTextCursor cursor = currentCell->textEdit()->textCursor(); - cursor.clearSelection(); - currentCell->textEdit()->setTextCursor( cursor ); - - // if inputcell, clear output also - if( typeid( (*currentCell) ) == typeid( InputCell ) ) - { - InputCell* inputcell = dynamic_cast( currentCell ); - if( inputcell ) - { - QTextCursor cursor = inputcell->textEditOutput()->textCursor(); - cursor.clearSelection(); - inputcell->textEditOutput()->setTextCursor( cursor ); - } - } - } - - // move - if( document_->getCursor()->moveUp() ) - { - // after move, update scrollarea - document_->updateScrollArea(); - - // moved up one cell - currentCell = document_->getCursor()->currentCell(); - if( currentCell ) - { - // if the new currentCell have a text editor, - // move the text cursor to pos 'end' - editor = currentCell->textEdit(); - if( editor ) - { - QTextCursor cursor = editor->textCursor(); - cursor.movePosition( QTextCursor::End ); - editor->setTextCursor( cursor ); - } - - // if inputcell, also move the cursor of the output - if( typeid( (*currentCell) ) == typeid( InputCell ) ) - { - InputCell* inputcell = dynamic_cast( currentCell ); - if( inputcell ) - { - editor = inputcell->textEditOutput(); - if( editor ) - { - QTextCursor cursor = editor->textCursor(); - cursor.movePosition( QTextCursor::End ); - editor->setTextCursor( cursor ); - } - } - } - - // if the new currentCell is closed and the option inside cells is set, - // open the new cell - if( insideClosedCell && currentCell->isClosed() ) - { - if( typeid( (*currentCell) ) == typeid( CellGroup ) ) - { - CellGroup* groupcell = dynamic_cast( currentCell ); - if( groupcell ) - { - groupcell->setClosed( false, false ); - groupcell->closeChildCells(); - openedCells_.push_back( currentCell ); - } - } - } - } - } - else - { - // unable to move up, assume that the cursor have reached start of document - QString msg = QString( "Reached start of document. No more instances of '" ) + - searchText_ + QString( "' found." ); - QMessageBox::information( this, "Information", msg ); - return; - } - } - } - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Function for replaceing a word - */ - void SearchForm::replace() - { - if( !document_ ) - { - QMessageBox::information( this, "Information", "This window don't contain a document." ); - return; - } - - bool correct( false ); - Cell* currentCell = document_->getCursor()->currentCell(); - if( currentCell ) - { - QTextEdit* editor = currentCell->textEdit(); - if( editor ) - { - QTextCursor cursor = editor->textCursor(); - if( cursor.hasSelection() ) - { - // check if correct text is selected - int cs( 0 ); - QString text = cursor.selectedText(); - if( matchCase_ ) - cs = Qt::CaseSensitive; - else - cs = Qt::CaseInsensitive; - - if( text.startsWith( searchText_, ( Qt::CaseSensitivity)cs ) && - text.endsWith( searchText_, ( Qt::CaseSensitivity)cs )) - { - // REPLACE - correct = true; - cursor.insertText( ui.replaceText_->text() ); - } - } - } - } - - // if correct, do search again - if( correct ) - search(); - else - { - QMessageBox::information( this, "Information", "The correct search text isn't selected, can't preform replace." ); - return; - } - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Function for replaceing all word that match the specified - * word. - */ - void SearchForm::replaceAll() - { - // check if document is empty - if( document_ ) - { - if( document_->isEmpty() ) - { - QMessageBox::information( this, "Information", "This document is empty." ); - return; - } - } - else - { - QMessageBox::information( this, "Information", "This window don't contain a document." ); - return; - } - - int count( 0 ); - - // find/replace text - QString findText = ui.searchComboBox_->currentText(); - QString replaceText = ui.replaceText_->text(); - - if( findText.isEmpty() ) - { - QMessageBox::information( this, "Information", "You must enter a text that should be replaced." ); - return; - } - - // clear find/replace text - ui.searchComboBox_->addItem( findText ); - ui.searchComboBox_->clearEditText(); - ui.replaceText_->clear(); - - // start making a composite command in the commandcenter - // create and run the replace all visitor - ReplaceAllVisitor visitor( findText, replaceText, ui.matchCaseBox_->isChecked(), - ui.matchWord_->isChecked(), &count ); - document_->runVisitor( visitor ); - - // done, show message box with status info - QString msg; - msg.setNum( count ); - msg += QString( " instances of the text '" ) + findText + - QString( "' was replaced with the text '" ) + replaceText + QString( "'." ); - QMessageBox::information( this, "Done", msg ); - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Function for showing/hiding the replace function - */ - void SearchForm::showHideReplace() - { - viewReplace_ = !viewReplace_; - showOrHideReplace(); - } - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Close search form and restore any closed cells that had been opened - */ - void SearchForm::closeForm() - { - QList::iterator iter = openedCells_.begin(); - while( iter != openedCells_.end() ) - { - (*iter)->setClosed( true, false ); - if( typeid( (*(*iter)) ) == typeid( CellGroup ) ) - { - CellGroup* groupcell = dynamic_cast( (*iter) ); - if( groupcell ) - groupcell->closeChildCells(); - } - - ++iter; - } - - close(); - } - - // HELP FUNCTIONS - // ------------------------------------------------------------------ - - /*! - * \author Anders Fernström - * \date 2006-08-24 - * - * \brief Help function for showing/hiding the replace function - */ - void SearchForm::showOrHideReplace() - { - if( viewReplace_ ) - { - // View Replace - ui.viewReplaceButton_->hide(); - ui.hideReplaceButton_->show(); - ui.replaceText_->show(); - ui.replaceLabel_->show(); - ui.replaceButton_->show(); - ui.replaceAllButton_->show(); - - setWindowTitle( "Replace Form" ); - } - else - { - // Don't show replace - only search - ui.viewReplaceButton_->show(); - ui.hideReplaceButton_->hide(); - ui.replaceText_->hide(); - ui.replaceLabel_->hide(); - ui.replaceButton_->hide(); - ui.replaceAllButton_->hide(); - - setWindowTitle( "Search Form" ); - } - } + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Class constructor + */ + SearchForm::SearchForm( QWidget* parent, Document* document, bool viewReplace ) + : QDialog( parent ), + document_( document ), + viewReplace_( viewReplace ) + { + ui.setupUi(this); + + // connections + connect( ui.viewReplaceButton_, SIGNAL( clicked() ), + this, SLOT( showHideReplace() )); + connect( ui.hideReplaceButton_, SIGNAL( clicked() ), + this, SLOT( showHideReplace() )); + connect( ui.searchButton_, SIGNAL( clicked() ), + this, SLOT( search() )); + connect( ui.replaceButton_, SIGNAL( clicked() ), + this, SLOT( replace() )); + connect( ui.replaceAllButton_, SIGNAL( clicked() ), + this, SLOT( replaceAll() )); + connect( ui.searchComboBox_, SIGNAL( returnPressed() ), + this, SLOT( search() )); + connect( ui.closeButton_, SIGNAL( clicked() ), + this, SLOT( closeForm() )); + + // Replace stuff + showOrHideReplace(); + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Class destructor + */ + SearchForm::~SearchForm() + { + + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Function for seting the correct notebook/document + */ + void SearchForm::setDocument( Document* document ) + { + document_ = document; + } + + + // PRIVATE SLOTS / MAIN CORE FUNCTION + // ------------------------------------------------------------------ + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Function for searching a word + */ + void SearchForm::search() + { + if( !document_ ) + { + QMessageBox::information( this, "Information", "This window don't contain a document." ); + return; + } + + // check if document is empty + if( document_->isEmpty() ) + { + QMessageBox::information( this, "Information", "This notebook is empty." ); + return; + } + + // find text + searchText_ = ui.searchComboBox_->currentText(); + if( searchText_.isEmpty() ) + { + QMessageBox::information( this, "Information", "You must enter a text that should be searched for." ); + return; + } + + // add filetext to search box + if( ui.searchComboBox_->findText( searchText_ ) == -1 ) + ui.searchComboBox_->addItem( searchText_ ); + + // match case & match word + int options( 0 ); + matchCase_ = ui.matchCaseBox_->isChecked(); + matchWord_ = ui.matchWord_->isChecked(); + if( matchCase_ && matchWord_ ) + options = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; + else if( matchCase_ ) + options = QTextDocument::FindCaseSensitively; + else if( matchWord_ ) + options = QTextDocument::FindWholeWords; + + // get options (inside group & search direction) and current cell + bool insideClosedCell = ui.insideGroupCellBox_->isChecked(); + bool searchDown = ui.downRadioButton_->isChecked(); + Cell* currentCell = document_->getCursor()->currentCell(); + + // if no currentCell, use first cell in document + if( !currentCell ) + currentCell = document_->getMainCell(); + + if( !currentCell ) + { + QMessageBox::information( this, "Information", "No cell is selected. Please select a cell and try again." ); + return; + } + + // SEARCH + bool foundText( false ); + while( !foundText ) + { + // if cell have a editor, search in it. + QTextEdit* editor; + if( currentCell ) + { + editor = currentCell->textEdit(); + if( editor ) + { + // FIND FUNCTION + if( searchDown ) + { + if( editor->find( searchText_, (QTextDocument::FindFlag)options )) + { + // TODO: Activate Main Window, don't know if it is necessary + //parentWidget()->activateWindow(); + break; + } + } + else + { + if( editor->find( searchText_, (QTextDocument::FindFlag)options | QTextDocument::FindBackward )) + { + // TODO: Activate Main Window, don't know if it is necessary + //parentWidget()->activateWindow(); + break; + } + } + } + + // search inside inputcells + if( typeid( (*currentCell) ) == typeid( InputCell ) ) + { + InputCell* inputcell = dynamic_cast( currentCell ); + if( inputcell ) + { + // only look inside open inputcells + if( !inputcell->isClosed() ) + { + editor = inputcell->textEditOutput(); + if( editor ) + { + // FIND FUNCTION + if( searchDown ) + { + if( editor->find( searchText_, (QTextDocument::FindFlag)options )) + break; + } + else + { + if( editor->find( searchText_, (QTextDocument::FindFlag)options | QTextDocument::FindBackward )) + break; + } + } + } + } + } + } + + // no hit in cell, move to next cell + if( searchDown ) + { + // DOWN + // check if the cell after the current cell is a closed cell, if so open it. + if( insideClosedCell ) + { + if( currentCell ) + { + Cell* nextCell = currentCell->next(); // this cell should be the cellcursor + if( nextCell ) + { + if( typeid( (*nextCell) ) == typeid( CellCursor ) ) + { + Cell* nextCellAgain = nextCell->next(); + if( nextCellAgain ) + { + if( typeid( (*nextCellAgain) ) == typeid( CellGroup ) ) + { + CellGroup* groupcell = dynamic_cast( nextCellAgain ); + if( groupcell ) + { + if( groupcell->isClosed() ) + { + groupcell->setClosed( false, false ); + groupcell->closeChildCells(); + openedCells_.push_back( groupcell ); + } + } + } + else if( typeid( (*nextCellAgain) ) == typeid( InputCell ) ) + { + InputCell* inputcell = dynamic_cast( nextCellAgain ); + if( inputcell ) + { + if( inputcell->isClosed() ) + { + inputcell->setClosed( false, false ); + openedCells_.push_back( inputcell ); + } + } + } + } + } + } + } + } + + // before moving, clear last cursor selection + if( currentCell->textEdit() ) + { + QTextCursor cursor = currentCell->textEdit()->textCursor(); + cursor.clearSelection(); + currentCell->textEdit()->setTextCursor( cursor ); + + // if inputcell, clear output also + if( typeid( (*currentCell) ) == typeid( InputCell ) ) + { + InputCell* inputcell = dynamic_cast( currentCell ); + if( inputcell ) + { + QTextCursor cursor = inputcell->textEditOutput()->textCursor(); + cursor.clearSelection(); + inputcell->textEditOutput()->setTextCursor( cursor ); + } + } + } + + if( document_->getCursor()->moveDown() ) + { + // after move, update scrollarea + document_->updateScrollArea(); + + // moved down one cell, get new currentcell + currentCell = document_->getCursor()->currentCell(); + + // if the new currentCell have a text editor, move the text cursor to pos 'start' + if( currentCell ) + { + editor = currentCell->textEdit(); + if( editor ) + { + QTextCursor cursor = editor->textCursor(); + cursor.movePosition( QTextCursor::Start ); + editor->setTextCursor( cursor ); + } + + // if inputcell, also move the cursor of the output + if( typeid( (*currentCell) ) == typeid( InputCell ) ) + { + InputCell* inputcell = dynamic_cast( currentCell ); + if( inputcell ) + { + editor = inputcell->textEditOutput(); + if( editor ) + { + QTextCursor cursor = editor->textCursor(); + cursor.movePosition( QTextCursor::Start ); + editor->setTextCursor( cursor ); + } + } + } + } + } + else + { + // unable to move down, assume that the cursor have reached end of document + QString msg = QString( "Reached end of document. No more instances of '" ) + + searchText_ + QString( "' found." ); + QMessageBox::information( this, "Information", msg ); + return; + } + } + else + { + // UP + // before moving, clear last cursor selection + if( currentCell->textEdit() ) + { + QTextCursor cursor = currentCell->textEdit()->textCursor(); + cursor.clearSelection(); + currentCell->textEdit()->setTextCursor( cursor ); + + // if inputcell, clear output also + if( typeid( (*currentCell) ) == typeid( InputCell ) ) + { + InputCell* inputcell = dynamic_cast( currentCell ); + if( inputcell ) + { + QTextCursor cursor = inputcell->textEditOutput()->textCursor(); + cursor.clearSelection(); + inputcell->textEditOutput()->setTextCursor( cursor ); + } + } + } + + // move + if( document_->getCursor()->moveUp() ) + { + // after move, update scrollarea + document_->updateScrollArea(); + + // moved up one cell + currentCell = document_->getCursor()->currentCell(); + if( currentCell ) + { + // if the new currentCell have a text editor, + // move the text cursor to pos 'end' + editor = currentCell->textEdit(); + if( editor ) + { + QTextCursor cursor = editor->textCursor(); + cursor.movePosition( QTextCursor::End ); + editor->setTextCursor( cursor ); + } + + // if inputcell, also move the cursor of the output + if( typeid( (*currentCell) ) == typeid( InputCell ) ) + { + InputCell* inputcell = dynamic_cast( currentCell ); + if( inputcell ) + { + editor = inputcell->textEditOutput(); + if( editor ) + { + QTextCursor cursor = editor->textCursor(); + cursor.movePosition( QTextCursor::End ); + editor->setTextCursor( cursor ); + } + } + } + + // if the new currentCell is closed and the option inside cells is set, + // open the new cell + if( insideClosedCell && currentCell->isClosed() ) + { + if( typeid( (*currentCell) ) == typeid( CellGroup ) ) + { + CellGroup* groupcell = dynamic_cast( currentCell ); + if( groupcell ) + { + groupcell->setClosed( false, false ); + groupcell->closeChildCells(); + openedCells_.push_back( currentCell ); + } + } + } + } + } + else + { + // unable to move up, assume that the cursor have reached start of document + QString msg = QString( "Reached start of document. No more instances of '" ) + + searchText_ + QString( "' found." ); + QMessageBox::information( this, "Information", msg ); + return; + } + } + } + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Function for replaceing a word + */ + void SearchForm::replace() + { + if( !document_ ) + { + QMessageBox::information( this, "Information", "This window don't contain a document." ); + return; + } + + bool correct( false ); + Cell* currentCell = document_->getCursor()->currentCell(); + if( currentCell ) + { + QTextEdit* editor = currentCell->textEdit(); + if( editor ) + { + QTextCursor cursor = editor->textCursor(); + if( cursor.hasSelection() ) + { + // check if correct text is selected + int cs( 0 ); + QString text = cursor.selectedText(); + if( matchCase_ ) + cs = Qt::CaseSensitive; + else + cs = Qt::CaseInsensitive; + + if( text.startsWith( searchText_, ( Qt::CaseSensitivity)cs ) && + text.endsWith( searchText_, ( Qt::CaseSensitivity)cs )) + { + // REPLACE + correct = true; + cursor.insertText( ui.replaceText_->text() ); + } + } + } + } + + // if correct, do search again + if( correct ) + search(); + else + { + QMessageBox::information( this, "Information", "The correct search text isn't selected, can't preform replace." ); + return; + } + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Function for replaceing all word that match the specified + * word. + */ + void SearchForm::replaceAll() + { + // check if document is empty + if( document_ ) + { + if( document_->isEmpty() ) + { + QMessageBox::information( this, "Information", "This document is empty." ); + return; + } + } + else + { + QMessageBox::information( this, "Information", "This window don't contain a document." ); + return; + } + + int count( 0 ); + + // find/replace text + QString findText = ui.searchComboBox_->currentText(); + QString replaceText = ui.replaceText_->text(); + + if( findText.isEmpty() ) + { + QMessageBox::information( this, "Information", "You must enter a text that should be replaced." ); + return; + } + + // clear find/replace text + ui.searchComboBox_->addItem( findText ); + ui.searchComboBox_->clearEditText(); + ui.replaceText_->clear(); + + // start making a composite command in the commandcenter + // create and run the replace all visitor + ReplaceAllVisitor visitor( findText, replaceText, ui.matchCaseBox_->isChecked(), + ui.matchWord_->isChecked(), &count ); + document_->runVisitor( visitor ); + + // done, show message box with status info + QString msg; + msg.setNum( count ); + msg += QString( " instances of the text '" ) + findText + + QString( "' was replaced with the text '" ) + replaceText + QString( "'." ); + QMessageBox::information( this, "Done", msg ); + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Function for showing/hiding the replace function + */ + void SearchForm::showHideReplace() + { + viewReplace_ = !viewReplace_; + showOrHideReplace(); + } + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Close search form and restore any closed cells that had been opened + */ + void SearchForm::closeForm() + { + QList::iterator iter = openedCells_.begin(); + while( iter != openedCells_.end() ) + { + (*iter)->setClosed( true, false ); + if( typeid( (*(*iter)) ) == typeid( CellGroup ) ) + { + CellGroup* groupcell = dynamic_cast( (*iter) ); + if( groupcell ) + groupcell->closeChildCells(); + } + + ++iter; + } + + close(); + } + + // HELP FUNCTIONS + // ------------------------------------------------------------------ + + /*! + * \author Anders Fernström + * \date 2006-08-24 + * + * \brief Help function for showing/hiding the replace function + */ + void SearchForm::showOrHideReplace() + { + if( viewReplace_ ) + { + // View Replace + ui.viewReplaceButton_->hide(); + ui.hideReplaceButton_->show(); + ui.replaceText_->show(); + ui.replaceLabel_->show(); + ui.replaceButton_->show(); + ui.replaceAllButton_->show(); + + setWindowTitle( "Replace Form" ); + } + else + { + // Don't show replace - only search + ui.viewReplaceButton_->show(); + ui.hideReplaceButton_->hide(); + ui.replaceText_->hide(); + ui.replaceLabel_->hide(); + ui.replaceButton_->hide(); + ui.replaceAllButton_->hide(); + + setWindowTitle( "Search Form" ); + } + } } diff --git a/OMNotebook/OMNotebookQT4/searchform.h b/OMNotebook/OMNotebookQT4/searchform.h index ee96865a884..2da8488de92 100644 --- a/OMNotebook/OMNotebookQT4/searchform.h +++ b/OMNotebook/OMNotebookQT4/searchform.h @@ -46,40 +46,40 @@ namespace IAEX { - // forward declaration - class Document; - class Cell; + // forward declaration + class Document; + class Cell; - class SearchForm : public QDialog - { - Q_OBJECT + class SearchForm : public QDialog + { + Q_OBJECT - public: - SearchForm(QWidget* parent, Document* document, bool viewReplace = false); - ~SearchForm(); + public: + SearchForm(QWidget* parent, Document* document, bool viewReplace = false); + ~SearchForm(); - void setDocument( Document* document ); + void setDocument( Document* document ); - private slots: - void search(); - void replace(); - void replaceAll(); - void showHideReplace(); - void closeForm(); + private slots: + void search(); + void replace(); + void replaceAll(); + void showHideReplace(); + void closeForm(); - private: - void showOrHideReplace(); + private: + void showOrHideReplace(); - private: - Ui::SearchFormClass ui; + private: + Ui::SearchFormClass ui; - QString searchText_; - QList openedCells_; + QString searchText_; + QList openedCells_; - Document* document_; - bool viewReplace_; - bool matchCase_; - bool matchWord_; - }; + Document* document_; + bool viewReplace_; + bool matchCase_; + bool matchWord_; + }; } #endif // SEARCHFORM_H diff --git a/OMNotebook/OMNotebookQT4/serializingvisitor.cpp b/OMNotebook/OMNotebookQT4/serializingvisitor.cpp index 196a5c19a10..dc3f7c33c9a 100644 --- a/OMNotebook/OMNotebookQT4/serializingvisitor.cpp +++ b/OMNotebook/OMNotebookQT4/serializingvisitor.cpp @@ -67,442 +67,442 @@ namespace IAEX { - /*! - * \class SerializingVisitor - * \date 2005-11-30 (update) - * - * \brief Saves a celltree to an xml file, by converting cell - * structure to XML. - * - * Traverses the cellstructure and creates a serialized - * stream of the internal representation of the document. - * - * 2005-11-30 AF, This class was remade when another xml format - * was used to save the cell structure. - */ - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2005-11-30 (update) - * - * \brief The class constructor - */ - SerializingVisitor::SerializingVisitor( QDomDocument &domdoc, Document* doc) - : domdoc_(domdoc), - doc_(doc) - { - currentElement_ = domdoc_.createElement( XML_NOTEBOOK ); - domdoc_.appendChild( currentElement_ ); - } - - /*! - * \author Ingemar Axelsson - * - * \brief The class deconstructor - */ - SerializingVisitor::~SerializingVisitor() - {} - - - // CELL - // ****************************************************************** - void SerializingVisitor::visitCellNodeBefore(Cell *) - {} - - void SerializingVisitor::visitCellNodeAfter(Cell *) - {} - - - // GROUPCELL - // ****************************************************************** - void SerializingVisitor::visitCellGroupNodeBefore(CellGroup *node) - { - parents_.push( currentElement_ ); - QDomElement groupcell = domdoc_.createElement( XML_GROUPCELL ); - currentElement_.appendChild( groupcell ); - - if( node->isClosed() ) - groupcell.setAttribute( XML_CLOSED, XML_TRUE ); - else - groupcell.setAttribute( XML_CLOSED, XML_FALSE ); - - // set the new current element - currentElement_ = groupcell; - } - - void SerializingVisitor::visitCellGroupNodeAfter(CellGroup *) - { - currentElement_ = parents_.top(); - parents_.pop(); - } - - - // TEXTCELL - // ****************************************************************** - void SerializingVisitor::visitTextCellNodeBefore(TextCell *node) - { - QDomElement textcell = domdoc_.createElement( XML_TEXTCELL ); - - // Make sure that the text is viewed correct - node->viewExpression(false); - - // Add style setting to textcell element - textcell.setAttribute( XML_STYLE, node->style()->name() ); - - // Create an text element and append an text node to the element - QDomElement textelement = domdoc_.createElement( XML_TEXT ); - QDomText textnode = domdoc_.createTextNode( node->textHtml() ); - textelement.appendChild( textnode ); - textcell.appendChild( textelement ); - - // Creates ruleelemetns - Cell::rules_t r = node->rules(); - Cell::rules_t::const_iterator r_iter = r.begin(); - for( ; r_iter != r.end(); ++r_iter ) - { - QDomElement ruleelement = domdoc_.createElement( XML_RULE ); - ruleelement.setAttribute( XML_NAME, (*r_iter)->attribute() ); - - QDomText rulenode = domdoc_.createTextNode( (*r_iter)->value() ); - ruleelement.appendChild( rulenode ); - - textcell.appendChild( ruleelement ); - } - - // Check if any image have been include in the text and add them - // to the the the textcell element - QString xoyz = node->textHtml(); - saveImages( textcell, xoyz ); - - // Add textcell element to current element - currentElement_.appendChild( textcell ); - } - - void SerializingVisitor::visitTextCellNodeAfter(TextCell *) - {} - - - //INPUTCELL - // ****************************************************************** - void SerializingVisitor::visitInputCellNodeBefore(InputCell *node) - { - QDomElement inputcell = domdoc_.createElement( XML_INPUTCELL ); - - // Add style setting to inputcell element - inputcell.setAttribute( XML_STYLE, node->style()->name() ); - - // Add close setting to inputcell element - if( node->isClosed() ) - inputcell.setAttribute( XML_CLOSED, XML_TRUE ); - else - inputcell.setAttribute( XML_CLOSED, XML_FALSE ); - - // Create an text element (for input) and append it to the element - QDomElement inputelement = domdoc_.createElement( XML_INPUTPART ); - QDomText inputnode = domdoc_.createTextNode( node->text() ); - inputelement.appendChild( inputnode ); - inputcell.appendChild( inputelement ); + /*! + * \class SerializingVisitor + * \date 2005-11-30 (update) + * + * \brief Saves a celltree to an xml file, by converting cell + * structure to XML. + * + * Traverses the cellstructure and creates a serialized + * stream of the internal representation of the document. + * + * 2005-11-30 AF, This class was remade when another xml format + * was used to save the cell structure. + */ + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2005-11-30 (update) + * + * \brief The class constructor + */ + SerializingVisitor::SerializingVisitor( QDomDocument &domdoc, Document* doc) + : domdoc_(domdoc), + doc_(doc) + { + currentElement_ = domdoc_.createElement( XML_NOTEBOOK ); + domdoc_.appendChild( currentElement_ ); + } + + /*! + * \author Ingemar Axelsson + * + * \brief The class deconstructor + */ + SerializingVisitor::~SerializingVisitor() + {} + + + // CELL + // ****************************************************************** + void SerializingVisitor::visitCellNodeBefore(Cell *) + {} + + void SerializingVisitor::visitCellNodeAfter(Cell *) + {} + + + // GROUPCELL + // ****************************************************************** + void SerializingVisitor::visitCellGroupNodeBefore(CellGroup *node) + { + parents_.push( currentElement_ ); + QDomElement groupcell = domdoc_.createElement( XML_GROUPCELL ); + currentElement_.appendChild( groupcell ); + + if( node->isClosed() ) + groupcell.setAttribute( XML_CLOSED, XML_TRUE ); + else + groupcell.setAttribute( XML_CLOSED, XML_FALSE ); + + // set the new current element + currentElement_ = groupcell; + } + + void SerializingVisitor::visitCellGroupNodeAfter(CellGroup *) + { + currentElement_ = parents_.top(); + parents_.pop(); + } + + + // TEXTCELL + // ****************************************************************** + void SerializingVisitor::visitTextCellNodeBefore(TextCell *node) + { + QDomElement textcell = domdoc_.createElement( XML_TEXTCELL ); + + // Make sure that the text is viewed correct + node->viewExpression(false); + + // Add style setting to textcell element + textcell.setAttribute( XML_STYLE, node->style()->name() ); + + // Create an text element and append an text node to the element + QDomElement textelement = domdoc_.createElement( XML_TEXT ); + QDomText textnode = domdoc_.createTextNode( node->textHtml() ); + textelement.appendChild( textnode ); + textcell.appendChild( textelement ); + + // Creates ruleelemetns + Cell::rules_t r = node->rules(); + Cell::rules_t::const_iterator r_iter = r.begin(); + for( ; r_iter != r.end(); ++r_iter ) + { + QDomElement ruleelement = domdoc_.createElement( XML_RULE ); + ruleelement.setAttribute( XML_NAME, (*r_iter)->attribute() ); + + QDomText rulenode = domdoc_.createTextNode( (*r_iter)->value() ); + ruleelement.appendChild( rulenode ); + + textcell.appendChild( ruleelement ); + } + + // Check if any image have been include in the text and add them + // to the the the textcell element + QString xoyz = node->textHtml(); + saveImages( textcell, xoyz ); + + // Add textcell element to current element + currentElement_.appendChild( textcell ); + } + + void SerializingVisitor::visitTextCellNodeAfter(TextCell *) + {} + + + //INPUTCELL + // ****************************************************************** + void SerializingVisitor::visitInputCellNodeBefore(InputCell *node) + { + QDomElement inputcell = domdoc_.createElement( XML_INPUTCELL ); + + // Add style setting to inputcell element + inputcell.setAttribute( XML_STYLE, node->style()->name() ); + + // Add close setting to inputcell element + if( node->isClosed() ) + inputcell.setAttribute( XML_CLOSED, XML_TRUE ); + else + inputcell.setAttribute( XML_CLOSED, XML_FALSE ); + + // Create an text element (for input) and append it to the element + QDomElement inputelement = domdoc_.createElement( XML_INPUTPART ); + QDomText inputnode = domdoc_.createTextNode( node->text() ); + inputelement.appendChild( inputnode ); + inputcell.appendChild( inputelement ); - // Create an text element (for output) and append it to the element - QDomElement outputelement = domdoc_.createElement( XML_OUTPUTPART ); - - QDomText outputnode; - if( node->isJavaPlot() ) - outputnode = domdoc_.createTextNode( node->textOutputHtml() ); - else - outputnode = domdoc_.createTextNode( node->textOutput() ); - - outputelement.appendChild( outputnode ); - inputcell.appendChild( outputelement ); - - // Creates ruleelemetns - Cell::rules_t r = node->rules(); - Cell::rules_t::const_iterator r_iter = r.begin(); - for( ; r_iter != r.end(); ++r_iter ) - { - QDomElement ruleelement = domdoc_.createElement( XML_RULE ); - ruleelement.setAttribute( XML_NAME, (*r_iter)->attribute() ); - - QDomText rulenode = domdoc_.createTextNode( (*r_iter)->value() ); - ruleelement.appendChild( rulenode ); - - inputcell.appendChild( ruleelement ); - } - - // Check if any image have been include in the text and add them - // to the the the inputcell element - QString xoyz = node->textOutputHtml(); - saveImages( inputcell, xoyz ); - - // Add inputcell element to current element - currentElement_.appendChild( inputcell ); - } - - void SerializingVisitor::visitInputCellNodeAfter(InputCell *) - {} - - //GRAPHCELL - // ****************************************************************** - void SerializingVisitor::visitGraphCellNodeBefore(GraphCell *node) - { - QDomElement graphcell = domdoc_.createElement( XML_GRAPHCELL ); - - // Add style setting to inputcell element - graphcell.setAttribute( XML_STYLE, node->style()->name() ); - - - // Add close setting to inputcell element - if( node->isClosed() ) - graphcell.setAttribute( XML_CLOSED, XML_TRUE ); - else - graphcell.setAttribute( XML_CLOSED, XML_FALSE ); - - QBuffer b; - b.open( QBuffer::WriteOnly ); - QDataStream ds( &b ); + // Create an text element (for output) and append it to the element + QDomElement outputelement = domdoc_.createElement( XML_OUTPUTPART ); + + QDomText outputnode; + if( node->isJavaPlot() ) + outputnode = domdoc_.createTextNode( node->textOutputHtml() ); + else + outputnode = domdoc_.createTextNode( node->textOutput() ); + + outputelement.appendChild( outputnode ); + inputcell.appendChild( outputelement ); + + // Creates ruleelemetns + Cell::rules_t r = node->rules(); + Cell::rules_t::const_iterator r_iter = r.begin(); + for( ; r_iter != r.end(); ++r_iter ) + { + QDomElement ruleelement = domdoc_.createElement( XML_RULE ); + ruleelement.setAttribute( XML_NAME, (*r_iter)->attribute() ); + + QDomText rulenode = domdoc_.createTextNode( (*r_iter)->value() ); + ruleelement.appendChild( rulenode ); + + inputcell.appendChild( ruleelement ); + } + + // Check if any image have been include in the text and add them + // to the the the inputcell element + QString xoyz = node->textOutputHtml(); + saveImages( inputcell, xoyz ); + + // Add inputcell element to current element + currentElement_.appendChild( inputcell ); + } + + void SerializingVisitor::visitInputCellNodeAfter(InputCell *) + {} + + //GRAPHCELL + // ****************************************************************** + void SerializingVisitor::visitGraphCellNodeBefore(GraphCell *node) + { + QDomElement graphcell = domdoc_.createElement( XML_GRAPHCELL ); + + // Add style setting to inputcell element + graphcell.setAttribute( XML_STYLE, node->style()->name() ); + + + // Add close setting to inputcell element + if( node->isClosed() ) + graphcell.setAttribute( XML_CLOSED, XML_TRUE ); + else + graphcell.setAttribute( XML_CLOSED, XML_FALSE ); + + QBuffer b; + b.open( QBuffer::WriteOnly ); + QDataStream ds( &b ); - ds << node->compoundwidget->gwMain->mapToScene(node->compoundwidget->gwMain->rect()).boundingRect(); - b.close(); + ds << node->compoundwidget->gwMain->mapToScene(node->compoundwidget->gwMain->rect()).boundingRect(); + b.close(); - graphcell.setAttribute( XML_GRAPHCELL_AREA, QString(b.data().toBase64().data())); + graphcell.setAttribute( XML_GRAPHCELL_AREA, QString(b.data().toBase64().data())); - graphcell.setAttribute( XML_GRAPHCELL_LEGEND, node->compoundwidget->legendFrame->isVisible()?XML_TRUE:XML_FALSE); - graphcell.setAttribute( XML_GRAPHCELL_AA, node->compoundwidget->gwMain->antiAliasing?XML_TRUE:XML_FALSE ); - graphcell.setAttribute( XML_GRAPHCELL_LOGX, node->compoundwidget->gwMain->xLog?XML_TRUE:XML_FALSE ); - graphcell.setAttribute( XML_GRAPHCELL_LOGY, node->compoundwidget->gwMain->yLog?XML_TRUE:XML_FALSE ); - graphcell.setAttribute( XML_GRAPHCELL_TITLE, node->compoundwidget->plotTitle->text()); - graphcell.setAttribute( XML_GRAPHCELL_XLABEL, node->compoundwidget->xLabel->text() ); - graphcell.setAttribute( XML_GRAPHCELL_YLABEL, node->compoundwidget->yLabel->text() ); - graphcell.setAttribute( XML_GRAPHCELL_GRID, node->compoundwidget->gwMain->graphicsScene->gridVisible?XML_TRUE:XML_FALSE ); - graphcell.setAttribute( XML_GRAPHCELL_GRIDAUTOX, node->compoundwidget->gwMain->fixedXSize?XML_FALSE:XML_TRUE ); - graphcell.setAttribute( XML_GRAPHCELL_GRIDAUTOY, node->compoundwidget->gwMain->fixedYSize?XML_FALSE:XML_TRUE ); + graphcell.setAttribute( XML_GRAPHCELL_LEGEND, node->compoundwidget->legendFrame->isVisible()?XML_TRUE:XML_FALSE); + graphcell.setAttribute( XML_GRAPHCELL_AA, node->compoundwidget->gwMain->antiAliasing?XML_TRUE:XML_FALSE ); + graphcell.setAttribute( XML_GRAPHCELL_LOGX, node->compoundwidget->gwMain->xLog?XML_TRUE:XML_FALSE ); + graphcell.setAttribute( XML_GRAPHCELL_LOGY, node->compoundwidget->gwMain->yLog?XML_TRUE:XML_FALSE ); + graphcell.setAttribute( XML_GRAPHCELL_TITLE, node->compoundwidget->plotTitle->text()); + graphcell.setAttribute( XML_GRAPHCELL_XLABEL, node->compoundwidget->xLabel->text() ); + graphcell.setAttribute( XML_GRAPHCELL_YLABEL, node->compoundwidget->yLabel->text() ); + graphcell.setAttribute( XML_GRAPHCELL_GRID, node->compoundwidget->gwMain->graphicsScene->gridVisible?XML_TRUE:XML_FALSE ); + graphcell.setAttribute( XML_GRAPHCELL_GRIDAUTOX, node->compoundwidget->gwMain->fixedXSize?XML_FALSE:XML_TRUE ); + graphcell.setAttribute( XML_GRAPHCELL_GRIDAUTOY, node->compoundwidget->gwMain->fixedYSize?XML_FALSE:XML_TRUE ); - graphcell.setAttribute( XML_GRAPHCELL_GRIDMAJORX, QVariant(node->compoundwidget->gwMain->xMajorDist).toString()); - graphcell.setAttribute( XML_GRAPHCELL_GRIDMAJORY, QVariant(node->compoundwidget->gwMain->yMajorDist).toString() ); - graphcell.setAttribute( XML_GRAPHCELL_GRIDMINORX, QVariant(node->compoundwidget->gwMain->xMinorDist).toString()); - graphcell.setAttribute( XML_GRAPHCELL_GRIDMINORY, QVariant(node->compoundwidget->gwMain->yMinorDist).toString()); - graphcell.setAttribute( XML_GRAPHCELL_SHOWGRAPH, node->showGraph?XML_TRUE:XML_FALSE); + graphcell.setAttribute( XML_GRAPHCELL_GRIDMAJORX, QVariant(node->compoundwidget->gwMain->xMajorDist).toString()); + graphcell.setAttribute( XML_GRAPHCELL_GRIDMAJORY, QVariant(node->compoundwidget->gwMain->yMajorDist).toString() ); + graphcell.setAttribute( XML_GRAPHCELL_GRIDMINORX, QVariant(node->compoundwidget->gwMain->xMinorDist).toString()); + graphcell.setAttribute( XML_GRAPHCELL_GRIDMINORY, QVariant(node->compoundwidget->gwMain->yMinorDist).toString()); + graphcell.setAttribute( XML_GRAPHCELL_SHOWGRAPH, node->showGraph?XML_TRUE:XML_FALSE); int sizeVars = node->compoundwidget->gwMain->variableData.size(); for(int i = 0; i < sizeVars; ++i) { - QDomElement data = domdoc_.createElement(XML_GRAPHCELL_DATA); + QDomElement data = domdoc_.createElement(XML_GRAPHCELL_DATA); CompoundWidget *cw = node->compoundwidget; GraphWidget *gw = cw->gwMain; VariableData *vd = gw->variableData[i]; QString varName = vd->variableName(); - data.setAttribute(XML_GRAPHCELL_LABEL, varName); - data.setAttribute(XML_GRAPHCELL_ID, "0"); + data.setAttribute(XML_GRAPHCELL_LABEL, varName); + data.setAttribute(XML_GRAPHCELL_ID, "0"); - QBuffer b; - b.open( QBuffer::WriteOnly ); - QDataStream ds( &b ); + QBuffer b; + b.open( QBuffer::WriteOnly ); + QDataStream ds( &b ); - ds << *(node->compoundwidget->gwMain->variableData[i]); - b.close(); + ds << *(node->compoundwidget->gwMain->variableData[i]); + b.close(); - QDomText dnode = domdoc_.createTextNode(b.buffer().toBase64()); - data.appendChild(dnode); - graphcell.appendChild(data); + QDomText dnode = domdoc_.createTextNode(b.buffer().toBase64()); + data.appendChild(dnode); + graphcell.appendChild(data); } for(int i = 0; i < node->compoundwidget->gwMain->curves.size(); ++i) { - QDomElement graph = domdoc_.createElement(XML_GRAPHCELL_GRAPH); - if(node->compoundwidget->gwMain->curves[i]->visible) - graph.setAttribute(XML_GRAPHCELL_LINE, XML_TRUE); - else - graph.setAttribute(XML_GRAPHCELL_LINE, XML_FALSE); - - if(node->compoundwidget->gwMain->curves[i]->drawPoints) - graph.setAttribute(XML_GRAPHCELL_POINTS, XML_TRUE); - else - graph.setAttribute(XML_GRAPHCELL_POINTS, XML_FALSE); - - graph.setAttribute(XML_GRAPHCELL_COLOR, QVariant(node->compoundwidget->gwMain->curves[i]->color_).toString()); - - if(node->compoundwidget->gwMain->curves[i]->interpolation = INTERPOLATION_NONE) - graph.setAttribute(XML_GRAPHCELL_INTERPOLATION, XML_GRAPHCELL_NONE); - else if(node->compoundwidget->gwMain->curves[i]->interpolation = INTERPOLATION_LINEAR) - graph.setAttribute(XML_GRAPHCELL_INTERPOLATION, XML_GRAPHCELL_LINEAR); - else if(node->compoundwidget->gwMain->curves[i]->interpolation = INTERPOLATION_CONSTANT) - graph.setAttribute(XML_GRAPHCELL_INTERPOLATION, XML_GRAPHCELL_CONSTANT); - - graph.setAttribute(XML_GRAPHCELL_X, node->compoundwidget->gwMain->curves[i]->x->variableName()); - graph.setAttribute(XML_GRAPHCELL_Y, node->compoundwidget->gwMain->curves[i]->y->variableName()); - - graphcell.appendChild(graph); + QDomElement graph = domdoc_.createElement(XML_GRAPHCELL_GRAPH); + if(node->compoundwidget->gwMain->curves[i]->visible) + graph.setAttribute(XML_GRAPHCELL_LINE, XML_TRUE); + else + graph.setAttribute(XML_GRAPHCELL_LINE, XML_FALSE); + + if(node->compoundwidget->gwMain->curves[i]->drawPoints) + graph.setAttribute(XML_GRAPHCELL_POINTS, XML_TRUE); + else + graph.setAttribute(XML_GRAPHCELL_POINTS, XML_FALSE); + + graph.setAttribute(XML_GRAPHCELL_COLOR, QVariant(node->compoundwidget->gwMain->curves[i]->color_).toString()); + + if(node->compoundwidget->gwMain->curves[i]->interpolation = INTERPOLATION_NONE) + graph.setAttribute(XML_GRAPHCELL_INTERPOLATION, XML_GRAPHCELL_NONE); + else if(node->compoundwidget->gwMain->curves[i]->interpolation = INTERPOLATION_LINEAR) + graph.setAttribute(XML_GRAPHCELL_INTERPOLATION, XML_GRAPHCELL_LINEAR); + else if(node->compoundwidget->gwMain->curves[i]->interpolation = INTERPOLATION_CONSTANT) + graph.setAttribute(XML_GRAPHCELL_INTERPOLATION, XML_GRAPHCELL_CONSTANT); + + graph.setAttribute(XML_GRAPHCELL_X, node->compoundwidget->gwMain->curves[i]->x->variableName()); + graph.setAttribute(XML_GRAPHCELL_Y, node->compoundwidget->gwMain->curves[i]->y->variableName()); + + graphcell.appendChild(graph); } QList l = node->compoundwidget->gwMain->graphicsItems->children(); for(int i = 0; i < l.size(); ++i) { - QBuffer b; - b.open( QBuffer::WriteOnly ); - QDataStream ds( &b ); - ds.setVersion(QDataStream::Qt_4_2); - - QDomElement shape = domdoc_.createElement(XML_GRAPHCELL_SHAPE); - QString type; - - if(QGraphicsRectItem* r =dynamic_cast(l[i])) - { - type = XML_GRAPHCELL_RECT; - ds << r->rect() << r->pen() << r->brush(); - } - else if(QGraphicsEllipseItem* r =dynamic_cast(l[i])) - { - type = XML_GRAPHCELL_ELLIPSE; - ds << r->rect() << r->pen() << r->brush(); - - } - else if(QGraphicsLineItem* r =dynamic_cast(l[i])) - { - type = XML_GRAPHCELL_LINE; - ds << r->line() << r->pen(); - } - - shape.setAttribute(XML_GRAPHCELL_SHAPETYPE, type); - - b.close(); - shape.setAttribute( XML_GRAPHCELL_SHAPEDATA, QString(b.data().toBase64().data())); - - graphcell.appendChild(shape); + QBuffer b; + b.open( QBuffer::WriteOnly ); + QDataStream ds( &b ); + ds.setVersion(QDataStream::Qt_4_2); + + QDomElement shape = domdoc_.createElement(XML_GRAPHCELL_SHAPE); + QString type; + + if(QGraphicsRectItem* r =dynamic_cast(l[i])) + { + type = XML_GRAPHCELL_RECT; + ds << r->rect() << r->pen() << r->brush(); + } + else if(QGraphicsEllipseItem* r =dynamic_cast(l[i])) + { + type = XML_GRAPHCELL_ELLIPSE; + ds << r->rect() << r->pen() << r->brush(); + + } + else if(QGraphicsLineItem* r =dynamic_cast(l[i])) + { + type = XML_GRAPHCELL_LINE; + ds << r->line() << r->pen(); + } + + shape.setAttribute(XML_GRAPHCELL_SHAPETYPE, type); + + b.close(); + shape.setAttribute( XML_GRAPHCELL_SHAPEDATA, QString(b.data().toBase64().data())); + + graphcell.appendChild(shape); } - // Create an text element (for input) and append it to the element - QDomElement textelement = domdoc_.createElement( XML_INPUTPART ); - QDomText textnode = domdoc_.createTextNode( node->text() ); - textelement.appendChild( textnode ); - graphcell.appendChild( textelement ); + // Create an text element (for input) and append it to the element + QDomElement textelement = domdoc_.createElement( XML_INPUTPART ); + QDomText textnode = domdoc_.createTextNode( node->text() ); + textelement.appendChild( textnode ); + graphcell.appendChild( textelement ); - // Create an text element (for output) and append it to the element - QDomElement outputelement = domdoc_.createElement( XML_OUTPUTPART ); + // Create an text element (for output) and append it to the element + QDomElement outputelement = domdoc_.createElement( XML_OUTPUTPART ); - QDomText outputnode; - if( node->isJavaPlot() ) - outputnode = domdoc_.createTextNode( node->textOutputHtml() ); - else - outputnode = domdoc_.createTextNode( node->textOutput() ); + QDomText outputnode; + if( node->isJavaPlot() ) + outputnode = domdoc_.createTextNode( node->textOutputHtml() ); + else + outputnode = domdoc_.createTextNode( node->textOutput() ); - outputelement.appendChild( outputnode ); - graphcell.appendChild( outputelement ); + outputelement.appendChild( outputnode ); + graphcell.appendChild( outputelement ); /* - // Create an text element (for output) and append it to the element - QDomElement outputelement = domdoc_.createElement( XML_OUTPUTPART ); + // Create an text element (for output) and append it to the element + QDomElement outputelement = domdoc_.createElement( XML_OUTPUTPART ); - QDomText outputnode; - outputnode = domdoc_.createTextNode( node->textOutput() ); + QDomText outputnode; + outputnode = domdoc_.createTextNode( node->textOutput() ); - outputelement.appendChild( outputnode ); - graphcell.appendChild( outputelement ); + outputelement.appendChild( outputnode ); + graphcell.appendChild( outputelement ); */ - // Creates ruleelemetns - Cell::rules_t r = node->rules(); - Cell::rules_t::const_iterator r_iter = r.begin(); - for( ; r_iter != r.end(); ++r_iter ) - { - QDomElement ruleelement = domdoc_.createElement( XML_RULE ); - ruleelement.setAttribute( XML_NAME, (*r_iter)->attribute() ); - - QDomText rulenode = domdoc_.createTextNode( (*r_iter)->value() ); - ruleelement.appendChild( rulenode ); - - graphcell.appendChild( ruleelement ); - } - - // Check if any image have been include in the text and add them - // to the the the inputcell element - QString xoyz = node->textOutputHtml(); - saveImages( graphcell, xoyz ); - - // Add inputcell element to current element - currentElement_.appendChild( graphcell ); - } - - void SerializingVisitor::visitGraphCellNodeAfter(GraphCell *) - {} - - //CELLCURSOR - // ****************************************************************** - void SerializingVisitor::visitCellCursorNodeBefore(CellCursor *) - {} - - void SerializingVisitor::visitCellCursorNodeAfter(CellCursor *) - {} - - - /*! - * \author Anders Fernström - * \date 2005-11-30 - * \date 2005-12-12 (update) - * - * \brief Look through a html text and find all the images included. - * When a image is found the images is saved to the xml file and - * included in the current element - * - * 2005-12-12 AF, Added support for pasting images from clipboard - */ - void SerializingVisitor::saveImages( QDomElement ¤t, QString &text ) - { - int pos(0); - while( true ) - { - int start = text.indexOf( "(doc_); - QImage *image = doc->getImage( imagename ); - - // 2005-12-12 AF, Added support of pasting images from clipboard - if( image->isNull() ) - { - // found image that isn't part of the document, - // probably images that have been pasted into the text or - // from copied cell - QString tmpImagename = imagename; - tmpImagename.remove( "file:///" ); - image = new QImage( tmpImagename ); - } - - if( !image->isNull() ) - { - // create element and save the image to file - QDomElement imageelement = domdoc_.createElement( XML_IMAGE ); - imageelement.setAttribute( XML_NAME, imagename ); - - QBuffer buffer; - buffer.open( QBuffer::WriteOnly ); - QDataStream out( &buffer ); - out << *image; - buffer.close(); - - QDomText imagedata = domdoc_.createTextNode( buffer.buffer().toBase64() ); - imageelement.appendChild( imagedata ); - - current.appendChild( imageelement ); - } - - pos = end + 1; - } - else - break; - } - } + // Creates ruleelemetns + Cell::rules_t r = node->rules(); + Cell::rules_t::const_iterator r_iter = r.begin(); + for( ; r_iter != r.end(); ++r_iter ) + { + QDomElement ruleelement = domdoc_.createElement( XML_RULE ); + ruleelement.setAttribute( XML_NAME, (*r_iter)->attribute() ); + + QDomText rulenode = domdoc_.createTextNode( (*r_iter)->value() ); + ruleelement.appendChild( rulenode ); + + graphcell.appendChild( ruleelement ); + } + + // Check if any image have been include in the text and add them + // to the the the inputcell element + QString xoyz = node->textOutputHtml(); + saveImages( graphcell, xoyz ); + + // Add inputcell element to current element + currentElement_.appendChild( graphcell ); + } + + void SerializingVisitor::visitGraphCellNodeAfter(GraphCell *) + {} + + //CELLCURSOR + // ****************************************************************** + void SerializingVisitor::visitCellCursorNodeBefore(CellCursor *) + {} + + void SerializingVisitor::visitCellCursorNodeAfter(CellCursor *) + {} + + + /*! + * \author Anders Fernström + * \date 2005-11-30 + * \date 2005-12-12 (update) + * + * \brief Look through a html text and find all the images included. + * When a image is found the images is saved to the xml file and + * included in the current element + * + * 2005-12-12 AF, Added support for pasting images from clipboard + */ + void SerializingVisitor::saveImages( QDomElement ¤t, QString &text ) + { + int pos(0); + while( true ) + { + int start = text.indexOf( "(doc_); + QImage *image = doc->getImage( imagename ); + + // 2005-12-12 AF, Added support of pasting images from clipboard + if( image->isNull() ) + { + // found image that isn't part of the document, + // probably images that have been pasted into the text or + // from copied cell + QString tmpImagename = imagename; + tmpImagename.remove( "file:///" ); + image = new QImage( tmpImagename ); + } + + if( !image->isNull() ) + { + // create element and save the image to file + QDomElement imageelement = domdoc_.createElement( XML_IMAGE ); + imageelement.setAttribute( XML_NAME, imagename ); + + QBuffer buffer; + buffer.open( QBuffer::WriteOnly ); + QDataStream out( &buffer ); + out << *image; + buffer.close(); + + QDomText imagedata = domdoc_.createTextNode( buffer.buffer().toBase64() ); + imageelement.appendChild( imagedata ); + + current.appendChild( imageelement ); + } + + pos = end + 1; + } + else + break; + } + } } diff --git a/OMNotebook/OMNotebookQT4/serializingvisitor.h b/OMNotebook/OMNotebookQT4/serializingvisitor.h index 32f78d2f34b..831739f8f8c 100644 --- a/OMNotebook/OMNotebookQT4/serializingvisitor.h +++ b/OMNotebook/OMNotebookQT4/serializingvisitor.h @@ -61,38 +61,38 @@ using namespace std; namespace IAEX { - class SerializingVisitor : public Visitor - { + class SerializingVisitor : public Visitor + { - public: - SerializingVisitor(QDomDocument &domdoc, Document* doc); - virtual ~SerializingVisitor(); + public: + SerializingVisitor(QDomDocument &domdoc, Document* doc); + virtual ~SerializingVisitor(); - virtual void visitCellNodeBefore(Cell *node); - virtual void visitCellNodeAfter(Cell *node); + virtual void visitCellNodeBefore(Cell *node); + virtual void visitCellNodeAfter(Cell *node); - virtual void visitCellGroupNodeBefore(CellGroup *node); - virtual void visitCellGroupNodeAfter(CellGroup *node); + virtual void visitCellGroupNodeBefore(CellGroup *node); + virtual void visitCellGroupNodeAfter(CellGroup *node); - virtual void visitTextCellNodeBefore(TextCell *node); - virtual void visitTextCellNodeAfter(TextCell *node); + virtual void visitTextCellNodeBefore(TextCell *node); + virtual void visitTextCellNodeAfter(TextCell *node); - virtual void visitInputCellNodeBefore(InputCell *node); - virtual void visitInputCellNodeAfter(InputCell *node); + virtual void visitInputCellNodeBefore(InputCell *node); + virtual void visitInputCellNodeAfter(InputCell *node); - virtual void visitGraphCellNodeBefore(GraphCell *node); - virtual void visitGraphCellNodeAfter(GraphCell *node); + virtual void visitGraphCellNodeBefore(GraphCell *node); + virtual void visitGraphCellNodeAfter(GraphCell *node); - virtual void visitCellCursorNodeBefore(CellCursor *cursor); - virtual void visitCellCursorNodeAfter(CellCursor *cursor); + virtual void visitCellCursorNodeBefore(CellCursor *cursor); + virtual void visitCellCursorNodeAfter(CellCursor *cursor); - private: - void saveImages( QDomElement ¤t, QString &text ); + private: + void saveImages( QDomElement ¤t, QString &text ); - stack parents_; - QDomElement currentElement_; - QDomDocument domdoc_; - Document* doc_; - }; + stack parents_; + QDomElement currentElement_; + QDomDocument domdoc_; + Document* doc_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/stripstring.h b/OMNotebook/OMNotebookQT4/stripstring.h index d971a052002..42614c14f96 100644 --- a/OMNotebook/OMNotebookQT4/stripstring.h +++ b/OMNotebook/OMNotebookQT4/stripstring.h @@ -55,282 +55,282 @@ using namespace std; /*! - * \class CellStyle - * \author Anders Fernström - * \date 2005-11-09 - * - * \brief A class that remove/add some stuff in the content strings taken - * from mathematica notebooks. - */ + * \class CellStyle + * \author Anders Fernström + * \date 2005-11-09 + * + * \brief A class that remove/add some stuff in the content strings taken + * from mathematica notebooks. + */ class StripString { public: - StripString(){} - ~StripString(){} + StripString(){} + ~StripString(){} - static string stripNBString( string str ) - { + static string stripNBString( string str ) + { string::size_type pos = 0; while((pos = str.find("\\", pos)) != string::npos) { switch(str[pos+1]) { case 'n': - // replace '\n' with html newline (
) + // replace '\n' with html newline (
) str.replace(pos, 2, "
"); break; case 't': - // replace '\t' with 4 html blankspace - str.replace( pos, 2, "    " ); - break; - case 'r': - // remove '\r' from the text - str.erase( pos, 2 ); - break; + // replace '\t' with 4 html blankspace + str.replace( pos, 2, "    " ); + break; + case 'r': + // remove '\r' from the text + str.erase( pos, 2 ); + break; case '"': case '[': - // remove '\"' and '\[' from the text. - // also repace mathematica notebook symbols for the letter å,ä,ö - if( str.find( "[ODoubleDot]", pos ) == pos+1 ) - str.replace( pos, 13, "ö" ); - else if( str.find( "[CapitalODoubleDot]", pos ) == pos+1 ) - str.replace( pos, 20, "Ö" ); - else if( str.find( "[ADoubleDot]", pos ) == pos+1 ) - str.replace( pos, 13, "ä" ); - else if( str.find( "[CapitalADoubleDot]", pos ) == pos+1 ) - str.replace( pos, 20, "Ä" ); - else if( str.find( "[ARing]", pos ) == pos+1 ) - str.replace( pos, 8, "å" ); - else if( str.find( "[CapitalARing]", pos ) == pos+1 ) - str.replace( pos, 15, "Å" ); - else if( str.find( "[LeftRightArrow]", pos ) == pos+1 ) // NOT CORRECT SYMBOL - str.replace( pos, 17, "<->" ); - else if( str.find( "[Bullet]", pos ) == pos+1 ) - str.replace( pos, 9, "*" ); - else if( str.find( "[Dash]", pos ) == pos+1 ) - str.replace( pos, 7, "-" ); - else if( str.find( "[CloseCurlyQuote]", pos ) == pos+1 ) - str.replace( pos, 18, "'" ); - else if( str.find( "[UnderBracket]", pos ) == pos+1 ) // NOT CORRECT SYMBOL - str.replace( pos, 15, "_" ); - else if( str.find( "[LeftDoubleBracket]", pos ) == pos+1 ) // NOT CORRECT SYMBOL - str.replace( pos, 20, "[[" ); - else if( str.find( "[RightDoubleBracket]", pos ) == pos+1 ) // NOT CORRECT SYMBOL - str.replace( pos, 21, "]]" ); - else if( str.find( "[Equal]", pos ) == pos+1 ) - str.replace( pos, 8, "=" ); - else if( str.find( "[SkeletonIndicator]", pos) == pos+1 ) - str.replace( pos, 20, "-" ); - else - str.erase( pos, 1 ); - break; + // remove '\"' and '\[' from the text. + // also repace mathematica notebook symbols for the letter å,ä,ö + if( str.find( "[ODoubleDot]", pos ) == pos+1 ) + str.replace( pos, 13, "ö" ); + else if( str.find( "[CapitalODoubleDot]", pos ) == pos+1 ) + str.replace( pos, 20, "Ö" ); + else if( str.find( "[ADoubleDot]", pos ) == pos+1 ) + str.replace( pos, 13, "ä" ); + else if( str.find( "[CapitalADoubleDot]", pos ) == pos+1 ) + str.replace( pos, 20, "Ä" ); + else if( str.find( "[ARing]", pos ) == pos+1 ) + str.replace( pos, 8, "å" ); + else if( str.find( "[CapitalARing]", pos ) == pos+1 ) + str.replace( pos, 15, "Å" ); + else if( str.find( "[LeftRightArrow]", pos ) == pos+1 ) // NOT CORRECT SYMBOL + str.replace( pos, 17, "<->" ); + else if( str.find( "[Bullet]", pos ) == pos+1 ) + str.replace( pos, 9, "*" ); + else if( str.find( "[Dash]", pos ) == pos+1 ) + str.replace( pos, 7, "-" ); + else if( str.find( "[CloseCurlyQuote]", pos ) == pos+1 ) + str.replace( pos, 18, "'" ); + else if( str.find( "[UnderBracket]", pos ) == pos+1 ) // NOT CORRECT SYMBOL + str.replace( pos, 15, "_" ); + else if( str.find( "[LeftDoubleBracket]", pos ) == pos+1 ) // NOT CORRECT SYMBOL + str.replace( pos, 20, "[[" ); + else if( str.find( "[RightDoubleBracket]", pos ) == pos+1 ) // NOT CORRECT SYMBOL + str.replace( pos, 21, "]]" ); + else if( str.find( "[Equal]", pos ) == pos+1 ) + str.replace( pos, 8, "=" ); + else if( str.find( "[SkeletonIndicator]", pos) == pos+1 ) + str.replace( pos, 20, "-" ); + else + str.erase( pos, 1 ); + break; default: pos += 1; break; } - } - - return str; - } - - static string stripSimulationData( string str ) - { - string::size_type pos = 0; - if( string::npos != str.find( "\" tag to the text, and - * return the index of the correct position inside the style - */ - static string::size_type getSpanIndex( string &str ) - { - if( str.find( "" + str + ""; - str = tmp; - } - - // go to the end of the style="" part - return str.find( "\">", 0 ); - } - - /*! - * \author Anders Fernström - * \date 2006-02-10 - * - * \brief Add # symbol to filenames for links. - * - * HTML link look like: Dir/filename.html#ChaperSeven + } + + return str; + } + + static string stripSimulationData( string str ) + { + string::size_type pos = 0; + if( string::npos != str.find( "\" tag to the text, and + * return the index of the correct position inside the style + */ + static string::size_type getSpanIndex( string &str ) + { + if( str.find( "" + str + ""; + str = tmp; + } + + // go to the end of the style="" part + return str.find( "\">", 0 ); + } + + /*! + * \author Anders Fernström + * \date 2006-02-10 + * + * \brief Add # symbol to filenames for links. + * + * HTML link look like: Dir/filename.html#ChaperSeven * The notebook parser returns: Dir/filename.htmlChapterSeven * have to insert # symbol - */ - static string fixFilename( string filename ) - { - string::size_type index = filename.find( ".nb" ); - - // didn't found '.nb', assume that it is an internal doc link - // and add '#' first in the filename - if( index == string::npos ) - { - filename = string("#") + filename; - return filename; - } - - // found .nb - if( index + 4 < filename.length() ) - { - // have some text behide the fileending. Add # symbol - filename.insert( index + 3, "#" ); - return filename; - } - else - return filename; - } + */ + static string fixFilename( string filename ) + { + string::size_type index = filename.find( ".nb" ); + + // didn't found '.nb', assume that it is an internal doc link + // and add '#' first in the filename + if( index == string::npos ) + { + filename = string("#") + filename; + return filename; + } + + // found .nb + if( index + 4 < filename.length() ) + { + // have some text behide the fileending. Add # symbol + filename.insert( index + 3, "#" ); + return filename; + } + else + return filename; + } }; diff --git a/OMNotebook/OMNotebookQT4/stylesheet.cpp b/OMNotebook/OMNotebookQT4/stylesheet.cpp index 6515de34251..752fd1963df 100644 --- a/OMNotebook/OMNotebookQT4/stylesheet.cpp +++ b/OMNotebook/OMNotebookQT4/stylesheet.cpp @@ -62,445 +62,445 @@ using namespace std; namespace IAEX { - /*! - * \class Stylesheet - * \author Anders Fernström (and Ingemar Axelsson) - * \date 2005-10-26 - * - * \brief Reads a stylesheet file and creates CellStyle object - * for all styles in the stylesheet file. - */ - - /*! - * \brief Reads a given file and tries to construct a DOM tree - * from that file. If the file is corrupt a exception will be throwed. - * \author Ingemar Axelsson (large part of this function is untouched) - * - * \param filename The file that will be read. - */ - Stylesheet::Stylesheet(const QString filename) - { - //read a stylesheet file. - doc_ = new QDomDocument("StyleDoc"); - - QFile file(filename); - if(!file.open(QIODevice::ReadOnly)) - { - // 2005-10-03 AF, thorw exception insted of exit - string tmp = "Could not open file: " + filename.toStdString(); - throw runtime_error( tmp.c_str() ); - } - - //Här kan det bli feeeeel! - if(!doc_->setContent(&file)) - { - file.close(); - - // 2005-10-26 AF, thorw exception insted of exit - string tmp = "Could not read content from file: " + - filename.toStdString() + - " Probably some syntax error in the xml file"; - throw runtime_error( tmp.c_str() ); - } - file.close(); - - - // initialize all the styles in the stylesheet file - initializeStyle(); - } - - Stylesheet *Stylesheet::instance_ = 0; - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief Instance the Stylesheet object. - * \author Ingemar Axelsson (this function is untouched) - * - * \param filename The file that will be read. - * \return The Stylesheet object - */ - Stylesheet *Stylesheet::instance(const QString &filename) - { - if(!instance_) - instance_ = new Stylesheet(filename); - - return instance_; - } - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief Returns the CellStyle that correspondence with the - * style name. The function retuns a CellStyle with the name - * null if no CellStyle is found with the style name. - * - * \param style The name of the style you looking for - * \return A CellStyle - */ - CellStyle Stylesheet::getStyle( const QString &style ) - { - if( styles_.contains( style )) - return styles_.value( style ); - else - { - CellStyle tmp; - tmp.setName( "null" ); - return tmp; - } - } - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief Returns all the CellStyles. - * \return A QHash with all CellStyles mapped to there name - */ - QHash Stylesheet::getAvailableStyles() const - { - return styles_; - } - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief Returns all the CellStyle names of the visible styles - * \return A vector with all CellStyle names - */ - vector Stylesheet::getAvailableStyleNames() const - { - return styleNames_; - } - - /*! - * \example stylesheet.xml - * - * There are a lot of different attribute values that can be used. - * Here is a list of all values that can be used for different - * attributes: - * - style - * > name [attribute, {string}] - * > visible [attribute, {"true", "false"}] - * - border - * > value [attribute, {integer}] //border thickness - * > margin [attribute, {integer}] - * > padding [attribute, {integer}] - * - alignment - * > value [attribute, {"left", "right", "center", "justify"}] - * > vertical [attribute, {"baseline", "sub", "super"}] - * - font - * - family [{string}] - * - size [{integer}] - * - weight [{integer <0-99>, "light", "normal", "demibold", "bold", "black"}] - * - stretch [{"ultracondensed", "extracondensed", "condensed", "semicondensed", "unstretched", "semiexpanded", "expanded", "extraexpanded", "ultraexpanded"}] - * - italic - * - strikeout - * - underline - * - overline - * - color - * > red [attribute, {integer <0-255>}] - * > green [attribute, {integer <0-255>}] - * > blue [attribute, {integer <0-255>}] - * - chapter [{string}] - * - * Read the stylesheet file if something is unclear. - */ - - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief loop through the DOM tree and creates CellStyle after - * specified styles. - */ - void Stylesheet::initializeStyle() - { - QDomElement root = doc_->documentElement(); - QDomNode n = root.firstChild(); - - // loop through the DOM tree - while( !n.isNull() ) - { - QDomElement e = n.toElement(); - if( !e.isNull() ) - { - if( e.tagName() == "style" ) - { - CellStyle style; - style.setName( e.attribute( "name" )); - - // get visibility - if( e.attribute( "visible", "true" ).indexOf( "false", 0, Qt::CaseInsensitive ) < 0 ) + /*! + * \class Stylesheet + * \author Anders Fernström (and Ingemar Axelsson) + * \date 2005-10-26 + * + * \brief Reads a stylesheet file and creates CellStyle object + * for all styles in the stylesheet file. + */ + + /*! + * \brief Reads a given file and tries to construct a DOM tree + * from that file. If the file is corrupt a exception will be throwed. + * \author Ingemar Axelsson (large part of this function is untouched) + * + * \param filename The file that will be read. + */ + Stylesheet::Stylesheet(const QString filename) + { + //read a stylesheet file. + doc_ = new QDomDocument("StyleDoc"); + + QFile file(filename); + if(!file.open(QIODevice::ReadOnly)) + { + // 2005-10-03 AF, thorw exception insted of exit + string tmp = "Could not open file: " + filename.toStdString(); + throw runtime_error( tmp.c_str() ); + } + + //Här kan det bli feeeeel! + if(!doc_->setContent(&file)) + { + file.close(); + + // 2005-10-26 AF, thorw exception insted of exit + string tmp = "Could not read content from file: " + + filename.toStdString() + + " Probably some syntax error in the xml file"; + throw runtime_error( tmp.c_str() ); + } + file.close(); + + + // initialize all the styles in the stylesheet file + initializeStyle(); + } + + Stylesheet *Stylesheet::instance_ = 0; + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief Instance the Stylesheet object. + * \author Ingemar Axelsson (this function is untouched) + * + * \param filename The file that will be read. + * \return The Stylesheet object + */ + Stylesheet *Stylesheet::instance(const QString &filename) + { + if(!instance_) + instance_ = new Stylesheet(filename); + + return instance_; + } + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief Returns the CellStyle that correspondence with the + * style name. The function retuns a CellStyle with the name + * null if no CellStyle is found with the style name. + * + * \param style The name of the style you looking for + * \return A CellStyle + */ + CellStyle Stylesheet::getStyle( const QString &style ) + { + if( styles_.contains( style )) + return styles_.value( style ); + else + { + CellStyle tmp; + tmp.setName( "null" ); + return tmp; + } + } + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief Returns all the CellStyles. + * \return A QHash with all CellStyles mapped to there name + */ + QHash Stylesheet::getAvailableStyles() const + { + return styles_; + } + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief Returns all the CellStyle names of the visible styles + * \return A vector with all CellStyle names + */ + vector Stylesheet::getAvailableStyleNames() const + { + return styleNames_; + } + + /*! + * \example stylesheet.xml + * + * There are a lot of different attribute values that can be used. + * Here is a list of all values that can be used for different + * attributes: + * - style + * > name [attribute, {string}] + * > visible [attribute, {"true", "false"}] + * - border + * > value [attribute, {integer}] //border thickness + * > margin [attribute, {integer}] + * > padding [attribute, {integer}] + * - alignment + * > value [attribute, {"left", "right", "center", "justify"}] + * > vertical [attribute, {"baseline", "sub", "super"}] + * - font + * - family [{string}] + * - size [{integer}] + * - weight [{integer <0-99>, "light", "normal", "demibold", "bold", "black"}] + * - stretch [{"ultracondensed", "extracondensed", "condensed", "semicondensed", "unstretched", "semiexpanded", "expanded", "extraexpanded", "ultraexpanded"}] + * - italic + * - strikeout + * - underline + * - overline + * - color + * > red [attribute, {integer <0-255>}] + * > green [attribute, {integer <0-255>}] + * > blue [attribute, {integer <0-255>}] + * - chapter [{string}] + * + * Read the stylesheet file if something is unclear. + */ + + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief loop through the DOM tree and creates CellStyle after + * specified styles. + */ + void Stylesheet::initializeStyle() + { + QDomElement root = doc_->documentElement(); + QDomNode n = root.firstChild(); + + // loop through the DOM tree + while( !n.isNull() ) + { + QDomElement e = n.toElement(); + if( !e.isNull() ) + { + if( e.tagName() == "style" ) + { + CellStyle style; + style.setName( e.attribute( "name" )); + + // get visibility + if( e.attribute( "visible", "true" ).indexOf( "false", 0, Qt::CaseInsensitive ) < 0 ) style.setVisible( true ); - else - style.setVisible( false ); - - QDomNode node = e.firstChild(); - traverseStyleSettings(node, &style); - - styles_.insert( style.name(), style ); - - // 2006-03-02 AF, only add styles that are visible - if( style.visible() ) - styleNames_.push_back( style.name() ); - } - } - n = n.nextSibling(); - } - } - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief traverse through a style tag in the DOM tree - */ - void Stylesheet::traverseStyleSettings( QDomNode node, CellStyle *item ) const - { - if( !item ) - throw runtime_error( "STYLESHEET TRAVERSE... No ITEM SET!!" ); - - while( !node.isNull() ) - { - QDomElement element = node.toElement(); - - if( element.tagName() == "border" ) - parseBorderTag( element, item ); - else if( element.tagName() == "alignment" ) - parseAlignmentTag( element, item ); - else if( element.tagName() == "font" ) - parseFontTag( element, item ); - else if( element.tagName() == "chapterlevel" ) - parseChapterLevelTag( element, item ); - else - cout << "Tag not known" << element.tagName().toStdString(); - - node = node.nextSibling(); - } - } - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief Parse the BORDER tag - */ - void Stylesheet::parseBorderTag( QDomElement element, - CellStyle *item ) const - { - bool ok; - - // VALUE - int value = element.attribute( "value", "" ).toInt(&ok); - if(ok) - item->textFrameFormat()->setBorder( value ); - - // MARGIN - value = element.attribute( "margin", "" ).toInt(&ok); - if(ok) - item->textFrameFormat()->setMargin( value ); - - // PADDING - value = element.attribute( "padding", "" ).toInt(&ok); - if(ok) - item->textFrameFormat()->setPadding( value ); - } - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief Parse the ALIGNMENT tag - */ - void Stylesheet::parseAlignmentTag( QDomElement element, - CellStyle *item ) const - { - // ALIGNMENT - QString alignment = element.attribute( "value", "left" ); - if( alignment == "left" ) - item->setAlignment( Qt::AlignLeft ); - else if( alignment == "right" ) - item->setAlignment( Qt::AlignRight ); - else if( alignment == "center" ) - item->setAlignment( Qt::AlignCenter ); - else if( alignment == "justify" ) - item->setAlignment( Qt::AlignJustify ); - else - cout << "Alignment value not correct: " << alignment.toStdString(); - - - // VERTICAL ALIGNMENT - QString vertical = element.attribute( "vertical", "baseline" ); - if( vertical == "baseline" ) - item->textCharFormat()->setVerticalAlignment( QTextCharFormat::AlignNormal ); - else if( vertical == "sub" ) - item->textCharFormat()->setVerticalAlignment( QTextCharFormat::AlignSubScript ); - else if( vertical == "super" ) - item->textCharFormat()->setVerticalAlignment( QTextCharFormat::AlignSuperScript ); - else - cout << "Vertical Alignment value not correct: " << vertical.toStdString(); - } - - /* - * \author Anders Fernström - * \date 2005-10-26 - * - * \brief Parse the FONT tag - */ - void Stylesheet::parseFontTag( QDomElement element, - CellStyle *item ) const - { - QDomNode fontNode = element.firstChild(); - while( !fontNode.isNull() ) - { - QDomElement fontElement = fontNode.toElement(); - if( !fontElement.isNull() ) - { - // FAMILY - if( fontElement.tagName() == "family" ) - { - item->textCharFormat()->setFontFamily( fontElement.text() ); - } - // SIZE - else if( fontElement.tagName() == "size" ) - { - bool ok; - int size = fontElement.text().toInt(&ok); - - if(ok) - item->textCharFormat()->setFontPointSize( size ); - else - item->textCharFormat()->setFontPointSize( 12 ); - } - // WEIGHT - else if( fontElement.tagName() == "weight" ) - { - QString weight = fontElement.text(); - - if( weight == "light" ) - item->textCharFormat()->setFontWeight( QFont::Light ); - else if( weight == "normal" ) - item->textCharFormat()->setFontWeight( QFont::Normal ); - else if( weight == "demibold" ) - item->textCharFormat()->setFontWeight( QFont::DemiBold ); - else if( weight == "bold" ) - item->textCharFormat()->setFontWeight( QFont::Bold ); - else if( weight == "black" ) - item->textCharFormat()->setFontWeight( QFont::Black ); - else - { - bool ok; - int size = weight.toInt(&ok); - - if(ok) - item->textCharFormat()->setFontWeight( size ); - else - item->textCharFormat()->setFontWeight( QFont::Normal ); - } - } - // STRETCH - else if( fontElement.tagName() == "stretch" ) - { - QString stretch = fontElement.text(); - - if( stretch == "ultracondensed" ) - item->textCharFormat()->font().setStretch( QFont::UltraCondensed ); - else if( stretch == "extracondensed" ) - item->textCharFormat()->font().setStretch( QFont::ExtraCondensed ); - else if( stretch == "condensed" ) - item->textCharFormat()->font().setStretch( QFont::Condensed ); - else if( stretch == "semicondensed" ) - item->textCharFormat()->font().setStretch( QFont::SemiCondensed ); - else if( stretch == "unstretched" ) - item->textCharFormat()->font().setStretch( QFont::Unstretched ); - else if( stretch == "semiexpanded" ) - item->textCharFormat()->font().setStretch( QFont::SemiExpanded ); - else if( stretch == "expanded" ) - item->textCharFormat()->font().setStretch( QFont::Expanded ); - else if( stretch == "extraexpanded" ) - item->textCharFormat()->font().setStretch( QFont::ExtraExpanded ); - else if( stretch == "ultraexpanded" ) - item->textCharFormat()->font().setStretch( QFont::UltraExpanded ); - else - { - cout << "Stretch value not correct: " << stretch.toStdString(); - item->textCharFormat()->font().setStretch( QFont::Unstretched ); - } - } - // ITALIC - else if( fontElement.tagName() == "italic" ) - { - //This only occur when italic tag is present. - //delete italic tag to disable. - item->textCharFormat()->setFontItalic( true ); - } - // STRIKEOUT - else if( fontElement.tagName() == "strikeout" ) - { - //This only occur when strikeout tag is present. - //delete strikeout tag to disable. - item->textCharFormat()->setFontStrikeOut( true ); - } - // UNDERLINE - else if( fontElement.tagName() == "underline" ) - { - //This only occur when underline tag is present. - //delete underline tag to disable. - item->textCharFormat()->setFontUnderline( true ); - } - // OVERLINE - else if( fontElement.tagName() == "overline" ) - { - //This only occur when overline tag is present. - //delete overline tag to disable. - item->textCharFormat()->setFontOverline( true ); - } - // COLOR - else if( fontElement.tagName() == "color" ) - { - bool okRed; - bool okGreen; - bool okBlue; - - int red = fontElement.attribute( "red", "0" ).toInt(&okRed); - int green = fontElement.attribute( "green", "0" ).toInt(&okGreen); - int blue = fontElement.attribute( "blue", "0" ).toInt(&okBlue); - - if( okRed && okGreen && okBlue ) - item->textCharFormat()->setForeground( QBrush( QColor(red, green, blue) )); - else - item->textCharFormat()->setForeground( QBrush( QColor(0, 0, 0) )); - } - else - { - cout << "font tag not specified: " << - fontElement.tagName().toStdString(); - } - } - - fontNode = fontNode.nextSibling(); - } - } - - /* - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief Parse the CHAPTERLEVEL tag - */ - void Stylesheet::parseChapterLevelTag(QDomElement element, - CellStyle *item) const - { - bool ok; - - // Level - int level = element.text().toInt(&ok); - if(ok) - item->setChapterLevel( level ); - } + else + style.setVisible( false ); + + QDomNode node = e.firstChild(); + traverseStyleSettings(node, &style); + + styles_.insert( style.name(), style ); + + // 2006-03-02 AF, only add styles that are visible + if( style.visible() ) + styleNames_.push_back( style.name() ); + } + } + n = n.nextSibling(); + } + } + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief traverse through a style tag in the DOM tree + */ + void Stylesheet::traverseStyleSettings( QDomNode node, CellStyle *item ) const + { + if( !item ) + throw runtime_error( "STYLESHEET TRAVERSE... No ITEM SET!!" ); + + while( !node.isNull() ) + { + QDomElement element = node.toElement(); + + if( element.tagName() == "border" ) + parseBorderTag( element, item ); + else if( element.tagName() == "alignment" ) + parseAlignmentTag( element, item ); + else if( element.tagName() == "font" ) + parseFontTag( element, item ); + else if( element.tagName() == "chapterlevel" ) + parseChapterLevelTag( element, item ); + else + cout << "Tag not known" << element.tagName().toStdString(); + + node = node.nextSibling(); + } + } + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief Parse the BORDER tag + */ + void Stylesheet::parseBorderTag( QDomElement element, + CellStyle *item ) const + { + bool ok; + + // VALUE + int value = element.attribute( "value", "" ).toInt(&ok); + if(ok) + item->textFrameFormat()->setBorder( value ); + + // MARGIN + value = element.attribute( "margin", "" ).toInt(&ok); + if(ok) + item->textFrameFormat()->setMargin( value ); + + // PADDING + value = element.attribute( "padding", "" ).toInt(&ok); + if(ok) + item->textFrameFormat()->setPadding( value ); + } + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief Parse the ALIGNMENT tag + */ + void Stylesheet::parseAlignmentTag( QDomElement element, + CellStyle *item ) const + { + // ALIGNMENT + QString alignment = element.attribute( "value", "left" ); + if( alignment == "left" ) + item->setAlignment( Qt::AlignLeft ); + else if( alignment == "right" ) + item->setAlignment( Qt::AlignRight ); + else if( alignment == "center" ) + item->setAlignment( Qt::AlignCenter ); + else if( alignment == "justify" ) + item->setAlignment( Qt::AlignJustify ); + else + cout << "Alignment value not correct: " << alignment.toStdString(); + + + // VERTICAL ALIGNMENT + QString vertical = element.attribute( "vertical", "baseline" ); + if( vertical == "baseline" ) + item->textCharFormat()->setVerticalAlignment( QTextCharFormat::AlignNormal ); + else if( vertical == "sub" ) + item->textCharFormat()->setVerticalAlignment( QTextCharFormat::AlignSubScript ); + else if( vertical == "super" ) + item->textCharFormat()->setVerticalAlignment( QTextCharFormat::AlignSuperScript ); + else + cout << "Vertical Alignment value not correct: " << vertical.toStdString(); + } + + /* + * \author Anders Fernström + * \date 2005-10-26 + * + * \brief Parse the FONT tag + */ + void Stylesheet::parseFontTag( QDomElement element, + CellStyle *item ) const + { + QDomNode fontNode = element.firstChild(); + while( !fontNode.isNull() ) + { + QDomElement fontElement = fontNode.toElement(); + if( !fontElement.isNull() ) + { + // FAMILY + if( fontElement.tagName() == "family" ) + { + item->textCharFormat()->setFontFamily( fontElement.text() ); + } + // SIZE + else if( fontElement.tagName() == "size" ) + { + bool ok; + int size = fontElement.text().toInt(&ok); + + if(ok) + item->textCharFormat()->setFontPointSize( size ); + else + item->textCharFormat()->setFontPointSize( 12 ); + } + // WEIGHT + else if( fontElement.tagName() == "weight" ) + { + QString weight = fontElement.text(); + + if( weight == "light" ) + item->textCharFormat()->setFontWeight( QFont::Light ); + else if( weight == "normal" ) + item->textCharFormat()->setFontWeight( QFont::Normal ); + else if( weight == "demibold" ) + item->textCharFormat()->setFontWeight( QFont::DemiBold ); + else if( weight == "bold" ) + item->textCharFormat()->setFontWeight( QFont::Bold ); + else if( weight == "black" ) + item->textCharFormat()->setFontWeight( QFont::Black ); + else + { + bool ok; + int size = weight.toInt(&ok); + + if(ok) + item->textCharFormat()->setFontWeight( size ); + else + item->textCharFormat()->setFontWeight( QFont::Normal ); + } + } + // STRETCH + else if( fontElement.tagName() == "stretch" ) + { + QString stretch = fontElement.text(); + + if( stretch == "ultracondensed" ) + item->textCharFormat()->font().setStretch( QFont::UltraCondensed ); + else if( stretch == "extracondensed" ) + item->textCharFormat()->font().setStretch( QFont::ExtraCondensed ); + else if( stretch == "condensed" ) + item->textCharFormat()->font().setStretch( QFont::Condensed ); + else if( stretch == "semicondensed" ) + item->textCharFormat()->font().setStretch( QFont::SemiCondensed ); + else if( stretch == "unstretched" ) + item->textCharFormat()->font().setStretch( QFont::Unstretched ); + else if( stretch == "semiexpanded" ) + item->textCharFormat()->font().setStretch( QFont::SemiExpanded ); + else if( stretch == "expanded" ) + item->textCharFormat()->font().setStretch( QFont::Expanded ); + else if( stretch == "extraexpanded" ) + item->textCharFormat()->font().setStretch( QFont::ExtraExpanded ); + else if( stretch == "ultraexpanded" ) + item->textCharFormat()->font().setStretch( QFont::UltraExpanded ); + else + { + cout << "Stretch value not correct: " << stretch.toStdString(); + item->textCharFormat()->font().setStretch( QFont::Unstretched ); + } + } + // ITALIC + else if( fontElement.tagName() == "italic" ) + { + //This only occur when italic tag is present. + //delete italic tag to disable. + item->textCharFormat()->setFontItalic( true ); + } + // STRIKEOUT + else if( fontElement.tagName() == "strikeout" ) + { + //This only occur when strikeout tag is present. + //delete strikeout tag to disable. + item->textCharFormat()->setFontStrikeOut( true ); + } + // UNDERLINE + else if( fontElement.tagName() == "underline" ) + { + //This only occur when underline tag is present. + //delete underline tag to disable. + item->textCharFormat()->setFontUnderline( true ); + } + // OVERLINE + else if( fontElement.tagName() == "overline" ) + { + //This only occur when overline tag is present. + //delete overline tag to disable. + item->textCharFormat()->setFontOverline( true ); + } + // COLOR + else if( fontElement.tagName() == "color" ) + { + bool okRed; + bool okGreen; + bool okBlue; + + int red = fontElement.attribute( "red", "0" ).toInt(&okRed); + int green = fontElement.attribute( "green", "0" ).toInt(&okGreen); + int blue = fontElement.attribute( "blue", "0" ).toInt(&okBlue); + + if( okRed && okGreen && okBlue ) + item->textCharFormat()->setForeground( QBrush( QColor(red, green, blue) )); + else + item->textCharFormat()->setForeground( QBrush( QColor(0, 0, 0) )); + } + else + { + cout << "font tag not specified: " << + fontElement.tagName().toStdString(); + } + } + + fontNode = fontNode.nextSibling(); + } + } + + /* + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief Parse the CHAPTERLEVEL tag + */ + void Stylesheet::parseChapterLevelTag(QDomElement element, + CellStyle *item) const + { + bool ok; + + // Level + int level = element.text().toInt(&ok); + if(ok) + item->setChapterLevel( level ); + } } diff --git a/OMNotebook/OMNotebookQT4/stylesheet.h b/OMNotebook/OMNotebookQT4/stylesheet.h index d5d2e5ebbce..eb60273ab1e 100644 --- a/OMNotebook/OMNotebookQT4/stylesheet.h +++ b/OMNotebook/OMNotebookQT4/stylesheet.h @@ -60,33 +60,33 @@ namespace IAEX { - class Stylesheet : public QObject - { - Q_OBJECT + class Stylesheet : public QObject + { + Q_OBJECT - public: - static Stylesheet *instance(const QString &filename); + public: + static Stylesheet *instance(const QString &filename); - CellStyle getStyle(const QString &style); - QHash getAvailableStyles() const; - std::vector getAvailableStyleNames() const; + CellStyle getStyle(const QString &style); + QHash getAvailableStyles() const; + std::vector getAvailableStyleNames() const; - protected: - void initializeStyle(); - void traverseStyleSettings(QDomNode p, CellStyle *item) const; - void parseBorderTag(QDomElement element, CellStyle *item) const; - void parseAlignmentTag(QDomElement element, CellStyle *item) const; - void parseFontTag(QDomElement element, CellStyle *item) const; - void parseChapterLevelTag(QDomElement element, CellStyle *item) const; + protected: + void initializeStyle(); + void traverseStyleSettings(QDomNode p, CellStyle *item) const; + void parseBorderTag(QDomElement element, CellStyle *item) const; + void parseAlignmentTag(QDomElement element, CellStyle *item) const; + void parseFontTag(QDomElement element, CellStyle *item) const; + void parseChapterLevelTag(QDomElement element, CellStyle *item) const; - private: - Stylesheet(const QString filename); + private: + Stylesheet(const QString filename); - QDomDocument *doc_; - static Stylesheet *instance_; + QDomDocument *doc_; + static Stylesheet *instance_; - QHash styles_; - std::vector styleNames_; - }; + QHash styles_; + std::vector styleNames_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/syntaxhighlighter.h b/OMNotebook/OMNotebookQT4/syntaxhighlighter.h index 3ec2d01d099..73f4227fd23 100644 --- a/OMNotebook/OMNotebookQT4/syntaxhighlighter.h +++ b/OMNotebook/OMNotebookQT4/syntaxhighlighter.h @@ -52,18 +52,18 @@ class QTextDocument; namespace IAEX { - /*! - * \interface SyntaxHighlighter - * \brief Interface that syntaxhighlighters needs to obey to. - * - * updated file 2006-01-09 to represent the new highlighter that have - * been made to run in an new thread. - */ - class SyntaxHighlighter - { - public: - virtual void highlight(QTextDocument *) = 0; - }; + /*! + * \interface SyntaxHighlighter + * \brief Interface that syntaxhighlighters needs to obey to. + * + * updated file 2006-01-09 to represent the new highlighter that have + * been made to run in an new thread. + */ + class SyntaxHighlighter + { + public: + virtual void highlight(QTextDocument *) = 0; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/textcell.cpp b/OMNotebook/OMNotebookQT4/textcell.cpp index 9788b236eed..7763505362c 100644 --- a/OMNotebook/OMNotebookQT4/textcell.cpp +++ b/OMNotebook/OMNotebookQT4/textcell.cpp @@ -66,846 +66,846 @@ namespace IAEX { - /*! - * \class MyTextBrowser - * \author Ingemar Axelsson and Anders Fernström - * - * \brief extends QTextBrowser. Mostly so I can catch when a user - * clicks on a link without a change in textbrowsers content. - * - */ - MyTextBrowser::MyTextBrowser(QWidget *parent) - : QTextBrowser(parent) - { - - } - - MyTextBrowser::~MyTextBrowser() - { - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * date 2005-11-03 - * - * 2005-11-03 AF, Updated the function to reflect the changes made - * in qt (from v3 to v4). The function now takes a QUrl as parameter - * insted of a QString (in qt3). - */ - void MyTextBrowser::setSource(const QUrl &name) - { - emit openLink( &name ); - } - - /*! - * \author Anders Fernström - * \date 2005-11-01 - * - * \brief Needed a signal to be emited when the user click on - * the cell. - */ - void MyTextBrowser::mousePressEvent(QMouseEvent *event) - { - QTextBrowser::mousePressEvent(event); - - - if( event->modifiers() == Qt::ShiftModifier || textCursor().hasSelection() ) - { - return; //fjass3 - } - - emit clickOnCell(); - } - - /*! - * \author Anders Fernström - * \date 2005-11-28 - * - * \brief Handles mouse wheel events, ignore them and send the up - * in the cell hierarchy - */ - void MyTextBrowser::wheelEvent(QWheelEvent * event) - { - // ignore event and send it up in the event hierarchy - event->ignore(); - emit wheelMove( event ); - } - - /*! - * \author Anders Fernström - * \date 2006-01-23 - * - * \brief If the mimedata that should be insertet contain text, - * create a new mimedata object that only contains text, otherwise - * html is inserted - don't want that html code (inserting from - * microsoft words for example). - */ - void MyTextBrowser::insertFromMimeData(const QMimeData *source) - { - if( source->hasText() && !source->hasImage() ) - { - QMimeData *newSource = new QMimeData(); - newSource->setText( source->text() ); - QTextBrowser::insertFromMimeData( newSource ); - delete newSource; - } - else - QTextBrowser::insertFromMimeData( source ); - } + /*! + * \class MyTextBrowser + * \author Ingemar Axelsson and Anders Fernström + * + * \brief extends QTextBrowser. Mostly so I can catch when a user + * clicks on a link without a change in textbrowsers content. + * + */ + MyTextBrowser::MyTextBrowser(QWidget *parent) + : QTextBrowser(parent) + { + + } + + MyTextBrowser::~MyTextBrowser() + { + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * date 2005-11-03 + * + * 2005-11-03 AF, Updated the function to reflect the changes made + * in qt (from v3 to v4). The function now takes a QUrl as parameter + * insted of a QString (in qt3). + */ + void MyTextBrowser::setSource(const QUrl &name) + { + emit openLink( &name ); + } + + /*! + * \author Anders Fernström + * \date 2005-11-01 + * + * \brief Needed a signal to be emited when the user click on + * the cell. + */ + void MyTextBrowser::mousePressEvent(QMouseEvent *event) + { + QTextBrowser::mousePressEvent(event); + + + if( event->modifiers() == Qt::ShiftModifier || textCursor().hasSelection() ) + { + return; //fjass3 + } + + emit clickOnCell(); + } + + /*! + * \author Anders Fernström + * \date 2005-11-28 + * + * \brief Handles mouse wheel events, ignore them and send the up + * in the cell hierarchy + */ + void MyTextBrowser::wheelEvent(QWheelEvent * event) + { + // ignore event and send it up in the event hierarchy + event->ignore(); + emit wheelMove( event ); + } + + /*! + * \author Anders Fernström + * \date 2006-01-23 + * + * \brief If the mimedata that should be insertet contain text, + * create a new mimedata object that only contains text, otherwise + * html is inserted - don't want that html code (inserting from + * microsoft words for example). + */ + void MyTextBrowser::insertFromMimeData(const QMimeData *source) + { + if( source->hasText() && !source->hasImage() ) + { + QMimeData *newSource = new QMimeData(); + newSource->setText( source->text() ); + QTextBrowser::insertFromMimeData( newSource ); + delete newSource; + } + else + QTextBrowser::insertFromMimeData( source ); + } /*! - * \author Anders Fernström - * \date 2006-01-30 - * - * \brief Handles key event, added ignore to 'Alt+Enter' - */ - void MyTextBrowser::keyPressEvent(QKeyEvent *event ) - { - // ALT+ENTER (ignore) - if( event->modifiers() == Qt::AltModifier && - ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )) - { - event->ignore(); - } - // PAGE UP (ignore) - else if( event->key() == Qt::Key_PageUp ) - { - event->ignore(); - } - // PAGE DOWN (ignore) - else if( event->key() == Qt::Key_PageDown ) - { - event->ignore(); - } - // CTRL+C - else if( event->modifiers() == Qt::ControlModifier && - event->key() == Qt::Key_C ) - { - event->ignore(); - emit forwardAction( 1 ); - } - // CTRL+X - else if( event->modifiers() == Qt::ControlModifier && - event->key() == Qt::Key_X ) - { - event->ignore(); - emit forwardAction( 2 ); - } - // CTRL+V - else if( event->modifiers() == Qt::ControlModifier && - event->key() == Qt::Key_V ) - { - event->ignore(); - emit forwardAction( 3 ); - } - else - { - QTextBrowser::keyPressEvent( event ); - } - - } - - - - - /*! - * \class TextCell - * \author Ingemar Axelsson and Anders Fernström - * - * \brief A concrete cellclass using QTextEdit as mainwidget. - * - * TextCell is a class that fulfills the Cell interface. It has the - * behavior of both QTextEdit and Cell. It is used to display texts - * in a cell. It supports simple undo, redo, cut, copy, paste. The - * text can be edited if the setReadOnly flag is set to - * false. Otherwise text is just selectable. The later is the - * default. - * - * \todo Add members to fulfill the QTextEdit interface. This is - * very nice when it is needed.(Ingemar Axelsson) - * - * \bug Set so tab focuses on next cell. - */ - - /*! - * \author Ingemar Axelsson (and Anders Fernström) - * \date 2005-10-31 (update) - * - * \brief The class constructor - */ - TextCell::TextCell(QWidget *parent) - : Cell(parent), - oldHeight_( 0 ) - { - setFocusPolicy(Qt::NoFocus); - createTextWidget(); - } - - TextCell::TextCell(TextCell &t) - : Cell(t) - { - setText(t.text()); - setStyle(*t.style()); - } - - /*! - * \author Ingemar Axelsson - * - * \brief The class destructor - */ - TextCell::~TextCell() - { - setMainWidget(0); - delete text_; - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2006-03-02 (update) - * - * \brief Creates the QTextBrowser for the text inside the - * cell - * - * Large part of this function was changes due to porting - * to QT4 (changes from Q3TextBrowser to QTextBrowser). /AF - * - * 2006-03-02 AF, Added call to createChapterCounter(); - */ - void TextCell::createTextWidget() - { - text_ = new MyTextBrowser(this); - setMainWidget(text_); - - // 2006-03-02 AF, Add a chapter counter - createChapterCounter(); - - text_->setReadOnly( true ); - text_->setUndoRedoEnabled( true ); - text_->setFrameStyle( QFrame::NoFrame ); - text_->setAutoFormatting( QTextEdit::AutoNone ); - - - text_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); - text_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - text_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); -// text_->setContextMenuPolicy( Qt::NoContextMenu ); //fjass - - - - connect( text_, SIGNAL( textChanged() ), - this, SLOT( contentChanged() )); - - connect( text_, SIGNAL( openLink(const QUrl *) ), - this, SLOT( openLinkInternal(const QUrl *) )); - - connect( text_, SIGNAL( clickOnCell() ), - this, SLOT( clickEvent() )); - connect( text_, SIGNAL( wheelMove(QWheelEvent*) ), - this, SLOT( wheelEvent(QWheelEvent*) )); - // 2006-01-17 AF, new... - connect( text_, SIGNAL( currentCharFormatChanged(const QTextCharFormat &) ), - this, SLOT( charFormatChanged(const QTextCharFormat &) )); - connect( text_, SIGNAL( textChanged() ), - this, SLOT( textChangedInternal() )); - // 2006-02-10 AF, new... - connect( text_, SIGNAL( highlighted(const QUrl &) ), - this, SLOT( hoverOverLink(const QUrl &) )); - // 2006-04-27 AF, - connect( text_, SIGNAL( forwardAction(int) ), - this, SIGNAL( forwardAction(int) )); - - -// connect(text_, SIGNAL(anchorClicked(const QUrl&)), this, SLOT(openLinkIternal(const QUrl&))); - contentChanged(); - } - - /*! - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief Creates the chapter counter - */ - void TextCell::createChapterCounter() - { - chaptercounter_ = new MyTextBrowser(this); - chaptercounter_->setFrameStyle( QFrame::NoFrame ); - chaptercounter_->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding)); - chaptercounter_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - chaptercounter_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - chaptercounter_->setContextMenuPolicy( Qt::NoContextMenu ); - - chaptercounter_->setFixedWidth(50); - chaptercounter_->setReadOnly( true ); - - connect( chaptercounter_, SIGNAL( clickOnCell() ), - this, SLOT( clickEvent() )); - - addChapterCounter( chaptercounter_ ); - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Returns the text (as plain text) from the mainarea. - * - * \returns The text inside the cell., as plain text - */ - QString TextCell::text() - { - return text_->toPlainText(); - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Return the text inside the cell as Html code - * - * \return Html code - */ - QString TextCell::textHtml() - { - return text_->toHtml(); - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Return the text cursor to the QTextBrowser that make up - * mainarea of the cell - * - * \return Text cursor to the cell - */ - QTextCursor TextCell::textCursor() - { - return text_->textCursor(); - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Return the text editor that make up the cell - * - * \return The text editor inside the cell - */ - QTextEdit* TextCell::textEdit() - { - return text_; - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-11-03 (update) - * - * \brief Sets the visible text. - * - * Sets the text that should be visible. Can change the - * cellheight if the text is very long. - * - * 2005-11-02 AF, Ported the project to QT4, so I needed to add - * a check if the text is html code. If it's html code, just the - * correkt set function in QTextEdit. - * 2005-11-03 AF, Updated the html check - * - * \param text Text that should be visible inside the cell - * mainarea. - */ - void TextCell::setText( QString text ) - { - // check if the text contains html code, if so - set the - // text with correct function. - QRegExp expression( " |||||
|
||||||||||||
" ); - QRegExp expressionTag( "<.*" ); - if( 0 <= text.indexOf( expression )) - { - // 2005-12-06 AF, ugly way to get the style, when inserting - // text containg some html tags. - text_->setPlainText( "TMP_OMNOTEBOOK" ); - setStyle( *style() ); - QString html = text_->toHtml(); - int pos = html.indexOf( "TMP_OMNOTEBOOK", 0, Qt::CaseInsensitive ); - html.replace( pos, 14, text ); - text_->setHtml( html ); - text_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); - text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); - - //setTextHtml( text ); - } - else if( 0 <= text.indexOf( expressionTag )) - { - qDebug( "Possible HTML tag in text:" ); - qDebug( text.toStdString().c_str() ); - - text_->setPlainText( text ); - setStyle( style_ ); - - contentChanged(); - } - else - { - text_->setPlainText( text ); - setStyle( style_ ); - - contentChanged(); - } - - text_->setUndoRedoEnabled( true ); - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Sets the visible text, given an specific text format. - * - * Sets the text that should be visible and uses the text format - * that's sent to the function. Can change the cellheight if the - * text is very long. - * - * \param text Text that should be visible inside the cell mainarea. - * \param format Text format that should be used on the text - */ - void TextCell::setText( QString text, QTextCharFormat format ) - { - text_->setCurrentCharFormat( format ); - text_->setPlainText( text ); - contentChanged(); - text_->setUndoRedoEnabled( true ); - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Sets the visible text using html code. - * - * Sets the text that should be visible using html code. Can change - * the cellheight if the text is very long. - * - * \param html Html code that should be visible as normal text inside the cell mainarea. - */ - void TextCell::setTextHtml(QString html) - { - text_->setHtml( html ); - text_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); - text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); - - contentChanged(); - text_->setUndoRedoEnabled( true ); - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Set cell style - * - * \param stylename The style name of the style that is to be applyed to the cell - */ - void TextCell::setStyle(const QString &stylename) - { - Cell::setStyle( stylename ); - } - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * \date 2006-03-02 (update) - * - * \brief Set cell style - * - * \param style The cell style that is to be applyed to the cell - * - * 2005-11-03 AF, updated so the text is selected when the style - * is changed, after the text is unselected. - * 2005-11-15 AF, added trick to make sure that links are displayed - * correctly - * 2006-01-17 AF, removed trick to make sure the links are displaed - * correctly - * 2006-03-02 AF, set chapter style - * - * \todo right now all the text inside the cell is changed, when - * changing style. Text that have been changed from the cells - * style (for example words made bold) should be uneffected by - * the change in cellstyle. Right now this function is used when - * the user sets text to change the hole text to the cellstyle. /AF - */ - void TextCell::setStyle(CellStyle style) - { - Cell::setStyle( style ); + * \author Anders Fernström + * \date 2006-01-30 + * + * \brief Handles key event, added ignore to 'Alt+Enter' + */ + void MyTextBrowser::keyPressEvent(QKeyEvent *event ) + { + // ALT+ENTER (ignore) + if( event->modifiers() == Qt::AltModifier && + ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )) + { + event->ignore(); + } + // PAGE UP (ignore) + else if( event->key() == Qt::Key_PageUp ) + { + event->ignore(); + } + // PAGE DOWN (ignore) + else if( event->key() == Qt::Key_PageDown ) + { + event->ignore(); + } + // CTRL+C + else if( event->modifiers() == Qt::ControlModifier && + event->key() == Qt::Key_C ) + { + event->ignore(); + emit forwardAction( 1 ); + } + // CTRL+X + else if( event->modifiers() == Qt::ControlModifier && + event->key() == Qt::Key_X ) + { + event->ignore(); + emit forwardAction( 2 ); + } + // CTRL+V + else if( event->modifiers() == Qt::ControlModifier && + event->key() == Qt::Key_V ) + { + event->ignore(); + emit forwardAction( 3 ); + } + else + { + QTextBrowser::keyPressEvent( event ); + } + + } + + + + + /*! + * \class TextCell + * \author Ingemar Axelsson and Anders Fernström + * + * \brief A concrete cellclass using QTextEdit as mainwidget. + * + * TextCell is a class that fulfills the Cell interface. It has the + * behavior of both QTextEdit and Cell. It is used to display texts + * in a cell. It supports simple undo, redo, cut, copy, paste. The + * text can be edited if the setReadOnly flag is set to + * false. Otherwise text is just selectable. The later is the + * default. + * + * \todo Add members to fulfill the QTextEdit interface. This is + * very nice when it is needed.(Ingemar Axelsson) + * + * \bug Set so tab focuses on next cell. + */ + + /*! + * \author Ingemar Axelsson (and Anders Fernström) + * \date 2005-10-31 (update) + * + * \brief The class constructor + */ + TextCell::TextCell(QWidget *parent) + : Cell(parent), + oldHeight_( 0 ) + { + setFocusPolicy(Qt::NoFocus); + createTextWidget(); + } + + TextCell::TextCell(TextCell &t) + : Cell(t) + { + setText(t.text()); + setStyle(*t.style()); + } + + /*! + * \author Ingemar Axelsson + * + * \brief The class destructor + */ + TextCell::~TextCell() + { + setMainWidget(0); + delete text_; + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2006-03-02 (update) + * + * \brief Creates the QTextBrowser for the text inside the + * cell + * + * Large part of this function was changes due to porting + * to QT4 (changes from Q3TextBrowser to QTextBrowser). /AF + * + * 2006-03-02 AF, Added call to createChapterCounter(); + */ + void TextCell::createTextWidget() + { + text_ = new MyTextBrowser(this); + setMainWidget(text_); + + // 2006-03-02 AF, Add a chapter counter + createChapterCounter(); + + text_->setReadOnly( true ); + text_->setUndoRedoEnabled( true ); + text_->setFrameStyle( QFrame::NoFrame ); + text_->setAutoFormatting( QTextEdit::AutoNone ); + + + text_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); + text_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + text_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); +// text_->setContextMenuPolicy( Qt::NoContextMenu ); //fjass + + + + connect( text_, SIGNAL( textChanged() ), + this, SLOT( contentChanged() )); + + connect( text_, SIGNAL( openLink(const QUrl *) ), + this, SLOT( openLinkInternal(const QUrl *) )); + + connect( text_, SIGNAL( clickOnCell() ), + this, SLOT( clickEvent() )); + connect( text_, SIGNAL( wheelMove(QWheelEvent*) ), + this, SLOT( wheelEvent(QWheelEvent*) )); + // 2006-01-17 AF, new... + connect( text_, SIGNAL( currentCharFormatChanged(const QTextCharFormat &) ), + this, SLOT( charFormatChanged(const QTextCharFormat &) )); + connect( text_, SIGNAL( textChanged() ), + this, SLOT( textChangedInternal() )); + // 2006-02-10 AF, new... + connect( text_, SIGNAL( highlighted(const QUrl &) ), + this, SLOT( hoverOverLink(const QUrl &) )); + // 2006-04-27 AF, + connect( text_, SIGNAL( forwardAction(int) ), + this, SIGNAL( forwardAction(int) )); + + +// connect(text_, SIGNAL(anchorClicked(const QUrl&)), this, SLOT(openLinkIternal(const QUrl&))); + contentChanged(); + } + + /*! + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief Creates the chapter counter + */ + void TextCell::createChapterCounter() + { + chaptercounter_ = new MyTextBrowser(this); + chaptercounter_->setFrameStyle( QFrame::NoFrame ); + chaptercounter_->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding)); + chaptercounter_->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + chaptercounter_->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + chaptercounter_->setContextMenuPolicy( Qt::NoContextMenu ); + + chaptercounter_->setFixedWidth(50); + chaptercounter_->setReadOnly( true ); + + connect( chaptercounter_, SIGNAL( clickOnCell() ), + this, SLOT( clickEvent() )); + + addChapterCounter( chaptercounter_ ); + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Returns the text (as plain text) from the mainarea. + * + * \returns The text inside the cell., as plain text + */ + QString TextCell::text() + { + return text_->toPlainText(); + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Return the text inside the cell as Html code + * + * \return Html code + */ + QString TextCell::textHtml() + { + return text_->toHtml(); + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Return the text cursor to the QTextBrowser that make up + * mainarea of the cell + * + * \return Text cursor to the cell + */ + QTextCursor TextCell::textCursor() + { + return text_->textCursor(); + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Return the text editor that make up the cell + * + * \return The text editor inside the cell + */ + QTextEdit* TextCell::textEdit() + { + return text_; + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-11-03 (update) + * + * \brief Sets the visible text. + * + * Sets the text that should be visible. Can change the + * cellheight if the text is very long. + * + * 2005-11-02 AF, Ported the project to QT4, so I needed to add + * a check if the text is html code. If it's html code, just the + * correkt set function in QTextEdit. + * 2005-11-03 AF, Updated the html check + * + * \param text Text that should be visible inside the cell + * mainarea. + */ + void TextCell::setText( QString text ) + { + // check if the text contains html code, if so - set the + // text with correct function. + QRegExp expression( " |||||
|
||||||||||||
" ); + QRegExp expressionTag( "<.*" ); + if( 0 <= text.indexOf( expression )) + { + // 2005-12-06 AF, ugly way to get the style, when inserting + // text containg some html tags. + text_->setPlainText( "TMP_OMNOTEBOOK" ); + setStyle( *style() ); + QString html = text_->toHtml(); + int pos = html.indexOf( "TMP_OMNOTEBOOK", 0, Qt::CaseInsensitive ); + html.replace( pos, 14, text ); + text_->setHtml( html ); + text_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); + text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); + + //setTextHtml( text ); + } + else if( 0 <= text.indexOf( expressionTag )) + { + qDebug( "Possible HTML tag in text:" ); + qDebug( text.toStdString().c_str() ); + + text_->setPlainText( text ); + setStyle( style_ ); + + contentChanged(); + } + else + { + text_->setPlainText( text ); + setStyle( style_ ); + + contentChanged(); + } + + text_->setUndoRedoEnabled( true ); + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Sets the visible text, given an specific text format. + * + * Sets the text that should be visible and uses the text format + * that's sent to the function. Can change the cellheight if the + * text is very long. + * + * \param text Text that should be visible inside the cell mainarea. + * \param format Text format that should be used on the text + */ + void TextCell::setText( QString text, QTextCharFormat format ) + { + text_->setCurrentCharFormat( format ); + text_->setPlainText( text ); + contentChanged(); + text_->setUndoRedoEnabled( true ); + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Sets the visible text using html code. + * + * Sets the text that should be visible using html code. Can change + * the cellheight if the text is very long. + * + * \param html Html code that should be visible as normal text inside the cell mainarea. + */ + void TextCell::setTextHtml(QString html) + { + text_->setHtml( html ); + text_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); + text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); + + contentChanged(); + text_->setUndoRedoEnabled( true ); + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Set cell style + * + * \param stylename The style name of the style that is to be applyed to the cell + */ + void TextCell::setStyle(const QString &stylename) + { + Cell::setStyle( stylename ); + } + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * \date 2006-03-02 (update) + * + * \brief Set cell style + * + * \param style The cell style that is to be applyed to the cell + * + * 2005-11-03 AF, updated so the text is selected when the style + * is changed, after the text is unselected. + * 2005-11-15 AF, added trick to make sure that links are displayed + * correctly + * 2006-01-17 AF, removed trick to make sure the links are displaed + * correctly + * 2006-03-02 AF, set chapter style + * + * \todo right now all the text inside the cell is changed, when + * changing style. Text that have been changed from the cells + * style (for example words made bold) should be uneffected by + * the change in cellstyle. Right now this function is used when + * the user sets text to change the hole text to the cellstyle. /AF + */ + void TextCell::setStyle(CellStyle style) + { + Cell::setStyle( style ); // select all the text, - // don't do it if the text contains an image, qt krasches if a - // cell contains starts with a image and the entier cell is - // selected. - // ignore this in version 4.1. of QT - //if( text_->toHtml().indexOf( "file:///", 0) < 0 ) + // don't do it if the text contains an image, qt krasches if a + // cell contains starts with a image and the entier cell is + // selected. + // ignore this in version 4.1. of QT + //if( text_->toHtml().indexOf( "file:///", 0) < 0 ) - text_->selectAll(); + text_->selectAll(); - // set the new style settings - text_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); - text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); - text_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); + // set the new style settings + text_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); + text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); + text_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); - // unselect the text, reset cursor position - QTextCursor cursor( text_->textCursor() ); - cursor.clearSelection(); - text_->setTextCursor( cursor ); + // unselect the text, reset cursor position + QTextCursor cursor( text_->textCursor() ); + cursor.clearSelection(); + text_->setTextCursor( cursor ); - - // clear the undo/redo - text_->setUndoRedoEnabled( false ); - text_->setUndoRedoEnabled( true ); - - // ugly trick to make the sure that the links haven't change color - //if( !text_->toPlainText().isEmpty() ) - // text_->setHtml( text_->toHtml() ); - - // 2006-03-02 AF, set chapter counter style - - if(chaptercounter_->document()->isEmpty()) - chaptercounter_->document()->setPlainText(" "); //070606 This seems to eliminate the style bug.. - - - chaptercounter_->selectAll(); - chaptercounter_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); - - - - QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); - - format.setMargin( style_.textFrameFormat()->margin() + - style_.textFrameFormat()->border() + - style_.textFrameFormat()->padding() ); - chaptercounter_->document()->rootFrame()->setFrameFormat( format ); - - - chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); - - - cursor = chaptercounter_->textCursor(); - - cursor.clearSelection(); - chaptercounter_->setTextCursor( cursor ); - - - - } - - /*! - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief set the chapter counter - */ - void TextCell::setChapterCounter( QString number ) - { - chaptercounter_->selectAll(); - chaptercounter_->setPlainText( number ); - chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); - QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); - format.setMargin( style_.textFrameFormat()->margin() + - style_.textFrameFormat()->border() + - style_.textFrameFormat()->padding() ); - chaptercounter_->document()->rootFrame()->setFrameFormat( format ); - } - - /*! - * \author Anders Fernström - * \date 2006-03-02 - * - * \brief return the value of the chapter counter, as plain text. - * Returns null if the counter is empty - */ - QString TextCell::ChapterCounter() - { - if( chaptercounter_->toPlainText().isEmpty() ) - return QString::null; - - return chaptercounter_->toPlainText(); - } - - /*! - * \author Anders Fernström - * \date 2006-03-03 - * - * \brief return the value of the chapter counter, as html code. - * Returns null if the counter is empty - */ - QString TextCell::ChapterCounterHtml() - { - if( chaptercounter_->toPlainText().isEmpty() ) - return QString::null; - - return chaptercounter_->toHtml(); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2006-03-02 (update) - * - * \breif Set readonly value on the texteditor - * - * 2005-10-31 AF, removed the change in framstyle, looks better now - * 2005-11-01 AF, clear text selection when text edit is set to readonly - * 2006-03-02 AF, clear text selection in chapter counter - * - * \param readonly The boolean value of readonly property - */ - void TextCell::setReadOnly(const bool readonly) - { - if( readonly ) - { - QTextCursor cursor = text_->textCursor(); - cursor.clearSelection(); - text_->setTextCursor( cursor ); - - // 2006-03-02 AF, clear selection in chapter counter - cursor = chaptercounter_->textCursor(); - cursor.clearSelection(); - chaptercounter_->setTextCursor( cursor ); - } - - text_->setReadOnly(readonly); - text_->setTextInteractionFlags(text_->textInteractionFlags() | Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); - /* Removed /AF - if(readonly) - text_->setFrameStyle(QFrame::NoFrame); - else - text_->setFrameStyle(QFrame::Panel|QFrame::Sunken); - */ - } - - /*! - * \author Ingemar Axelsson - */ - void TextCell::setFocus(const bool focus) - { - if(focus) - text_->setFocus(); - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * - * \breif send a clicked signal if the user clicks on the cell - */ - void TextCell::clickEvent() - { - //if( text_->isReadOnly() ) -// QTextCursor c = textCursor(); - -// if(textCursor().charFormat().isAnchor()) -// openLinkInternal(QUrl(textCursor().charFormat().anchorHref())); //fjass -// else - - emit clicked(this); -// { -// QUrl u(c.charFormat().anchorHref()); - -// setReadOnly(true); - -// if -// } - - } - - /*! - * \author Anders Fernström and Ingemar Axelsson - * \date 2006-04-10 (update) - * - * \breif Recalculates height. - * - * 2005-10-31 AF, Large part of this function was changes due to - * porting to QT4 (changes from Q3TextBrowser to QTextBrowser). - * 2006-04-10 AF, emits heightChanged if the height changes - */ - void TextCell::contentChanged() - { - int height = text_->document()->documentLayout()->documentSize().toSize().height(); - - //cout << "Height: " << height << endl; - - if( height < 0 ) - height = 30; - - text_->setMinimumHeight( height ); - - // add a little extra, just in case, emit 'heightChanged()' if height - // have chagned /AF - setHeight( height + 5 ); - emit textChanged(); - - if( oldHeight_ != (height + 5) ) - emit heightChanged(); - - oldHeight_ = height + 5; - } - - /*! - * \author Anders Fernström - * \date 2006-02-10 - */ - void TextCell::hoverOverLink(const QUrl &link) - { - if( oldHoverLink_ != (link.path() + link.fragment()) ) - { - oldHoverLink_ = link.path() + link.fragment(); - emit hoverOverUrl( link ); - } - } - - /*! - * \author Ingemar Axelsson - * - * \bug The link is removed if the sourcefile does not - * exists. This is strange. - */ - void TextCell::openLinkInternal(const QUrl *url) - { - emit openLink(url); - } - - void TextCell::openLinkInternal(const QUrl &url) - { - emit openLink(&url); - } - - - /*! - * \author Anders Fernström - */ - void TextCell::textChangedInternal() - { - emit textChanged( true ); - } - - /*! - * \author Anders Fernström - * \date 2006-01-17 - * - * \breif set the correct style if the charFormat is changed and the - * cell is empty. This is done because otherwise the style is lost if - * all text is removed inside a cell. - */ - void TextCell::charFormatChanged(const QTextCharFormat &) - { - if( text_->toPlainText().isEmpty() ) - { - text_->blockSignals( true ); - text_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); - text_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); - text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); - text_->blockSignals( false ); - contentChanged(); - } - } - - - /*! - * \author Anders Fernström - * \date 2005-10-28 - * - * \brief Function for telling if the user is allowed to change - * the text settings for the text inside the cell. User is - * allowed to change the text settings for textcell so this - * function always return true. - * - * \return True - */ - bool TextCell::isEditable() - { - return true; - } - - /*! - * \author Ingemar Axelsson and Anders Fernström - * \date 2005-11-01 (update) - * - * \breif toggle between showing the html code in the cell and - * normal plain text. - * - * 2005-11-01 AF, Remade the function to reflect the new - * QTextEdit - */ - void TextCell::viewExpression(const bool expr) - { - if( expr != isViewExpression() ) - { - text_->blockSignals( true ); - - if( expr ) - { - viewexpression_ = true; - text_->setCurrentCharFormat( *style_.textCharFormat() ); - text_->setPlainText( text_->toHtml() ); - - QPalette palette; - palette.setColor( text_->backgroundRole(), - QColor( 180, 180, 180 ) ); - text_->setPalette(palette); - } - else - { - viewexpression_ = false; - text_->setHtml( text_->toPlainText() ); - text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); - - QPalette palette; - palette.setColor( text_->backgroundRole(), - backgroundColor() ); - text_->setPalette(palette); - } - - text_->blockSignals( false ); - contentChanged(); - } - } - - - // *************************************************************** - - - - - - - - - void TextCell::accept(Visitor &v) - { - v.visitTextCellNodeBefore(this); - - if(hasChilds()) - { - child()->accept(v); - } - v.visitTextCellNodeAfter(this); - - //Move along. - if(hasNext()) - next()->accept(v); - } - - /*! - * Resize textcell when the mainwindow is resized. This because the - * cellcontent should always be visible. - */ - void TextCell::resizeEvent(QResizeEvent *event) - { - contentChanged(); - Cell::resizeEvent(event); - } - - void TextCell::clear() - { - text_->clear(); - } + + // clear the undo/redo + text_->setUndoRedoEnabled( false ); + text_->setUndoRedoEnabled( true ); + + // ugly trick to make the sure that the links haven't change color + //if( !text_->toPlainText().isEmpty() ) + // text_->setHtml( text_->toHtml() ); + + // 2006-03-02 AF, set chapter counter style + + if(chaptercounter_->document()->isEmpty()) + chaptercounter_->document()->setPlainText(" "); //070606 This seems to eliminate the style bug.. + + + chaptercounter_->selectAll(); + chaptercounter_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); + + + + QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); + + format.setMargin( style_.textFrameFormat()->margin() + + style_.textFrameFormat()->border() + + style_.textFrameFormat()->padding() ); + chaptercounter_->document()->rootFrame()->setFrameFormat( format ); + + + chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); + + + cursor = chaptercounter_->textCursor(); + + cursor.clearSelection(); + chaptercounter_->setTextCursor( cursor ); + + + + } + + /*! + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief set the chapter counter + */ + void TextCell::setChapterCounter( QString number ) + { + chaptercounter_->selectAll(); + chaptercounter_->setPlainText( number ); + chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight ); + QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat(); + format.setMargin( style_.textFrameFormat()->margin() + + style_.textFrameFormat()->border() + + style_.textFrameFormat()->padding() ); + chaptercounter_->document()->rootFrame()->setFrameFormat( format ); + } + + /*! + * \author Anders Fernström + * \date 2006-03-02 + * + * \brief return the value of the chapter counter, as plain text. + * Returns null if the counter is empty + */ + QString TextCell::ChapterCounter() + { + if( chaptercounter_->toPlainText().isEmpty() ) + return QString::null; + + return chaptercounter_->toPlainText(); + } + + /*! + * \author Anders Fernström + * \date 2006-03-03 + * + * \brief return the value of the chapter counter, as html code. + * Returns null if the counter is empty + */ + QString TextCell::ChapterCounterHtml() + { + if( chaptercounter_->toPlainText().isEmpty() ) + return QString::null; + + return chaptercounter_->toHtml(); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2006-03-02 (update) + * + * \breif Set readonly value on the texteditor + * + * 2005-10-31 AF, removed the change in framstyle, looks better now + * 2005-11-01 AF, clear text selection when text edit is set to readonly + * 2006-03-02 AF, clear text selection in chapter counter + * + * \param readonly The boolean value of readonly property + */ + void TextCell::setReadOnly(const bool readonly) + { + if( readonly ) + { + QTextCursor cursor = text_->textCursor(); + cursor.clearSelection(); + text_->setTextCursor( cursor ); + + // 2006-03-02 AF, clear selection in chapter counter + cursor = chaptercounter_->textCursor(); + cursor.clearSelection(); + chaptercounter_->setTextCursor( cursor ); + } + + text_->setReadOnly(readonly); + text_->setTextInteractionFlags(text_->textInteractionFlags() | Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); + /* Removed /AF + if(readonly) + text_->setFrameStyle(QFrame::NoFrame); + else + text_->setFrameStyle(QFrame::Panel|QFrame::Sunken); + */ + } + + /*! + * \author Ingemar Axelsson + */ + void TextCell::setFocus(const bool focus) + { + if(focus) + text_->setFocus(); + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * + * \breif send a clicked signal if the user clicks on the cell + */ + void TextCell::clickEvent() + { + //if( text_->isReadOnly() ) +// QTextCursor c = textCursor(); + +// if(textCursor().charFormat().isAnchor()) +// openLinkInternal(QUrl(textCursor().charFormat().anchorHref())); //fjass +// else + + emit clicked(this); +// { +// QUrl u(c.charFormat().anchorHref()); + +// setReadOnly(true); + +// if +// } + + } + + /*! + * \author Anders Fernström and Ingemar Axelsson + * \date 2006-04-10 (update) + * + * \breif Recalculates height. + * + * 2005-10-31 AF, Large part of this function was changes due to + * porting to QT4 (changes from Q3TextBrowser to QTextBrowser). + * 2006-04-10 AF, emits heightChanged if the height changes + */ + void TextCell::contentChanged() + { + int height = text_->document()->documentLayout()->documentSize().toSize().height(); + + //cout << "Height: " << height << endl; + + if( height < 0 ) + height = 30; + + text_->setMinimumHeight( height ); + + // add a little extra, just in case, emit 'heightChanged()' if height + // have chagned /AF + setHeight( height + 5 ); + emit textChanged(); + + if( oldHeight_ != (height + 5) ) + emit heightChanged(); + + oldHeight_ = height + 5; + } + + /*! + * \author Anders Fernström + * \date 2006-02-10 + */ + void TextCell::hoverOverLink(const QUrl &link) + { + if( oldHoverLink_ != (link.path() + link.fragment()) ) + { + oldHoverLink_ = link.path() + link.fragment(); + emit hoverOverUrl( link ); + } + } + + /*! + * \author Ingemar Axelsson + * + * \bug The link is removed if the sourcefile does not + * exists. This is strange. + */ + void TextCell::openLinkInternal(const QUrl *url) + { + emit openLink(url); + } + + void TextCell::openLinkInternal(const QUrl &url) + { + emit openLink(&url); + } + + + /*! + * \author Anders Fernström + */ + void TextCell::textChangedInternal() + { + emit textChanged( true ); + } + + /*! + * \author Anders Fernström + * \date 2006-01-17 + * + * \breif set the correct style if the charFormat is changed and the + * cell is empty. This is done because otherwise the style is lost if + * all text is removed inside a cell. + */ + void TextCell::charFormatChanged(const QTextCharFormat &) + { + if( text_->toPlainText().isEmpty() ) + { + text_->blockSignals( true ); + text_->setAlignment( (Qt::AlignmentFlag)style_.alignment() ); + text_->mergeCurrentCharFormat( (*style_.textCharFormat()) ); + text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); + text_->blockSignals( false ); + contentChanged(); + } + } + + + /*! + * \author Anders Fernström + * \date 2005-10-28 + * + * \brief Function for telling if the user is allowed to change + * the text settings for the text inside the cell. User is + * allowed to change the text settings for textcell so this + * function always return true. + * + * \return True + */ + bool TextCell::isEditable() + { + return true; + } + + /*! + * \author Ingemar Axelsson and Anders Fernström + * \date 2005-11-01 (update) + * + * \breif toggle between showing the html code in the cell and + * normal plain text. + * + * 2005-11-01 AF, Remade the function to reflect the new + * QTextEdit + */ + void TextCell::viewExpression(const bool expr) + { + if( expr != isViewExpression() ) + { + text_->blockSignals( true ); + + if( expr ) + { + viewexpression_ = true; + text_->setCurrentCharFormat( *style_.textCharFormat() ); + text_->setPlainText( text_->toHtml() ); + + QPalette palette; + palette.setColor( text_->backgroundRole(), + QColor( 180, 180, 180 ) ); + text_->setPalette(palette); + } + else + { + viewexpression_ = false; + text_->setHtml( text_->toPlainText() ); + text_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) ); + + QPalette palette; + palette.setColor( text_->backgroundRole(), + backgroundColor() ); + text_->setPalette(palette); + } + + text_->blockSignals( false ); + contentChanged(); + } + } + + + // *************************************************************** + + + + + + + + + void TextCell::accept(Visitor &v) + { + v.visitTextCellNodeBefore(this); + + if(hasChilds()) + { + child()->accept(v); + } + v.visitTextCellNodeAfter(this); + + //Move along. + if(hasNext()) + next()->accept(v); + } + + /*! + * Resize textcell when the mainwindow is resized. This because the + * cellcontent should always be visible. + */ + void TextCell::resizeEvent(QResizeEvent *event) + { + contentChanged(); + Cell::resizeEvent(event); + } + + void TextCell::clear() + { + text_->clear(); + } } diff --git a/OMNotebook/OMNotebookQT4/textcell.h b/OMNotebook/OMNotebookQT4/textcell.h index 2ace87609fa..39add887843 100644 --- a/OMNotebook/OMNotebookQT4/textcell.h +++ b/OMNotebook/OMNotebookQT4/textcell.h @@ -58,99 +58,99 @@ class QWidget; namespace IAEX { - class TextCell : public Cell - { - Q_OBJECT - - public: - TextCell(QWidget *parent = 0); // Changed 2005-10-28 AF - TextCell(TextCell &t); - virtual ~TextCell(); - - QString text(); - QString textHtml(); // Added 2005-10-28 AF - QTextCursor textCursor(); // Added 2005-10-28 AF - QTextEdit* textEdit(); // Added 2005-10-28 AF - - void clear(); - virtual void accept(Visitor &v); - virtual bool isEditable(); - virtual void viewExpression(const bool expr); - - signals: - void heightChanged(); - void textChanged(); - void textChanged( bool ); - void hoverOverUrl( const QUrl &link ); // Added 2006-02-10 AF - void forwardAction( int ); // Added 2006-04-27 AF - - public slots: - void clickEvent(); - void setText(QString text); - void setText(QString text, QTextCharFormat format); // Added 2005-10-28 AF - void setTextHtml(QString html); // Added 2005-10-28 AF - void setStyle(const QString &stylename); // Changed 2005-10-28 AF - void setStyle(CellStyle style); // Changed 2005-10-28 AF - void setChapterCounter(QString number); // Added 2006-03-02 AF - QString ChapterCounter(); // Added 2006-03-02 AF - QString ChapterCounterHtml(); // Added 2006-03-03 AF - void setReadOnly(const bool readonly); - virtual void setFocus(const bool focus); - - - - protected slots: - void contentChanged(); - void hoverOverLink(const QUrl &link); // Added 2006-02-10 AF - void openLinkInternal(const QUrl *url); - void openLinkInternal(const QUrl &url); - void textChangedInternal(); - void charFormatChanged(const QTextCharFormat &); // Added 2006-01-17 AF - - protected: - void resizeEvent(QResizeEvent *event); - - private: - void createTextWidget(); - void createChapterCounter(); - - public: - QTextBrowser *text_; - private: - QTextBrowser *chaptercounter_; // Added 2006-03-02 AF - - QString oldHoverLink_; // Added 2006-02-10 AF - - int oldHeight_; // Added 2006-04-10 AF - }; - - //*************************************************** - class MyTextBrowser : public QTextBrowser - { - Q_OBJECT - - public: - MyTextBrowser(QWidget *parent=0); - virtual ~MyTextBrowser(); - - void setActive( bool active ); // Added 2006-04-25 AF - - signals: - void openLink(const QUrl *); // Changed 2005-11-03 AF - void clickOnCell(); // Added 2005-11-01 AF - void wheelMove( QWheelEvent* ); // Added 2005-11-28 AF - void forwardAction( int ); // Added 2006-04-27 AF - - public slots: - void setSource(const QUrl &name); // Changed 2005-11-03 AF - - protected: - void mousePressEvent(QMouseEvent *event); // Added 2005-11-01 AF - void wheelEvent(QWheelEvent * event); // Added 2005-11-28 AF - void insertFromMimeData(const QMimeData *source); // Added 2006-01-23 AF - void keyPressEvent(QKeyEvent *event ); // Added 2006-01-30 AF - - }; + class TextCell : public Cell + { + Q_OBJECT + + public: + TextCell(QWidget *parent = 0); // Changed 2005-10-28 AF + TextCell(TextCell &t); + virtual ~TextCell(); + + QString text(); + QString textHtml(); // Added 2005-10-28 AF + QTextCursor textCursor(); // Added 2005-10-28 AF + QTextEdit* textEdit(); // Added 2005-10-28 AF + + void clear(); + virtual void accept(Visitor &v); + virtual bool isEditable(); + virtual void viewExpression(const bool expr); + + signals: + void heightChanged(); + void textChanged(); + void textChanged( bool ); + void hoverOverUrl( const QUrl &link ); // Added 2006-02-10 AF + void forwardAction( int ); // Added 2006-04-27 AF + + public slots: + void clickEvent(); + void setText(QString text); + void setText(QString text, QTextCharFormat format); // Added 2005-10-28 AF + void setTextHtml(QString html); // Added 2005-10-28 AF + void setStyle(const QString &stylename); // Changed 2005-10-28 AF + void setStyle(CellStyle style); // Changed 2005-10-28 AF + void setChapterCounter(QString number); // Added 2006-03-02 AF + QString ChapterCounter(); // Added 2006-03-02 AF + QString ChapterCounterHtml(); // Added 2006-03-03 AF + void setReadOnly(const bool readonly); + virtual void setFocus(const bool focus); + + + + protected slots: + void contentChanged(); + void hoverOverLink(const QUrl &link); // Added 2006-02-10 AF + void openLinkInternal(const QUrl *url); + void openLinkInternal(const QUrl &url); + void textChangedInternal(); + void charFormatChanged(const QTextCharFormat &); // Added 2006-01-17 AF + + protected: + void resizeEvent(QResizeEvent *event); + + private: + void createTextWidget(); + void createChapterCounter(); + + public: + QTextBrowser *text_; + private: + QTextBrowser *chaptercounter_; // Added 2006-03-02 AF + + QString oldHoverLink_; // Added 2006-02-10 AF + + int oldHeight_; // Added 2006-04-10 AF + }; + + //*************************************************** + class MyTextBrowser : public QTextBrowser + { + Q_OBJECT + + public: + MyTextBrowser(QWidget *parent=0); + virtual ~MyTextBrowser(); + + void setActive( bool active ); // Added 2006-04-25 AF + + signals: + void openLink(const QUrl *); // Changed 2005-11-03 AF + void clickOnCell(); // Added 2005-11-01 AF + void wheelMove( QWheelEvent* ); // Added 2005-11-28 AF + void forwardAction( int ); // Added 2006-04-27 AF + + public slots: + void setSource(const QUrl &name); // Changed 2005-11-03 AF + + protected: + void mousePressEvent(QMouseEvent *event); // Added 2005-11-01 AF + void wheelEvent(QWheelEvent * event); // Added 2005-11-28 AF + void insertFromMimeData(const QMimeData *source); // Added 2006-01-23 AF + void keyPressEvent(QKeyEvent *event ); // Added 2006-01-30 AF + + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/textcursorcommands.cpp b/OMNotebook/OMNotebookQT4/textcursorcommands.cpp index 1141a62c876..3629cbbd9f8 100644 --- a/OMNotebook/OMNotebookQT4/textcursorcommands.cpp +++ b/OMNotebook/OMNotebookQT4/textcursorcommands.cpp @@ -60,559 +60,559 @@ namespace IAEX { - /*! + /*! * \class TextCursorCutText - * \author Anders Fernström - * \date 2006-02-07 + * \author Anders Fernström + * \date 2006-02-07 * * \brief Command for cuting text */ - void TextCursorCutText::execute() - { - Cell *cell = document()->getCursor()->currentCell(); - if( cell ) - { - if( typeid(InputCell) == typeid(*cell) ) - { - InputCell *inputcell = dynamic_cast(cell); - if( inputcell->textEditOutput()->hasFocus() && - inputcell->isEvaluated() ) - { - inputcell->textEditOutput()->copy(); - } - else - inputcell->textEdit()->cut(); - } - else if( typeid(GraphCell) == typeid(*cell) ) - { - GraphCell *graphcell = dynamic_cast(cell); - if( graphcell->textEditOutput()->hasFocus() && - graphcell->isEvaluated() ) - { - graphcell->textEditOutput()->copy(); - } - else - graphcell->textEdit()->cut(); - } - - - else - { - QTextEdit *editor = cell->textEdit(); - if( editor ) - { - editor->cut(); - } - } - } - } - - - /*! + void TextCursorCutText::execute() + { + Cell *cell = document()->getCursor()->currentCell(); + if( cell ) + { + if( typeid(InputCell) == typeid(*cell) ) + { + InputCell *inputcell = dynamic_cast(cell); + if( inputcell->textEditOutput()->hasFocus() && + inputcell->isEvaluated() ) + { + inputcell->textEditOutput()->copy(); + } + else + inputcell->textEdit()->cut(); + } + else if( typeid(GraphCell) == typeid(*cell) ) + { + GraphCell *graphcell = dynamic_cast(cell); + if( graphcell->textEditOutput()->hasFocus() && + graphcell->isEvaluated() ) + { + graphcell->textEditOutput()->copy(); + } + else + graphcell->textEdit()->cut(); + } + + + else + { + QTextEdit *editor = cell->textEdit(); + if( editor ) + { + editor->cut(); + } + } + } + } + + + /*! * \class TextCursorCopyText - * \author Anders Fernström - * \date 2006-02-07 + * \author Anders Fernström + * \date 2006-02-07 * * \brief Command for copying text */ - void TextCursorCopyText::execute() - { - Cell *cell = document()->getCursor()->currentCell(); - if( cell ) - { - if( typeid(InputCell) == typeid(*cell) ) - { - InputCell *inputcell = dynamic_cast(cell); - if( inputcell->textEditOutput()->hasFocus() && - inputcell->isEvaluated() ) - { - inputcell->textEditOutput()->copy(); - } - else - inputcell->textEdit()->copy(); - } - else if( typeid(GraphCell) == typeid(*cell) ) - { - GraphCell *graphcell = dynamic_cast(cell); - if( graphcell->textEditOutput()->hasFocus() && - graphcell->isEvaluated() ) - { - graphcell->textEditOutput()->copy(); - } - else - graphcell->textEdit()->copy(); - } - else - { - QTextEdit *editor = cell->textEdit(); - if( editor ) - { - editor->copy(); - } - } - } - } - - - /*! + void TextCursorCopyText::execute() + { + Cell *cell = document()->getCursor()->currentCell(); + if( cell ) + { + if( typeid(InputCell) == typeid(*cell) ) + { + InputCell *inputcell = dynamic_cast(cell); + if( inputcell->textEditOutput()->hasFocus() && + inputcell->isEvaluated() ) + { + inputcell->textEditOutput()->copy(); + } + else + inputcell->textEdit()->copy(); + } + else if( typeid(GraphCell) == typeid(*cell) ) + { + GraphCell *graphcell = dynamic_cast(cell); + if( graphcell->textEditOutput()->hasFocus() && + graphcell->isEvaluated() ) + { + graphcell->textEditOutput()->copy(); + } + else + graphcell->textEdit()->copy(); + } + else + { + QTextEdit *editor = cell->textEdit(); + if( editor ) + { + editor->copy(); + } + } + } + } + + + /*! * \class TextCursorCopyText - * \author Anders Fernström - * \date 2006-02-07 + * \author Anders Fernström + * \date 2006-02-07 * * \brief Command for pasting text */ - void TextCursorPasteText::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - { - editor->paste(); - } - } + void TextCursorPasteText::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + if( editor ) + { + editor->paste(); + } + } - /*! + /*! * \class TextCursorChangeFontFamily - * \author Anders Fernström - * \date 2005-11-03 + * \author Anders Fernström + * \date 2005-11-03 * * \brief Command for changing font family */ - void TextCursorChangeFontFamily::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + void TextCursorChangeFontFamily::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - editor->setFontFamily( family_ ); - } + if( editor ) + editor->setFontFamily( family_ ); + } - /*! + /*! * \class TextCursorChangeFontFace - * \author Anders Fernström - * \date 2005-11-03 - * \date 2006-01-13 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2006-01-13 (update) * * \brief Command for changing font face - * - * 2005-11-07 AF, Added function (case 4) in switch to change - * strikckout settings - * 2005-11-15 AF, added trick to get correct style on links - * 2006-01-13 AF, remove trick to get correct style on links because - * it made undo/redo work incorrectly + * + * 2005-11-07 AF, Added function (case 4) in switch to change + * strikckout settings + * 2005-11-15 AF, added trick to get correct style on links + * 2006-01-13 AF, remove trick to get correct style on links because + * it made undo/redo work incorrectly */ - void TextCursorChangeFontFace::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - QFont font; - - if( editor ) - { - switch( face_ ) - { - case 0: // Plain - editor->setFontWeight( QFont::Normal ); - editor->setFontItalic( false ); - editor->setFontUnderline( false ); - - font = editor->currentFont(); - font.setStrikeOut( false ); - editor->setCurrentFont( font ); - break; - case 1: // Bold - if( editor->fontWeight() != QFont::Normal ) - editor->setFontWeight( QFont::Normal ); - else - editor->setFontWeight( QFont::Bold ); - break; - case 2: // Italic - if( editor->fontItalic() ) - editor->setFontItalic( false ); - else - editor->setFontItalic( true ); - break; - case 3: // Underline - if( editor->fontUnderline() ) - editor->setFontUnderline( false ); - else - editor->setFontUnderline( true ); - break; - case 4: // Strickout - font = editor->currentFont(); - if( font.strikeOut() ) - font.setStrikeOut( false ); - else - font.setStrikeOut( true ); - editor->setCurrentFont( font ); - break; - } - - // ugly trick to make the sure that the links haven't change - // color - /* - if( !editor->toPlainText().isEmpty() ) - { - int start = editor->textCursor().selectionStart(); - int end = editor->textCursor().selectionEnd(); - editor->setHtml( editor->toHtml() ); - - QTextCursor cursor( editor->textCursor() ); - cursor.setPosition( start ); - cursor.setPosition( end, QTextCursor::KeepAnchor ); - editor->setTextCursor( cursor ); - }*/ - } - } - - - /*! + void TextCursorChangeFontFace::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + QFont font; + + if( editor ) + { + switch( face_ ) + { + case 0: // Plain + editor->setFontWeight( QFont::Normal ); + editor->setFontItalic( false ); + editor->setFontUnderline( false ); + + font = editor->currentFont(); + font.setStrikeOut( false ); + editor->setCurrentFont( font ); + break; + case 1: // Bold + if( editor->fontWeight() != QFont::Normal ) + editor->setFontWeight( QFont::Normal ); + else + editor->setFontWeight( QFont::Bold ); + break; + case 2: // Italic + if( editor->fontItalic() ) + editor->setFontItalic( false ); + else + editor->setFontItalic( true ); + break; + case 3: // Underline + if( editor->fontUnderline() ) + editor->setFontUnderline( false ); + else + editor->setFontUnderline( true ); + break; + case 4: // Strickout + font = editor->currentFont(); + if( font.strikeOut() ) + font.setStrikeOut( false ); + else + font.setStrikeOut( true ); + editor->setCurrentFont( font ); + break; + } + + // ugly trick to make the sure that the links haven't change + // color + /* + if( !editor->toPlainText().isEmpty() ) + { + int start = editor->textCursor().selectionStart(); + int end = editor->textCursor().selectionEnd(); + editor->setHtml( editor->toHtml() ); + + QTextCursor cursor( editor->textCursor() ); + cursor.setPosition( start ); + cursor.setPosition( end, QTextCursor::KeepAnchor ); + editor->setTextCursor( cursor ); + }*/ + } + } + + + /*! * \class TextCursorChangeFontSize - * \author Anders Fernström - * \date 2005-11-03 - * \date 2005-11-04 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2005-11-04 (update) * * \brief Command for changing font size - * - * 2005-11-04 AF, implemented the function + * + * 2005-11-04 AF, implemented the function */ - void TextCursorChangeFontSize::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + void TextCursorChangeFontSize::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - editor->setFontPointSize( size_ ); + if( editor ) + editor->setFontPointSize( size_ ); - } + } - /*! + /*! * \class TextCursorChangeFontStretch - * \author Anders Fernström - * \date 2005-11-03 - * \date 2005-11-04 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2005-11-04 (update) * * \brief Command for changing font stretch - * - * 2005-11-04 AF, implemented the function + * + * 2005-11-04 AF, implemented the function */ - void TextCursorChangeFontStretch::execute() - { - QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - QTextCharFormat format = cursor.charFormat(); - QFont font = format.font(); - - int oldStretch = font.stretch(); - if( oldStretch != stretch_ ) - { - font.setStretch( stretch_ ); - format.setFont( font ); - - cursor.mergeCharFormat ( format ); - - if( oldStretch == cursor.charFormat().font().stretch() ) - { - // 2006-01-30 AF, add message box - QString msg = "QT was unable to stretch the font"; - QMessageBox::warning( 0, "Warning", msg, "OK" ); - } - } - } - - } - - - /*! + void TextCursorChangeFontStretch::execute() + { + QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + QTextCharFormat format = cursor.charFormat(); + QFont font = format.font(); + + int oldStretch = font.stretch(); + if( oldStretch != stretch_ ) + { + font.setStretch( stretch_ ); + format.setFont( font ); + + cursor.mergeCharFormat ( format ); + + if( oldStretch == cursor.charFormat().font().stretch() ) + { + // 2006-01-30 AF, add message box + QString msg = "QT was unable to stretch the font"; + QMessageBox::warning( 0, "Warning", msg, "OK" ); + } + } + } + + } + + + /*! * \class TextCursorChangeFontColor - * \author Anders Fernström - * \date 2005-11-03 - * \date 2006-01-13 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2006-01-13 (update) * * \brief Command for changing font color - * - * 2005-11-07 AF, implemented the function - * 2005-11-15 AF, added trick to get correct style on links - * 2006-01-13 AF, remove trick to get correct style on links because - * it made undo/redo work incorrectly + * + * 2005-11-07 AF, implemented the function + * 2005-11-15 AF, added trick to get correct style on links + * 2006-01-13 AF, remove trick to get correct style on links because + * it made undo/redo work incorrectly */ - void TextCursorChangeFontColor::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - - if( editor ) - { - editor->setTextColor( color_ ); - - - // ugly trick to make the sure that the links haven't change - // color - /* - if( !editor->toPlainText().isEmpty() ) - { - int start = editor->textCursor().selectionStart(); - int end = editor->textCursor().selectionEnd(); - editor->setHtml( editor->toHtml() ); - - QTextCursor cursor( editor->textCursor() ); - cursor.setPosition( start ); - cursor.setPosition( end, QTextCursor::KeepAnchor ); - editor->setTextCursor( cursor ); - } - */ - } - } - - - /*! + void TextCursorChangeFontColor::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + + if( editor ) + { + editor->setTextColor( color_ ); + + + // ugly trick to make the sure that the links haven't change + // color + /* + if( !editor->toPlainText().isEmpty() ) + { + int start = editor->textCursor().selectionStart(); + int end = editor->textCursor().selectionEnd(); + editor->setHtml( editor->toHtml() ); + + QTextCursor cursor( editor->textCursor() ); + cursor.setPosition( start ); + cursor.setPosition( end, QTextCursor::KeepAnchor ); + editor->setTextCursor( cursor ); + } + */ + } + } + + + /*! * \class TextCursorChangeTextAlignment - * \author Anders Fernström - * \date 2005-11-03 - * \date 2005-11-07 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2005-11-07 (update) * * \brief Command for changing text alignment - * - * 2005-11-07 AF, implemented the function + * + * 2005-11-07 AF, implemented the function */ - void TextCursorChangeTextAlignment::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - - if( editor ) - { - editor->setAlignment( (Qt::Alignment)alignment_ ); - - // create a rule for the alignment - Rule *rule; - if( (Qt::Alignment)alignment_ == Qt::AlignLeft ) - rule = new Rule( "TextAlignment", "Left" ); - else if( (Qt::Alignment)alignment_ == Qt::AlignRight ) - rule = new Rule( "TextAlignment", "Right" ); - else if( (Qt::Alignment)alignment_ == Qt::AlignHCenter ) - rule = new Rule( "TextAlignment", "Center" ); - else if( (Qt::Alignment)alignment_ == Qt::AlignJustify ) - rule = new Rule( "TextAlignment", "Justify" ); - - document()->getCursor()->currentCell()->addRule( rule ); - - // update the cells style - document()->getCursor()->currentCell()->style()->setAlignment( alignment_ ); - } - } - - - /*! + void TextCursorChangeTextAlignment::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + + if( editor ) + { + editor->setAlignment( (Qt::Alignment)alignment_ ); + + // create a rule for the alignment + Rule *rule; + if( (Qt::Alignment)alignment_ == Qt::AlignLeft ) + rule = new Rule( "TextAlignment", "Left" ); + else if( (Qt::Alignment)alignment_ == Qt::AlignRight ) + rule = new Rule( "TextAlignment", "Right" ); + else if( (Qt::Alignment)alignment_ == Qt::AlignHCenter ) + rule = new Rule( "TextAlignment", "Center" ); + else if( (Qt::Alignment)alignment_ == Qt::AlignJustify ) + rule = new Rule( "TextAlignment", "Justify" ); + + document()->getCursor()->currentCell()->addRule( rule ); + + // update the cells style + document()->getCursor()->currentCell()->style()->setAlignment( alignment_ ); + } + } + + + /*! * \class TextCursorChangeVerticalAlignment - * \author Anders Fernström - * \date 2005-11-03 - * \date 2005-11-07 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2005-11-07 (update) * * \brief Command for changing the vertical alignment - * - * 2005-11-07 AF, implemented the function + * + * 2005-11-07 AF, implemented the function */ - void TextCursorChangeVerticalAlignment::execute() - { - QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { + void TextCursorChangeVerticalAlignment::execute() + { + QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { - QTextCharFormat format = cursor.charFormat(); - format.setVerticalAlignment( (QTextCharFormat::VerticalAlignment)alignment_ ); + QTextCharFormat format = cursor.charFormat(); + format.setVerticalAlignment( (QTextCharFormat::VerticalAlignment)alignment_ ); - cursor.mergeCharFormat ( format ); - } - } + cursor.mergeCharFormat ( format ); + } + } - /*! + /*! * \class TextCursorChangeMargin - * \author Anders Fernström - * \date 2005-11-03 - * \date 2005-11-07 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2005-11-07 (update) * * \brief Command for changing margin - * - * 2005-11-07 AF, implemented the function + * + * 2005-11-07 AF, implemented the function */ - void TextCursorChangeMargin::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + void TextCursorChangeMargin::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - { - QTextFrameFormat format = editor->document()->rootFrame()->frameFormat(); - format.setMargin( margin_ ); - editor->document()->rootFrame()->setFrameFormat( format ); + if( editor ) + { + QTextFrameFormat format = editor->document()->rootFrame()->frameFormat(); + format.setMargin( margin_ ); + editor->document()->rootFrame()->setFrameFormat( format ); - // create a rule for the margin - QString ruleValue; - ruleValue.setNum( margin_ ); - Rule *rule = new Rule( "OMNotebook_Margin", ruleValue ); - document()->getCursor()->currentCell()->addRule( rule ); + // create a rule for the margin + QString ruleValue; + ruleValue.setNum( margin_ ); + Rule *rule = new Rule( "OMNotebook_Margin", ruleValue ); + document()->getCursor()->currentCell()->addRule( rule ); - // update the cells style - document()->getCursor()->currentCell()->style()->textFrameFormat()->setMargin( margin_ ); - } - } + // update the cells style + document()->getCursor()->currentCell()->style()->textFrameFormat()->setMargin( margin_ ); + } + } - /*! + /*! * \class TextCursorChangePadding - * \author Anders Fernström - * \date 2005-11-03 - * \date 2005-11-07 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2005-11-07 (update) * * \brief Command for changing padding - * - * 2005-11-07 AF, implemented the function + * + * 2005-11-07 AF, implemented the function */ - void TextCursorChangePadding::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + void TextCursorChangePadding::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - { - QTextFrameFormat format = editor->document()->rootFrame()->frameFormat(); - format.setPadding( padding_ ); - editor->document()->rootFrame()->setFrameFormat( format ); + if( editor ) + { + QTextFrameFormat format = editor->document()->rootFrame()->frameFormat(); + format.setPadding( padding_ ); + editor->document()->rootFrame()->setFrameFormat( format ); - // create a rule for the padding - QString ruleValue; - ruleValue.setNum( padding_ ); - Rule *rule = new Rule( "OMNotebook_Padding", ruleValue ); - document()->getCursor()->currentCell()->addRule( rule ); + // create a rule for the padding + QString ruleValue; + ruleValue.setNum( padding_ ); + Rule *rule = new Rule( "OMNotebook_Padding", ruleValue ); + document()->getCursor()->currentCell()->addRule( rule ); - // update the cells style - document()->getCursor()->currentCell()->style()->textFrameFormat()->setPadding( padding_ ); - } - } + // update the cells style + document()->getCursor()->currentCell()->style()->textFrameFormat()->setPadding( padding_ ); + } + } - /*! + /*! * \class TextCursorChangeBorder - * \author Anders Fernström - * \date 2005-11-03 - * \date 2005-11-07 (update) + * \author Anders Fernström + * \date 2005-11-03 + * \date 2005-11-07 (update) * * \brief Command for changing border - * - * 2005-11-07 AF, implemented the function + * + * 2005-11-07 AF, implemented the function */ - void TextCursorChangeBorder::execute() - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + void TextCursorChangeBorder::execute() + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - { - QTextFrameFormat format = editor->document()->rootFrame()->frameFormat(); - format.setBorder( border_ ); - editor->document()->rootFrame()->setFrameFormat( format ); + if( editor ) + { + QTextFrameFormat format = editor->document()->rootFrame()->frameFormat(); + format.setBorder( border_ ); + editor->document()->rootFrame()->setFrameFormat( format ); - // create a rule for the border - QString ruleValue; - ruleValue.setNum( border_ ); - Rule *rule = new Rule( "OMNotebook_Border", ruleValue ); - document()->getCursor()->currentCell()->addRule( rule ); + // create a rule for the border + QString ruleValue; + ruleValue.setNum( border_ ); + Rule *rule = new Rule( "OMNotebook_Border", ruleValue ); + document()->getCursor()->currentCell()->addRule( rule ); - // update the cells style - document()->getCursor()->currentCell()->style()->textFrameFormat()->setBorder( border_ ); - } - } + // update the cells style + document()->getCursor()->currentCell()->style()->textFrameFormat()->setBorder( border_ ); + } + } - /*! + /*! * \class TextCursorInsertImage - * \author Anders Fernström - * \date 2005-11-18 + * \author Anders Fernström + * \date 2005-11-18 * * \brief Command for inserting an image */ - void TextCursorInsertImage::execute() - { - QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - QImage* image = new QImage( filepath_ ); - if( !image->isNull() ) - { - QString imagename = document()->addImage( image ); - - QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - { - // save text settings and set them after image have been inserted - QTextCharFormat format = cursor.charFormat(); - if( editor->toPlainText().isEmpty() ) - format = *document()->getCursor()->currentCell()->style()->textCharFormat(); - - QTextImageFormat imageformat; - imageformat.merge( format ); - imageformat.setHeight( height_ ); - imageformat.setWidth( width_ ); - imageformat.setName( imagename ); - - cursor.insertImage( imageformat ); - } - } - } - else - { - string str = string("Could not open image: ") + filepath_.toStdString().c_str(); - throw runtime_error( str.c_str() ); - } - } - } - - - /*! + void TextCursorInsertImage::execute() + { + QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + QImage* image = new QImage( filepath_ ); + if( !image->isNull() ) + { + QString imagename = document()->addImage( image ); + + QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); + if( editor ) + { + // save text settings and set them after image have been inserted + QTextCharFormat format = cursor.charFormat(); + if( editor->toPlainText().isEmpty() ) + format = *document()->getCursor()->currentCell()->style()->textCharFormat(); + + QTextImageFormat imageformat; + imageformat.merge( format ); + imageformat.setHeight( height_ ); + imageformat.setWidth( width_ ); + imageformat.setName( imagename ); + + cursor.insertImage( imageformat ); + } + } + } + else + { + string str = string("Could not open image: ") + filepath_.toStdString().c_str(); + throw runtime_error( str.c_str() ); + } + } + } + + + /*! * \class TextCursorInsertLink - * \author Anders Fernström - * \date 2005-12-05 + * \author Anders Fernström + * \date 2005-12-05 * * \brief Command for inserting an link */ - void TextCursorInsertLink::execute() - - { - -// QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); - if( !cursor.isNull() ) - { - if( cursor.hasSelection() ) - { - QDir dir; - QString currentfilepath = document()->getFilename(); - if( !currentfilepath.isEmpty() && !currentfilepath.isNull() ) - dir.setPath( QFileInfo(currentfilepath).absolutePath() ); - - // check if dir exist - if( !dir.exists() ) - return; - // get the relative link path - QString relativepath = dir.relativeFilePath( filepath_ ); - - // create html code for the link and insert it to the document' - QString text = cursor.selection().toHtml(); - int fragmentStart = text.indexOf( "", - 0, Qt::CaseInsensitive ) + 20; - int fragmentEnd = text.indexOf( "", - fragmentStart, Qt::CaseInsensitive ); - - QString html = text.mid( fragmentStart, fragmentEnd - fragmentStart ); - QString htmlcode = "" + - html + ""; - cursor.insertFragment( QTextDocumentFragment::fromHtml( htmlcode )); - - // set the cursor, so there is no selection + void TextCursorInsertLink::execute() + + { + +// QTextCursor cursor( document()->getCursor()->currentCell()->textCursor() ); + if( !cursor.isNull() ) + { + if( cursor.hasSelection() ) + { + QDir dir; + QString currentfilepath = document()->getFilename(); + if( !currentfilepath.isEmpty() && !currentfilepath.isNull() ) + dir.setPath( QFileInfo(currentfilepath).absolutePath() ); + + // check if dir exist + if( !dir.exists() ) + return; + // get the relative link path + QString relativepath = dir.relativeFilePath( filepath_ ); + + // create html code for the link and insert it to the document' + QString text = cursor.selection().toHtml(); + int fragmentStart = text.indexOf( "", + 0, Qt::CaseInsensitive ) + 20; + int fragmentEnd = text.indexOf( "", + fragmentStart, Qt::CaseInsensitive ); + + QString html = text.mid( fragmentStart, fragmentEnd - fragmentStart ); + QString htmlcode = "" + + html + ""; + cursor.insertFragment( QTextDocumentFragment::fromHtml( htmlcode )); + + // set the cursor, so there is no selection QTextEdit *editor = document()->getCursor()->currentCell()->textEdit(); - if( editor ) - editor->setTextCursor( cursor ); - } - } - } + if( editor ) + editor->setTextCursor( cursor ); + } + } + } } diff --git a/OMNotebook/OMNotebookQT4/textcursorcommands.h b/OMNotebook/OMNotebookQT4/textcursorcommands.h index e1ffb20d322..533a98069c6 100644 --- a/OMNotebook/OMNotebookQT4/textcursorcommands.h +++ b/OMNotebook/OMNotebookQT4/textcursorcommands.h @@ -50,206 +50,206 @@ using namespace std; namespace IAEX { - // Added 2006-02-07 AF - class TextCursorCutText : public Command - { - public: - TextCursorCutText(){} - virtual ~TextCursorCutText(){} - virtual QString commandName(){ return QString("TextCursorCutText"); } - void execute(); - }; - - // Added 2006-02-07 AF - class TextCursorCopyText : public Command - { - public: - TextCursorCopyText(){} - virtual ~TextCursorCopyText(){} - virtual QString commandName(){ return QString("TextCursorCopyText"); } - void execute(); - }; - - - // Added 2006-02-07 AF - class TextCursorPasteText : public Command - { - public: - TextCursorPasteText(){} - virtual ~TextCursorPasteText(){} - virtual QString commandName(){ return QString("TextCursorPasteText"); } - void execute(); - }; - - class TextCursorChangeFontFamily : public Command - { - public: - TextCursorChangeFontFamily(QString family) - : family_(family){} - virtual ~TextCursorChangeFontFamily(){} - virtual QString commandName(){ return QString("TextCursorChangeFontFamily"); } - void execute(); - - private: - QString family_; - }; - - - class TextCursorChangeFontFace : public Command - { - public: - TextCursorChangeFontFace(int face) - : face_(face){} - virtual ~TextCursorChangeFontFace(){} - virtual QString commandName(){ return QString("TextCursorChangeFontFace"); } - void execute(); - - private: - int face_; - }; - - - class TextCursorChangeFontSize : public Command - { - public: - TextCursorChangeFontSize(int size) - : size_(size){} - virtual ~TextCursorChangeFontSize(){} - virtual QString commandName(){ return QString("TextCursorChangeFontSize"); } - void execute(); - - private: - int size_; - }; - - - class TextCursorChangeFontStretch : public Command - { - public: - TextCursorChangeFontStretch(int stretch) - : stretch_(stretch){} - virtual ~TextCursorChangeFontStretch(){} - virtual QString commandName(){ return QString("TextCursorChangeFontStretch"); } - void execute(); - - private: - int stretch_; - }; - - - class TextCursorChangeFontColor : public Command - { - public: - TextCursorChangeFontColor(QColor color) - : color_(color){} - virtual ~TextCursorChangeFontColor(){} - virtual QString commandName(){ return QString("TextCursorChangeFontColor"); } - void execute(); - - private: - QColor color_; - }; - - - class TextCursorChangeTextAlignment : public Command - { - public: - TextCursorChangeTextAlignment(int alignment) - : alignment_(alignment){} - virtual ~TextCursorChangeTextAlignment(){} - virtual QString commandName(){ return QString("TextCursorChangeTextAlignment"); } - void execute(); - - private: - int alignment_; - }; - - - class TextCursorChangeVerticalAlignment : public Command - { - public: - TextCursorChangeVerticalAlignment(int alignment) - : alignment_(alignment){} - virtual ~TextCursorChangeVerticalAlignment(){} - virtual QString commandName(){ return QString("TextCursorChangeVerticalAlignment"); } - void execute(); - - private: - int alignment_; - }; - - - class TextCursorChangeMargin : public Command - { - public: - TextCursorChangeMargin(int margin) - : margin_(margin){} - virtual ~TextCursorChangeMargin(){} - virtual QString commandName(){ return QString("TextCursorChangeMargin"); } - void execute(); - - private: - int margin_; - }; - - - class TextCursorChangePadding : public Command - { - public: - TextCursorChangePadding(int padding) - : padding_(padding){} - virtual ~TextCursorChangePadding(){} - virtual QString commandName(){ return QString("TextCursorChangePadding"); } - void execute(); - - private: - int padding_; - }; - - - class TextCursorChangeBorder : public Command - { - public: - TextCursorChangeBorder(int border) - : border_(border){} - virtual ~TextCursorChangeBorder(){} - virtual QString commandName(){ return QString("TextCursorChangeBorder"); } - void execute(); - - private: - int border_; - }; - - - class TextCursorInsertImage : public Command - { - public: - TextCursorInsertImage(QString filepath, QSize size) - : filepath_(filepath), height_(size.height()), width_(size.width()){} - virtual ~TextCursorInsertImage(){} - virtual QString commandName(){ return QString("TextCursorInsertImage"); } - void execute(); - - private: - QString filepath_; - int height_; - int width_; - }; - - - class TextCursorInsertLink : public Command - { - public: - TextCursorInsertLink( QString filepath, QTextCursor& cursor_ ) - : filepath_(filepath), cursor(cursor_){} - virtual ~TextCursorInsertLink(){} - virtual QString commandName(){ return QString("TextCursorInsertLink"); } - void execute(); - - private: - QString filepath_; - QTextCursor cursor; - }; + // Added 2006-02-07 AF + class TextCursorCutText : public Command + { + public: + TextCursorCutText(){} + virtual ~TextCursorCutText(){} + virtual QString commandName(){ return QString("TextCursorCutText"); } + void execute(); + }; + + // Added 2006-02-07 AF + class TextCursorCopyText : public Command + { + public: + TextCursorCopyText(){} + virtual ~TextCursorCopyText(){} + virtual QString commandName(){ return QString("TextCursorCopyText"); } + void execute(); + }; + + + // Added 2006-02-07 AF + class TextCursorPasteText : public Command + { + public: + TextCursorPasteText(){} + virtual ~TextCursorPasteText(){} + virtual QString commandName(){ return QString("TextCursorPasteText"); } + void execute(); + }; + + class TextCursorChangeFontFamily : public Command + { + public: + TextCursorChangeFontFamily(QString family) + : family_(family){} + virtual ~TextCursorChangeFontFamily(){} + virtual QString commandName(){ return QString("TextCursorChangeFontFamily"); } + void execute(); + + private: + QString family_; + }; + + + class TextCursorChangeFontFace : public Command + { + public: + TextCursorChangeFontFace(int face) + : face_(face){} + virtual ~TextCursorChangeFontFace(){} + virtual QString commandName(){ return QString("TextCursorChangeFontFace"); } + void execute(); + + private: + int face_; + }; + + + class TextCursorChangeFontSize : public Command + { + public: + TextCursorChangeFontSize(int size) + : size_(size){} + virtual ~TextCursorChangeFontSize(){} + virtual QString commandName(){ return QString("TextCursorChangeFontSize"); } + void execute(); + + private: + int size_; + }; + + + class TextCursorChangeFontStretch : public Command + { + public: + TextCursorChangeFontStretch(int stretch) + : stretch_(stretch){} + virtual ~TextCursorChangeFontStretch(){} + virtual QString commandName(){ return QString("TextCursorChangeFontStretch"); } + void execute(); + + private: + int stretch_; + }; + + + class TextCursorChangeFontColor : public Command + { + public: + TextCursorChangeFontColor(QColor color) + : color_(color){} + virtual ~TextCursorChangeFontColor(){} + virtual QString commandName(){ return QString("TextCursorChangeFontColor"); } + void execute(); + + private: + QColor color_; + }; + + + class TextCursorChangeTextAlignment : public Command + { + public: + TextCursorChangeTextAlignment(int alignment) + : alignment_(alignment){} + virtual ~TextCursorChangeTextAlignment(){} + virtual QString commandName(){ return QString("TextCursorChangeTextAlignment"); } + void execute(); + + private: + int alignment_; + }; + + + class TextCursorChangeVerticalAlignment : public Command + { + public: + TextCursorChangeVerticalAlignment(int alignment) + : alignment_(alignment){} + virtual ~TextCursorChangeVerticalAlignment(){} + virtual QString commandName(){ return QString("TextCursorChangeVerticalAlignment"); } + void execute(); + + private: + int alignment_; + }; + + + class TextCursorChangeMargin : public Command + { + public: + TextCursorChangeMargin(int margin) + : margin_(margin){} + virtual ~TextCursorChangeMargin(){} + virtual QString commandName(){ return QString("TextCursorChangeMargin"); } + void execute(); + + private: + int margin_; + }; + + + class TextCursorChangePadding : public Command + { + public: + TextCursorChangePadding(int padding) + : padding_(padding){} + virtual ~TextCursorChangePadding(){} + virtual QString commandName(){ return QString("TextCursorChangePadding"); } + void execute(); + + private: + int padding_; + }; + + + class TextCursorChangeBorder : public Command + { + public: + TextCursorChangeBorder(int border) + : border_(border){} + virtual ~TextCursorChangeBorder(){} + virtual QString commandName(){ return QString("TextCursorChangeBorder"); } + void execute(); + + private: + int border_; + }; + + + class TextCursorInsertImage : public Command + { + public: + TextCursorInsertImage(QString filepath, QSize size) + : filepath_(filepath), height_(size.height()), width_(size.width()){} + virtual ~TextCursorInsertImage(){} + virtual QString commandName(){ return QString("TextCursorInsertImage"); } + void execute(); + + private: + QString filepath_; + int height_; + int width_; + }; + + + class TextCursorInsertLink : public Command + { + public: + TextCursorInsertLink( QString filepath, QTextCursor& cursor_ ) + : filepath_(filepath), cursor(cursor_){} + virtual ~TextCursorInsertLink(){} + virtual QString commandName(){ return QString("TextCursorInsertLink"); } + void execute(); + + private: + QString filepath_; + QTextCursor cursor; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/treeview.cpp b/OMNotebook/OMNotebookQT4/treeview.cpp index 0be0dbe1c70..0b7545c2c07 100644 --- a/OMNotebook/OMNotebookQT4/treeview.cpp +++ b/OMNotebook/OMNotebookQT4/treeview.cpp @@ -51,13 +51,13 @@ namespace IAEX selected_(false), closed_(false), //selectedColor_(QColor(0,0,255)) - selectedColor_(QColor(160,160,160)) + selectedColor_(QColor(160,160,160)) { setFixedWidth(10); setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding)); - // PORT >> setBackgroundMode(Qt::PaletteBase); - setBackgroundRole( QPalette::Base ); + // PORT >> setBackgroundMode(Qt::PaletteBase); + setBackgroundRole( QPalette::Base ); } /*! \brief Set the background color of the treeview. @@ -111,52 +111,52 @@ namespace IAEX return backgroundColor_; } - /*! \brief Describes what a TreeView widget will look like. - * - * \bug Some cells are closed even if they cant be closed. This must - * be fixed in some way. - */ - void TreeView::paintEvent(QPaintEvent *event) - { - QPainter painter(this); - - if(selected_) - { - painter.setPen( QPen( QBrush( selectedColor() ), 10 )); - painter.drawRect( this->rect() ); - - painter.setPen(QPen( QBrush( QColor(160,0,0) ), 1, Qt::SolidLine)); - } - else - { - painter.setPen( QPen( QBrush( backgroundColor() ), 10 )); - - painter.drawRect( this->rect() ); - - painter.setPen(QPen(Qt::black,1, Qt::SolidLine)); - } - - QPolygon points(4); - - if(closed_) - { - points[0] = QPoint(1,2); - points[1] = QPoint(5,2); - points[2] = QPoint(5, height()-2); - points[3] = QPoint(1, height()-8); - } - else - { - points[0] = QPoint(1,2); - points[1] = QPoint(5,2); - points[2] = QPoint(5,height()-2); - points[3] = QPoint(1,height()-2); - } - - painter.drawPolyline(points); - - QWidget::paintEvent(event); - } + /*! \brief Describes what a TreeView widget will look like. + * + * \bug Some cells are closed even if they cant be closed. This must + * be fixed in some way. + */ + void TreeView::paintEvent(QPaintEvent *event) + { + QPainter painter(this); + + if(selected_) + { + painter.setPen( QPen( QBrush( selectedColor() ), 10 )); + painter.drawRect( this->rect() ); + + painter.setPen(QPen( QBrush( QColor(160,0,0) ), 1, Qt::SolidLine)); + } + else + { + painter.setPen( QPen( QBrush( backgroundColor() ), 10 )); + + painter.drawRect( this->rect() ); + + painter.setPen(QPen(Qt::black,1, Qt::SolidLine)); + } + + QPolygon points(4); + + if(closed_) + { + points[0] = QPoint(1,2); + points[1] = QPoint(5,2); + points[2] = QPoint(5, height()-2); + points[3] = QPoint(1, height()-8); + } + else + { + points[0] = QPoint(1,2); + points[1] = QPoint(5,2); + points[2] = QPoint(5,height()-2); + points[3] = QPoint(1,height()-2); + } + + painter.drawPolyline(points); + + QWidget::paintEvent(event); + } ////////////////////////////////////////////////////////////////////// @@ -169,48 +169,48 @@ namespace IAEX : TreeView(parent) {} - void InputTreeView::paintEvent(QPaintEvent *event) - { - QPainter painter(this); + void InputTreeView::paintEvent(QPaintEvent *event) + { + QPainter painter(this); - //Selected or not selected - if(selected()) - { - painter.setPen( QPen( QBrush( selectedColor() ), 10 )); - painter.drawRect( this->rect() ); + //Selected or not selected + if(selected()) + { + painter.setPen( QPen( QBrush( selectedColor() ), 10 )); + painter.drawRect( this->rect() ); - painter.setPen(QPen( QBrush( QColor(160,0,0) ), 1, Qt::SolidLine)); + painter.setPen(QPen( QBrush( QColor(160,0,0) ), 1, Qt::SolidLine)); - painter.drawRect(this->rect().x()-1, this->rect().y(), this->rect().width()-1, this->rect().height()-2); - painter.setPen(QPen(Qt::black,1, Qt::SolidLine)); + painter.drawRect(this->rect().x()-1, this->rect().y(), this->rect().width()-1, this->rect().height()-2); + painter.setPen(QPen(Qt::black,1, Qt::SolidLine)); - } - else - { - painter.setPen( QPen( QBrush( backgroundColor() ), 10 )); + } + else + { + painter.setPen( QPen( QBrush( backgroundColor() ), 10 )); - painter.drawRect( this->rect() ); + painter.drawRect( this->rect() ); -// painter.setPen(QPen(Qt::black,1, Qt::SolidLine)); -// painter.drawRect(this->rect().x()-1, this->rect().y(), this->rect().width()-1, this->rect().height()-2); - painter.setPen(QPen(Qt::black,1, Qt::SolidLine)); - } +// painter.setPen(QPen(Qt::black,1, Qt::SolidLine)); +// painter.drawRect(this->rect().x()-1, this->rect().y(), this->rect().width()-1, this->rect().height()-2); + painter.setPen(QPen(Qt::black,1, Qt::SolidLine)); + } - if(isVisible()) - { - QPolygon points(4); + if(isVisible()) + { + QPolygon points(4); - points[0] = QPoint(1,2); - points[1] = QPoint(5,2); - points[2] = QPoint(5,height()-2); - points[3] = QPoint(1,height()-2); + points[0] = QPoint(1,2); + points[1] = QPoint(5,2); + points[2] = QPoint(5,height()-2); + points[3] = QPoint(1,height()-2); - painter.drawPolyline(points); + painter.drawPolyline(points); - QWidget::paintEvent(event); - } - } + QWidget::paintEvent(event); + } + } } diff --git a/OMNotebook/OMNotebookQT4/updategroupcellvisitor.cpp b/OMNotebook/OMNotebookQT4/updategroupcellvisitor.cpp index 113e48ca5a6..3f5587a9549 100644 --- a/OMNotebook/OMNotebookQT4/updategroupcellvisitor.cpp +++ b/OMNotebook/OMNotebookQT4/updategroupcellvisitor.cpp @@ -45,73 +45,73 @@ namespace IAEX { - /*! - * \class UpdateGroupcellVisitor - * \date 2005-11-30 - * - * \brief call funciton 'closeChildCells()' in every GroupCell - */ + /*! + * \class UpdateGroupcellVisitor + * \date 2005-11-30 + * + * \brief call funciton 'closeChildCells()' in every GroupCell + */ - /*! - * \author Anders Fernström - * - * \brief The class constructor - */ - UpdateGroupcellVisitor::UpdateGroupcellVisitor() - {} + /*! + * \author Anders Fernström + * + * \brief The class constructor + */ + UpdateGroupcellVisitor::UpdateGroupcellVisitor() + {} - /*! - * \author Anders Fernström - * - * \brief The class deconstructor - */ - UpdateGroupcellVisitor::~UpdateGroupcellVisitor() - {} + /*! + * \author Anders Fernström + * + * \brief The class deconstructor + */ + UpdateGroupcellVisitor::~UpdateGroupcellVisitor() + {} - // CELL - void UpdateGroupcellVisitor::visitCellNodeBefore(Cell *) - {} + // CELL + void UpdateGroupcellVisitor::visitCellNodeBefore(Cell *) + {} - void UpdateGroupcellVisitor::visitCellNodeAfter(Cell *) - {} + void UpdateGroupcellVisitor::visitCellNodeAfter(Cell *) + {} - // GROUPCELL - void UpdateGroupcellVisitor::visitCellGroupNodeBefore(CellGroup *node) - { - node->closeChildCells(); - } + // GROUPCELL + void UpdateGroupcellVisitor::visitCellGroupNodeBefore(CellGroup *node) + { + node->closeChildCells(); + } - void UpdateGroupcellVisitor::visitCellGroupNodeAfter(CellGroup *) - {} + void UpdateGroupcellVisitor::visitCellGroupNodeAfter(CellGroup *) + {} - // TEXTCELL - void UpdateGroupcellVisitor::visitTextCellNodeBefore(TextCell *node) - {} + // TEXTCELL + void UpdateGroupcellVisitor::visitTextCellNodeBefore(TextCell *node) + {} - void UpdateGroupcellVisitor::visitTextCellNodeAfter(TextCell *) - {} + void UpdateGroupcellVisitor::visitTextCellNodeAfter(TextCell *) + {} - //INPUTCELL - void UpdateGroupcellVisitor::visitInputCellNodeBefore(InputCell *node) - {} + //INPUTCELL + void UpdateGroupcellVisitor::visitInputCellNodeBefore(InputCell *node) + {} - void UpdateGroupcellVisitor::visitInputCellNodeAfter(InputCell *) - {} + void UpdateGroupcellVisitor::visitInputCellNodeAfter(InputCell *) + {} - //GRAPHCELL + //GRAPHCELL - void UpdateGroupcellVisitor::visitGraphCellNodeBefore(GraphCell *node) - {} + void UpdateGroupcellVisitor::visitGraphCellNodeBefore(GraphCell *node) + {} - void UpdateGroupcellVisitor::visitGraphCellNodeAfter(GraphCell *) - {} + void UpdateGroupcellVisitor::visitGraphCellNodeAfter(GraphCell *) + {} - //CELLCURSOR - void UpdateGroupcellVisitor::visitCellCursorNodeBefore(CellCursor *) - {} + //CELLCURSOR + void UpdateGroupcellVisitor::visitCellCursorNodeBefore(CellCursor *) + {} - void UpdateGroupcellVisitor::visitCellCursorNodeAfter(CellCursor *) - {} + void UpdateGroupcellVisitor::visitCellCursorNodeAfter(CellCursor *) + {} } diff --git a/OMNotebook/OMNotebookQT4/updategroupcellvisitor.h b/OMNotebook/OMNotebookQT4/updategroupcellvisitor.h index f02054d5706..82307985b15 100644 --- a/OMNotebook/OMNotebookQT4/updategroupcellvisitor.h +++ b/OMNotebook/OMNotebookQT4/updategroupcellvisitor.h @@ -44,30 +44,30 @@ namespace IAEX { - class UpdateGroupcellVisitor : public Visitor - { + class UpdateGroupcellVisitor : public Visitor + { - public: - UpdateGroupcellVisitor(); - virtual ~UpdateGroupcellVisitor(); + public: + UpdateGroupcellVisitor(); + virtual ~UpdateGroupcellVisitor(); - virtual void visitCellNodeBefore(Cell *node); - virtual void visitCellNodeAfter(Cell *node); + virtual void visitCellNodeBefore(Cell *node); + virtual void visitCellNodeAfter(Cell *node); - virtual void visitCellGroupNodeBefore(CellGroup *node); - virtual void visitCellGroupNodeAfter(CellGroup *node); + virtual void visitCellGroupNodeBefore(CellGroup *node); + virtual void visitCellGroupNodeAfter(CellGroup *node); - virtual void visitTextCellNodeBefore(TextCell *node); - virtual void visitTextCellNodeAfter(TextCell *node); + virtual void visitTextCellNodeBefore(TextCell *node); + virtual void visitTextCellNodeAfter(TextCell *node); - virtual void visitInputCellNodeBefore(InputCell *node); - virtual void visitInputCellNodeAfter(InputCell *node); + virtual void visitInputCellNodeBefore(InputCell *node); + virtual void visitInputCellNodeAfter(InputCell *node); - virtual void visitGraphCellNodeBefore(GraphCell *node); - virtual void visitGraphCellNodeAfter(GraphCell *node); + virtual void visitGraphCellNodeBefore(GraphCell *node); + virtual void visitGraphCellNodeAfter(GraphCell *node); - virtual void visitCellCursorNodeBefore(CellCursor *cursor); - virtual void visitCellCursorNodeAfter(CellCursor *cursor); - }; + virtual void visitCellCursorNodeBefore(CellCursor *cursor); + virtual void visitCellCursorNodeAfter(CellCursor *cursor); + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/updatelinkvisitor.cpp b/OMNotebook/OMNotebookQT4/updatelinkvisitor.cpp index c352d255e2d..f71c6efd2d4 100644 --- a/OMNotebook/OMNotebookQT4/updatelinkvisitor.cpp +++ b/OMNotebook/OMNotebookQT4/updatelinkvisitor.cpp @@ -52,118 +52,118 @@ namespace IAEX { - /*! - * \class UpdateLinkVisitor - * \date 2005-12-05 - * - * \brief update any links in textcells to reflect any change in - * folder when saving. - */ - - /*! - * \author Anders Fernström - * - * \brief The class constructor - */ - UpdateLinkVisitor::UpdateLinkVisitor(QString oldFilepath, QString newFilepath) - { - oldDir_.setPath( oldFilepath ); - newDir_.setPath( newFilepath ); - - if( !oldDir_.exists() || !newDir_.exists() ) - { - string msg = "UpdateLink, old or new dir don't exists."; - throw runtime_error( msg.c_str() ); - } - } - - /*! - * \author Anders Fernström - * - * \brief The class deconstructor - */ - UpdateLinkVisitor::~UpdateLinkVisitor() - {} - - // CELL - void UpdateLinkVisitor::visitCellNodeBefore(Cell *) - {} - - void UpdateLinkVisitor::visitCellNodeAfter(Cell *) - {} - - // GROUPCELL - void UpdateLinkVisitor::visitCellGroupNodeBefore(CellGroup *node) - {} - - void UpdateLinkVisitor::visitCellGroupNodeAfter(CellGroup *) - {} - - // TEXTCELL - void UpdateLinkVisitor::visitTextCellNodeBefore(TextCell *node) - { - QString html = node->textHtml(); - int pos(0); - while( true ) - { - int startPos = html.indexOf( "textHtml(); + int pos(0); + while( true ) + { + int startPos = html.indexOf( "setTextHtml( html ); - } + // set the new html code to the textcell + node->setTextHtml( html ); + } - void UpdateLinkVisitor::visitTextCellNodeAfter(TextCell *) - {} + void UpdateLinkVisitor::visitTextCellNodeAfter(TextCell *) + {} - //INPUTCELL - void UpdateLinkVisitor::visitInputCellNodeBefore(InputCell *node) - {} + //INPUTCELL + void UpdateLinkVisitor::visitInputCellNodeBefore(InputCell *node) + {} - void UpdateLinkVisitor::visitInputCellNodeAfter(InputCell *) - {} + void UpdateLinkVisitor::visitInputCellNodeAfter(InputCell *) + {} - //GRAPHCELL - void UpdateLinkVisitor::visitGraphCellNodeBefore(GraphCell *node) - {} + //GRAPHCELL + void UpdateLinkVisitor::visitGraphCellNodeBefore(GraphCell *node) + {} - void UpdateLinkVisitor::visitGraphCellNodeAfter(GraphCell *) - {} + void UpdateLinkVisitor::visitGraphCellNodeAfter(GraphCell *) + {} - //CELLCURSOR - void UpdateLinkVisitor::visitCellCursorNodeBefore(CellCursor *) - {} + //CELLCURSOR + void UpdateLinkVisitor::visitCellCursorNodeBefore(CellCursor *) + {} - void UpdateLinkVisitor::visitCellCursorNodeAfter(CellCursor *) - {} + void UpdateLinkVisitor::visitCellCursorNodeAfter(CellCursor *) + {} } diff --git a/OMNotebook/OMNotebookQT4/updatelinkvisitor.h b/OMNotebook/OMNotebookQT4/updatelinkvisitor.h index 0b526b3da66..67f8c9e6ab1 100644 --- a/OMNotebook/OMNotebookQT4/updatelinkvisitor.h +++ b/OMNotebook/OMNotebookQT4/updatelinkvisitor.h @@ -49,34 +49,34 @@ using namespace std; namespace IAEX { - class UpdateLinkVisitor : public Visitor - { + class UpdateLinkVisitor : public Visitor + { - public: - UpdateLinkVisitor(QString oldFilepath, QString newFilepath); - virtual ~UpdateLinkVisitor(); + public: + UpdateLinkVisitor(QString oldFilepath, QString newFilepath); + virtual ~UpdateLinkVisitor(); - virtual void visitCellNodeBefore(Cell *node); - virtual void visitCellNodeAfter(Cell *node); + virtual void visitCellNodeBefore(Cell *node); + virtual void visitCellNodeAfter(Cell *node); - virtual void visitCellGroupNodeBefore(CellGroup *node); - virtual void visitCellGroupNodeAfter(CellGroup *node); + virtual void visitCellGroupNodeBefore(CellGroup *node); + virtual void visitCellGroupNodeAfter(CellGroup *node); - virtual void visitTextCellNodeBefore(TextCell *node); - virtual void visitTextCellNodeAfter(TextCell *node); + virtual void visitTextCellNodeBefore(TextCell *node); + virtual void visitTextCellNodeAfter(TextCell *node); - virtual void visitInputCellNodeBefore(InputCell *node); - virtual void visitInputCellNodeAfter(InputCell *node); + virtual void visitInputCellNodeBefore(InputCell *node); + virtual void visitInputCellNodeAfter(InputCell *node); - virtual void visitGraphCellNodeBefore(GraphCell *node); - virtual void visitGraphCellNodeAfter(GraphCell *node); + virtual void visitGraphCellNodeBefore(GraphCell *node); + virtual void visitGraphCellNodeAfter(GraphCell *node); - virtual void visitCellCursorNodeBefore(CellCursor *cursor); - virtual void visitCellCursorNodeAfter(CellCursor *cursor); + virtual void visitCellCursorNodeBefore(CellCursor *cursor); + virtual void visitCellCursorNodeAfter(CellCursor *cursor); - private: - QDir oldDir_; - QDir newDir_; - }; + private: + QDir oldDir_; + QDir newDir_; + }; } #endif diff --git a/OMNotebook/OMNotebookQT4/visitor.h b/OMNotebook/OMNotebookQT4/visitor.h index d8af57c3804..307f58fb5fd 100644 --- a/OMNotebook/OMNotebookQT4/visitor.h +++ b/OMNotebook/OMNotebookQT4/visitor.h @@ -51,13 +51,13 @@ namespace IAEX{ /*! \interface Visitor * \author Ingemar Axelsson (and Anders Ferström) - * \date 2005-11-30 (update) + * \date 2005-11-30 (update) * * When a new celltype is added to the cellhierarchy a new visitor * member function must be added also. This means that it is expensive * to add new celltypes. * - * 2005-11-30 AF, Removed support for imagecells + * 2005-11-30 AF, Removed support for imagecells */ class Visitor { @@ -74,7 +74,7 @@ namespace IAEX{ virtual void visitInputCellNodeBefore(InputCell *node) = 0; virtual void visitInputCellNodeAfter(InputCell *node) = 0; - virtual void visitGraphCellNodeBefore(GraphCell *node) = 0; + virtual void visitGraphCellNodeBefore(GraphCell *node) = 0; virtual void visitGraphCellNodeAfter(GraphCell *node) = 0; virtual void visitCellCursorNodeBefore(CellCursor *cursor) = 0; diff --git a/OMNotebook/OMNotebookQT4/xmlnodename.h b/OMNotebook/OMNotebookQT4/xmlnodename.h index 97cdcc12c00..eaddfa820cd 100644 --- a/OMNotebook/OMNotebookQT4/xmlnodename.h +++ b/OMNotebook/OMNotebookQT4/xmlnodename.h @@ -40,33 +40,33 @@ */ // notebook -#define XML_NOTEBOOK "Notebook" +#define XML_NOTEBOOK "Notebook" // cell element -#define XML_GROUPCELL "GroupCell" -#define XML_TEXTCELL "TextCell" -#define XML_INPUTCELL "InputCell" -#define XML_GRAPHCELL "GraphCell" +#define XML_GROUPCELL "GroupCell" +#define XML_TEXTCELL "TextCell" +#define XML_INPUTCELL "InputCell" +#define XML_GRAPHCELL "GraphCell" // attribute -#define XML_CLOSED "closed" -#define XML_STYLE "style" -#define XML_NAME "name" +#define XML_CLOSED "closed" +#define XML_STYLE "style" +#define XML_NAME "name" // child -#define XML_TEXT "Text" -#define XML_RULE "Rule" -#define XML_IMAGE "Image" -#define XML_INPUTPART "Input" -#define XML_OUTPUTPART "Output" +#define XML_TEXT "Text" +#define XML_RULE "Rule" +#define XML_IMAGE "Image" +#define XML_INPUTPART "Input" +#define XML_OUTPUTPART "Output" -#define XML_FALSE "false" -#define XML_TRUE "true" +#define XML_FALSE "false" +#define XML_TRUE "true" // Define different read mode -#define READMODE_NORMAL 1 -#define READMODE_OLD 2 -#define READMODE_CONVERTING_ONB 3 +#define READMODE_NORMAL 1 +#define READMODE_OLD 2 +#define READMODE_CONVERTING_ONB 3 #define XML_GRAPHCELL_AREA "Area" #define XML_GRAPHCELL_LEGEND "Legend" @@ -93,7 +93,7 @@ #define XML_GRAPHCELL_MATRIX "Matrix" #define XML_GRAPHCELL_GRID "Grid" #define XML_GRAPHCELL_GRIDAUTOX "AutoX" -#define XML_GRAPHCELL_GRIDAUTOY "AutoY" +#define XML_GRAPHCELL_GRIDAUTOY "AutoY" #define XML_GRAPHCELL_GRIDMAJORX "MajorX" #define XML_GRAPHCELL_GRIDMAJORY "MajorY" #define XML_GRAPHCELL_GRIDMINORX "MinorX" diff --git a/OMNotebook/OMNotebookQT4/xmlparser.cpp b/OMNotebook/OMNotebookQT4/xmlparser.cpp index 4a6587e8c1e..415aa824843 100644 --- a/OMNotebook/OMNotebookQT4/xmlparser.cpp +++ b/OMNotebook/OMNotebookQT4/xmlparser.cpp @@ -79,9 +79,9 @@ namespace IAEX * * \brief Open an XML file and read the content. The xmlparser support * two different read modes: - * READMODE_NORMAL : Read the xml file normaly - * READMODE_OLD : Read the xml file accordantly to the old xml - * format used by OMNotebook. + * READMODE_NORMAL : Read the xml file normaly + * READMODE_OLD : Read the xml file accordantly to the old xml + * format used by OMNotebook. */ @@ -556,7 +556,7 @@ namespace IAEX Cell *graphcell = factory_->createCell( style, parent ); graphcell->setStyle(QString("Input")); - // graphcell->setStyle(style); + // graphcell->setStyle(style); // go through all children in input cell/element @@ -573,15 +573,15 @@ namespace IAEX GraphCell *gCell = dynamic_cast(graphcell); gCell->setText(text); gCell->compoundwidget->gwMain->currentExpr = e.text(); - //fjass gCell->setText( text ); + //fjass gCell->setText( text ); } - /* else if( e.tagName() == XML_OUTPUTPART ) + /* else if( e.tagName() == XML_OUTPUTPART ) { GraphCell *gCell = dynamic_cast(graphcell); gCell->setTextOutput( e.text() ); } - */ else if( e.tagName() == XML_OUTPUTPART ) + */ else if( e.tagName() == XML_OUTPUTPART ) { GraphCell *iCell = dynamic_cast(graphcell); @@ -652,7 +652,7 @@ namespace IAEX LegendLabel *ll = new LegendLabel(color, yVar, gCell->compoundwidget->gwMain->legendFrame, !(interpolation_ == INTERPOLATION_NONE), points, 12); ll->graphWidget = gCell->compoundwidget->gwMain; gCell->compoundwidget->gwMain->legendFrame->setMinimumWidth(max(ll->fontMetrics().width(yVar)+41+4, gCell->compoundwidget->gwMain->legendFrame->minimumWidth())); - // ll->setMaximumHeight(21); + // ll->setMaximumHeight(21); gCell->compoundwidget->gwMain->legendLayout->addWidget(ll); ll->show(); @@ -703,25 +703,25 @@ namespace IAEX gCell->compoundwidget->gwMain->graphicsScene->addItem(gCell->compoundwidget->gwMain->graphicsItems); - // ds >> rect >> pen >> brush; - // gCell->compoundwidget->gwMain->graphicsItems->addToGroup(gCell->compoundwidget->gwMain->graphicsScene->addEllipse(rect, pen, brush)); + // ds >> rect >> pen >> brush; + // gCell->compoundwidget->gwMain->graphicsItems->addToGroup(gCell->compoundwidget->gwMain->graphicsScene->addEllipse(rect, pen, brush)); } else if(type == XML_GRAPHCELL_LINE) { - // ds.setVersion(QDataStream::Qt_3_3); + // ds.setVersion(QDataStream::Qt_3_3); ds >> line_ >> pen; QGraphicsLineItem* r = new QGraphicsLineItem(line_); r->show(); r->setPen(pen); - // r->setBrush(brush); + // r->setBrush(brush); gCell->compoundwidget->gwMain->graphicsItems->addToGroup(r); gCell->compoundwidget->gwMain->graphicsScene->addItem(gCell->compoundwidget->gwMain->graphicsItems); - // gCell->compoundwidget->gwMain->graphicsItems->addToGroup(gCell->compoundwidget->gwMain->graphicsScene->addLine(line_, pen)); + // gCell->compoundwidget->gwMain->graphicsItems->addToGroup(gCell->compoundwidget->gwMain->graphicsScene->addLine(line_, pen)); } b.close(); @@ -741,9 +741,9 @@ namespace IAEX // set style, before set text, so all rules are applied to the style - // graphcell->setStyle(QString("Graph")); + // graphcell->setStyle(QString("Graph")); - // graphcell->setText( text ); //fjass + // graphcell->setText( text ); //fjass GraphCell *gCell = dynamic_cast(graphcell); diff --git a/OMNotebook/OMNotebookQT4/xmlparser.h b/OMNotebook/OMNotebookQT4/xmlparser.h index 2eb0aa3a38a..ea973a6667a 100644 --- a/OMNotebook/OMNotebookQT4/xmlparser.h +++ b/OMNotebook/OMNotebookQT4/xmlparser.h @@ -63,34 +63,34 @@ class QDomNode; namespace IAEX { - class XMLParser : public NBParser - { - public: - XMLParser( const QString filename, Factory *factory, Document *document, int readmode = READMODE_NORMAL ); - virtual ~XMLParser(); - virtual Cell *parse(); + class XMLParser : public NBParser + { + public: + XMLParser( const QString filename, Factory *factory, Document *document, int readmode = READMODE_NORMAL ); + virtual ~XMLParser(); + virtual Cell *parse(); - private: - Cell *parseNormal( QDomDocument &domdoc ); - Cell *parseOld( QDomDocument &domdoc ); + private: + Cell *parseNormal( QDomDocument &domdoc ); + Cell *parseOld( QDomDocument &domdoc ); - // READMODE_NORMAL - void traverseCells( Cell *parent, QDomNode &node ); - void traverseGroupCell( Cell *parent, QDomElement &element ); - void traverseTextCell( Cell *parent, QDomElement &element ); - void traverseInputCell( Cell *parent, QDomElement &element ); - void traverseGraphCell( Cell *parent, QDomElement &element ); - void addImage( Cell *parent, QDomElement &element ); + // READMODE_NORMAL + void traverseCells( Cell *parent, QDomNode &node ); + void traverseGroupCell( Cell *parent, QDomElement &element ); + void traverseTextCell( Cell *parent, QDomElement &element ); + void traverseInputCell( Cell *parent, QDomElement &element ); + void traverseGraphCell( Cell *parent, QDomElement &element ); + void addImage( Cell *parent, QDomElement &element ); - // READMODE_OLD - void xmltraverse( Cell *parent, QDomNode &node ); + // READMODE_OLD + void xmltraverse( Cell *parent, QDomNode &node ); - // variables - QString filename_; - Factory *factory_; - Document *doc_; - int readmode_; - }; + // variables + QString filename_; + Factory *factory_; + Document *doc_; + int readmode_; + }; }; #endif diff --git a/OMNotebook/Pltpkg2/compoundWidget.cpp b/OMNotebook/Pltpkg2/compoundWidget.cpp index 34ccbf77bd6..cdd8d54c7d3 100644 --- a/OMNotebook/Pltpkg2/compoundWidget.cpp +++ b/OMNotebook/Pltpkg2/compoundWidget.cpp @@ -36,107 +36,107 @@ CompoundWidget::CompoundWidget(QWidget* parent): QWidget(parent) { -// this->resize(672, 784); -// this->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); +// this->resize(672, 784); +// this->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); // plotWidget = new QWidget(this); // plotWidget->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); // plotWidget->resize(400, 300); -// plotWidget->setMinimumHeight(784); -// plotWidget->setMinimumWidth(672); +// plotWidget->setMinimumHeight(784); +// plotWidget->setMinimumWidth(672); - setupUi(this); + setupUi(this); - QFont f("Arial",10); - f.setBold(true); - plotTitle->setFont(f); - gwMain->gvBottom = gvBottom; - gwMain->gvLeft = gvLeft; + QFont f("Arial",10); + f.setBold(true); + plotTitle->setFont(f); + gwMain->gvBottom = gvBottom; + gwMain->gvLeft = gvLeft; - gvBottom->setScene(gwMain->graphicsScene->xRulerScene); - gvLeft->setScene(gwMain->graphicsScene->yRulerScene); - gvBottom->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - gvBottom->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - gvLeft->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - gvLeft->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + gvBottom->setScene(gwMain->graphicsScene->xRulerScene); + gvLeft->setScene(gwMain->graphicsScene->yRulerScene); + gvBottom->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + gvBottom->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + gvLeft->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + gvLeft->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - connect(gwMain, SIGNAL(resizeY(quint32)), this, SLOT(resizeY(quint32))); - connect(gwMain, SIGNAL(showPreferences2()), this, SLOT(showPreferences())); + connect(gwMain, SIGNAL(resizeY(quint32)), this, SLOT(resizeY(quint32))); + connect(gwMain, SIGNAL(showPreferences2()), this, SLOT(showPreferences())); - layout = new QVBoxLayout; - legendFrame->setLayout(layout); + layout = new QVBoxLayout; + legendFrame->setLayout(layout); -// legendFrame->setMinimumWidth(50); +// legendFrame->setMinimumWidth(50); - gwMain->legendLayout = layout; - gwMain->legendFrame = legendFrame; + gwMain->legendLayout = layout; + gwMain->legendFrame = legendFrame; - gwMain->compoundwidget = this; + gwMain->compoundwidget = this; //Initialize SoQT //#ifdef HAVE_COIN - // SoQt::init(this); + // SoQt::init(this); //#endif - visWidget = new IAEX::VisualizationWidget(this); - // connect(visWidget, SIGNAL(resizeY(quint32)), this, SLOT(graphicsResizeY(quint32))); - visWidget->hide(); - + visWidget = new IAEX::VisualizationWidget(this); + // connect(visWidget, SIGNAL(resizeY(quint32)), this, SLOT(graphicsResizeY(quint32))); + visWidget->hide(); + } CompoundWidget::~CompoundWidget() { - delete gwMain; - delete gvLeft; - delete gvBottom; - delete xLabel; - delete yLabel; - delete plotTitle; - delete layout; + delete gwMain; + delete gvLeft; + delete gvBottom; + delete xLabel; + delete yLabel; + delete plotTitle; + delete layout; delete visWidget; } void CompoundWidget::showPreferences() { - PreferenceWindow* pw = new PreferenceWindow(this, 0); - pw->setAttribute(Qt::WA_DeleteOnClose); - pw->show(); + PreferenceWindow* pw = new PreferenceWindow(this, 0); + pw->setAttribute(Qt::WA_DeleteOnClose); + pw->show(); } void CompoundWidget::resizeY(quint32 w) { - gvLeft->setMinimumWidth(w+5); - gvLeft->update(); + gvLeft->setMinimumWidth(w+5); + gvLeft->update(); } void CompoundWidget::graphicsResizeY(quint32 w) { - visWidget->setMinimumWidth(w+5); - visWidget->update(); + visWidget->setMinimumWidth(w+5); + visWidget->update(); } void CompoundWidget::showVis() { - visWidget->show(); + visWidget->show(); gwMain->showGrid(false); gwMain->hide(); gvLeft->hide(); gvBottom->hide(); plotTitle->hide(); - // plotWidget->hide(); - xLabel->hide(); - yLabel->hide(); + // plotWidget->hide(); + xLabel->hide(); + yLabel->hide(); legendFrame->hide(); } void CompoundWidget::hideVis() { - visWidget->hide(); - // plotWidget->show(); + visWidget->hide(); + // plotWidget->show(); gwMain->showGrid(true); gwMain->show(); gvLeft->show(); gvBottom->show(); plotTitle->show(); - xLabel->show(); - yLabel->show(); + xLabel->show(); + yLabel->show(); legendFrame->show(); } diff --git a/OMNotebook/Pltpkg2/compoundWidget.h b/OMNotebook/Pltpkg2/compoundWidget.h index e991713e5ac..3a92f078d18 100644 --- a/OMNotebook/Pltpkg2/compoundWidget.h +++ b/OMNotebook/Pltpkg2/compoundWidget.h @@ -47,23 +47,23 @@ using namespace std; class CompoundWidget: public QWidget, public Ui::CompoundWidget { - Q_OBJECT + Q_OBJECT public: - CompoundWidget(QWidget* parent = 0); - ~CompoundWidget(); - void showVis(); - void hideVis(); + CompoundWidget(QWidget* parent = 0); + ~CompoundWidget(); + void showVis(); + void hideVis(); public slots: - void resizeY(quint32 w); - void showPreferences(); + void resizeY(quint32 w); + void showPreferences(); void graphicsResizeY(quint32 w); public: - QVBoxLayout* layout; - IAEX::VisualizationWidget* visWidget; - // QWidget* plotWidget; + QVBoxLayout* layout; + IAEX::VisualizationWidget* visWidget; + // QWidget* plotWidget; }; diff --git a/OMNotebook/Pltpkg2/curve.cpp b/OMNotebook/Pltpkg2/curve.cpp index 1887b333b52..7df5d8d478f 100644 --- a/OMNotebook/Pltpkg2/curve.cpp +++ b/OMNotebook/Pltpkg2/curve.cpp @@ -43,50 +43,50 @@ Curve::Curve(VariableData* x_, VariableData* y_, QColor& color, LegendLabel* ll): x(x_), y(y_), label(ll) { - line = new QGraphicsItemGroup; + line = new QGraphicsItemGroup; setColor(color); } Curve::~Curve() { - delete line; - delete label; + delete line; + delete label; -// foreach(Point* p, dataPoints) -// delete p; - dataPoints.clear(); +// foreach(Point* p, dataPoints) +// delete p; + dataPoints.clear(); } void Curve::showPoints(bool b) { - foreach(Point* p, dataPoints) - p->setVisible(b); + foreach(Point* p, dataPoints) + p->setVisible(b); - drawPoints = b; + drawPoints = b; } void Curve::showLine(bool b) { - line->setVisible(b); - line->update(); - visible = b; + line->setVisible(b); + line->update(); + visible = b; } void Curve::setColor(QColor c) { - color_ = c; - QPen p(c); + color_ = c; + QPen p(c); p.setWidthF(PLOT_LINE_WIDTH); p.setCosmetic(true); - QList l = line->children(); + QList l = line->children(); - for(int i = 0; i < l.size(); ++i) - static_cast(l[i])->setPen(p); + for(int i = 0; i < l.size(); ++i) + static_cast(l[i])->setPen(p); - for(int i = 0; i < dataPoints.size(); ++i) - { - dataPoints[i]->color = c; - dataPoints[i]->setPen(QPen(c)); - } + for(int i = 0; i < dataPoints.size(); ++i) + { + dataPoints[i]->color = c; + dataPoints[i]->setPen(QPen(c)); + } } diff --git a/OMNotebook/Pltpkg2/curve.h b/OMNotebook/Pltpkg2/curve.h index 777daa93290..d935e256615 100644 --- a/OMNotebook/Pltpkg2/curve.h +++ b/OMNotebook/Pltpkg2/curve.h @@ -48,24 +48,24 @@ class Curve { public: - Curve(VariableData* x_, VariableData* y_, QColor& color, LegendLabel* ll); - ~Curve(); + Curve(VariableData* x_, VariableData* y_, QColor& color, LegendLabel* ll); + ~Curve(); public slots: - void showLine(bool b); - void showPoints(bool b); - void setColor(QColor c); + void showLine(bool b); + void showPoints(bool b); + void setColor(QColor c); public: - QGraphicsItemGroup *line; - QList dataPoints; - LegendLabel* label; - bool visible; - bool drawPoints; - int interpolation; - QColor color_; + QGraphicsItemGroup *line; + QList dataPoints; + LegendLabel* label; + bool visible; + bool drawPoints; + int interpolation; + QColor color_; - VariableData* x, *y; + VariableData* x, *y; }; #endif diff --git a/OMNotebook/Pltpkg2/dataSelect.cpp b/OMNotebook/Pltpkg2/dataSelect.cpp index ad168f5e0f5..8e5f00aa769 100644 --- a/OMNotebook/Pltpkg2/dataSelect.cpp +++ b/OMNotebook/Pltpkg2/dataSelect.cpp @@ -44,7 +44,7 @@ using namespace std; DataSelect::DataSelect(QWidget* parent): QDialog(parent) { - setupUi(this); + setupUi(this); } @@ -55,14 +55,14 @@ DataSelect::~DataSelect() bool DataSelect::getVariables(const QStringList& vars, QString& xVar, QString& yVar) { - vData->addItems(vars); - hData->addItems(vars); + vData->addItems(vars); + hData->addItems(vars); - if(exec() == QDialog::Rejected) - return false; + if(exec() == QDialog::Rejected) + return false; - xVar = hData->currentText(); - yVar = vData->currentText(); + xVar = hData->currentText(); + yVar = vData->currentText(); - return true; + return true; } diff --git a/OMNotebook/Pltpkg2/focusRect.h b/OMNotebook/Pltpkg2/focusRect.h index f11a2eed49e..97dac3a5c17 100644 --- a/OMNotebook/Pltpkg2/focusRect.h +++ b/OMNotebook/Pltpkg2/focusRect.h @@ -43,39 +43,39 @@ class FocusRect: public QGraphicsRectItem { public: - FocusRect(const QRectF& rect, GraphWidget* w): QGraphicsRectItem(rect), widget(w) - { - setAcceptsHoverEvents(true); - setZValue(-2); - } - - ~FocusRect() - { - } - - void hoverEnterEvent ( QGraphicsSceneHoverEvent * event ) - { - QColor c(0, 255, 0, 50); - QBrush b(c); - setBrush(b); - } - - void hoverLeaveEvent ( QGraphicsSceneHoverEvent * event ) - { - QColor c(255, 0, 0, 50); - QBrush b(c); - setBrush(b); - } - - void mousePressEvent ( QGraphicsSceneMouseEvent * event ) - { - - - widget->zoomIn(rect()); - widget->updatePointSizes(QRect(-1,0,0,0)); - } - - GraphWidget* widget; + FocusRect(const QRectF& rect, GraphWidget* w): QGraphicsRectItem(rect), widget(w) + { + setAcceptsHoverEvents(true); + setZValue(-2); + } + + ~FocusRect() + { + } + + void hoverEnterEvent ( QGraphicsSceneHoverEvent * event ) + { + QColor c(0, 255, 0, 50); + QBrush b(c); + setBrush(b); + } + + void hoverLeaveEvent ( QGraphicsSceneHoverEvent * event ) + { + QColor c(255, 0, 0, 50); + QBrush b(c); + setBrush(b); + } + + void mousePressEvent ( QGraphicsSceneMouseEvent * event ) + { + + + widget->zoomIn(rect()); + widget->updatePointSizes(QRect(-1,0,0,0)); + } + + GraphWidget* widget; diff --git a/OMNotebook/Pltpkg2/graphScene.h b/OMNotebook/Pltpkg2/graphScene.h index ff5b68ab23c..43aec375fd1 100644 --- a/OMNotebook/Pltpkg2/graphScene.h +++ b/OMNotebook/Pltpkg2/graphScene.h @@ -41,26 +41,26 @@ class GraphScene: public QGraphicsScene { public: - GraphScene(QObject * parent = 0): QGraphicsScene(parent) - { - grid = 0; - gridVisible = false; + GraphScene(QObject * parent = 0): QGraphicsScene(parent) + { + grid = 0; + gridVisible = false; - xRulerScene = new QGraphicsScene(this); - yRulerScene = new QGraphicsScene(this); - this->setSceneRect(0,0,.01,.01); - } + xRulerScene = new QGraphicsScene(this); + yRulerScene = new QGraphicsScene(this); + this->setSceneRect(0,0,.01,.01); + } - ~GraphScene() - { + ~GraphScene() + { - } + } - QGraphicsItemGroup *grid; - QList zoomHistory; - bool gridVisible; + QGraphicsItemGroup *grid; + QList zoomHistory; + bool gridVisible; - QGraphicsScene* xRulerScene, *yRulerScene; + QGraphicsScene* xRulerScene, *yRulerScene; }; diff --git a/OMNotebook/Pltpkg2/graphWidget.cpp b/OMNotebook/Pltpkg2/graphWidget.cpp index f6324f03002..76e5b024123 100644 --- a/OMNotebook/Pltpkg2/graphWidget.cpp +++ b/OMNotebook/Pltpkg2/graphWidget.cpp @@ -169,8 +169,8 @@ GraphWidget::GraphWidget(QWidget* parent): QGraphicsView(parent) */ tmp=contextMenu->addAction("New window"); connect(tmp, SIGNAL(triggered()), this, SLOT(newWindow())); - // tmp->setVisible(false); - // connect(this, SIGNAL(scrolled()), this, SLOT(updateGrid())); + // tmp->setVisible(false); + // connect(this, SIGNAL(scrolled()), this, SLOT(updateGrid())); aaAction = contextMenu->addAction("Antialiasing"); aaAction->setCheckable(true); @@ -328,7 +328,7 @@ void GraphWidget::syncCall() void GraphWidget::originalZoom() { - // this->setMinimumHeight(height() + 50); + // this->setMinimumHeight(height() + 50); } void GraphWidget::addFocusBox() @@ -2027,23 +2027,23 @@ void GraphWidget::receiveDataStream() Line2D* l = new Line2D(x0, y0, x1, y1,color, PLOT_LINE_WIDTH, true); temporaryCurves[currentYVar]->line->addToGroup(l); l->show(); - graphicsScene->addItem(l); + graphicsScene->addItem(l); } else if(temporaryCurves[currentYVar]->interpolation == INTERPOLATION_CONSTANT) { Line2D* l = new Line2D(x0, y0,x1,y0,color, PLOT_LINE_WIDTH, true); - l->setVisible(true); - graphicsScene->addItem(l); + l->setVisible(true); + graphicsScene->addItem(l); temporaryCurves[currentYVar]->line->addToGroup(l); l = new Line2D(x1, y0,x1,y1,color, PLOT_LINE_WIDTH, true); - l->setVisible(true); - graphicsScene->addItem(l); + l->setVisible(true); + graphicsScene->addItem(l); temporaryCurves[currentYVar]->line->addToGroup(l); } else if(temporaryCurves[currentYVar]->interpolation == INTERPOLATION_NONE) { Line2D* l = new Line2D(x0, y0, x1, y1,color, PLOT_LINE_WIDTH, true); - graphicsScene->addItem(l); + graphicsScene->addItem(l); l->setVisible(true); temporaryCurves[currentYVar]->line->addToGroup(l); } @@ -2063,12 +2063,12 @@ void GraphWidget::receiveDataStream() packetSize = 0; ++it; - graphicsScene->setSceneRect(graphicsScene->itemsBoundingRect()); + graphicsScene->setSceneRect(graphicsScene->itemsBoundingRect()); range = graphicsScene->sceneRect(); setArea(graphicsScene->sceneRect()); - legendFrame->update(); + legendFrame->update(); graphicsScene->update(); - update(); + update(); } while(activeSocket->bytesAvailable() >= sizeof(quint32)); @@ -2087,14 +2087,14 @@ void GraphWidget::dataStreamClosed() // cerr << "tempCurves size: " << temporaryCurves.size() << endl; for(map::iterator i = temporaryCurves.begin(); i != temporaryCurves.end(); ++i) { - curves.append(i->second); - graphicsScene->addItem(i->second->line); + curves.append(i->second); + graphicsScene->addItem(i->second->line); } // cerr << "variables size: " << variables.size() << endl; // clear the variable data! variableData.clear(); for(map::iterator i = variables.begin(); i != variables.end(); ++i) - variableData.append(i->second); + variableData.append(i->second); bool b = graphicsScene->gridVisible; @@ -2102,13 +2102,13 @@ void GraphWidget::dataStreamClosed() if(range.width() == 0) { - range.setLeft(graphicsScene->itemsBoundingRect().left()); - range.setWidth(graphicsScene->itemsBoundingRect().width()); + range.setLeft(graphicsScene->itemsBoundingRect().left()); + range.setWidth(graphicsScene->itemsBoundingRect().width()); } if(range.height() == 0) { - range.setTop(graphicsScene->itemsBoundingRect().top()); - range.setHeight(graphicsScene->itemsBoundingRect().height()); + range.setTop(graphicsScene->itemsBoundingRect().top()); + range.setHeight(graphicsScene->itemsBoundingRect().height()); } setArea(range); @@ -2119,11 +2119,11 @@ void GraphWidget::dataStreamClosed() /* void GraphWidget::saveImage() { -// this->setBackgroundBrush(QBrush(Qt::white)); +// this->setBackgroundBrush(QBrush(Qt::white)); -// graphicsScene->setBackgroundBrush(QBrush(Qt::white)); +// graphicsScene->setBackgroundBrush(QBrush(Qt::white)); -// graphicsScene->setForegroundBrush(QBrush(Qt::red)); +// graphicsScene->setForegroundBrush(QBrush(Qt::red)); QGraphicsRectItem* r = new QGraphicsRectItem(mapToScene(rect()).boundingRect()); QBrush b(Qt::white); @@ -2131,13 +2131,13 @@ r->setBrush(b); r->setZValue(-100); graphicsScene->addItem(r); -// QImage qi(rect().size(),QImage::Format_RGB32); +// QImage qi(rect().size(),QImage::Format_RGB32); QImage qi(rect().size().width()/2, rect().size().height(),QImage::Format_RGB32); QPainter qp; -// qp.setBackground(QBrush(Qt::white)); +// qp.setBackground(QBrush(Qt::white)); -// qp.setBackgroundMode( Qt::OpaqueMode); +// qp.setBackgroundMode( Qt::OpaqueMode); @@ -2150,7 +2150,7 @@ qp.begin(&qi); render(&qp); qp.end(); -// qi.save("u2.png", "PNG"); +// qi.save("u2.png", "PNG"); QByteArray ba; QBuffer buffer(&ba); @@ -2170,79 +2170,79 @@ delete r; void GraphWidget::saveImage() { - QString filename = QFileDialog::getSaveFileName(this, "Export image", "untitled", "Portable Network Graphics (*.png);;Windows Bitmap (*.bmp);;Joint Photographic Experts Group (*.jpg)"); + QString filename = QFileDialog::getSaveFileName(this, "Export image", "untitled", "Portable Network Graphics (*.png);;Windows Bitmap (*.bmp);;Joint Photographic Experts Group (*.jpg)"); - if(!filename.size()) - return; + if(!filename.size()) + return; - QImage i3(compoundwidget->rect().size(), QImage::Format_RGB32); + QImage i3(compoundwidget->rect().size(), QImage::Format_RGB32); - i3.fill(QColor(Qt::white).rgb()); - QPainter p(&i3); - QRectF target = QRectF(compoundwidget->gwMain->rect()); - target.moveTo(compoundwidget->gwMain->pos()); - compoundwidget->gwMain->render(&p, target); + i3.fill(QColor(Qt::white).rgb()); + QPainter p(&i3); + QRectF target = QRectF(compoundwidget->gwMain->rect()); + target.moveTo(compoundwidget->gwMain->pos()); + compoundwidget->gwMain->render(&p, target); - p.drawRect(target); + p.drawRect(target); - target = QRectF(compoundwidget->gvLeft->rect()); - target.moveTo(compoundwidget->gvLeft->pos()); - compoundwidget->gvLeft->render(&p, target); + target = QRectF(compoundwidget->gvLeft->rect()); + target.moveTo(compoundwidget->gvLeft->pos()); + compoundwidget->gvLeft->render(&p, target); - target = QRectF(compoundwidget->gvBottom->rect()); - target.moveTo(compoundwidget->gvBottom->pos()); - compoundwidget->gvBottom->render(&p, target); + target = QRectF(compoundwidget->gvBottom->rect()); + target.moveTo(compoundwidget->gvBottom->pos()); + compoundwidget->gvBottom->render(&p, target); - compoundwidget->yLabel->render(&p, compoundwidget->yLabel->pos()); - compoundwidget->xLabel->render(&p, compoundwidget->xLabel->pos()); - compoundwidget->plotTitle->render(&p, compoundwidget->plotTitle->pos()); + compoundwidget->yLabel->render(&p, compoundwidget->yLabel->pos()); + compoundwidget->xLabel->render(&p, compoundwidget->xLabel->pos()); + compoundwidget->plotTitle->render(&p, compoundwidget->plotTitle->pos()); - QList l = compoundwidget->legendFrame->findChildren(); - for(int i = 0; i < l.size(); ++i) - l[i]->render(&p, l[i]->pos()+compoundwidget->legendFrame->pos()); + QList l = compoundwidget->legendFrame->findChildren(); + for(int i = 0; i < l.size(); ++i) + l[i]->render(&p, l[i]->pos()+compoundwidget->legendFrame->pos()); - if(filename.endsWith("png")) - i3.save(filename, "PNG"); - else if(filename.endsWith("bmp")) - i3.save(filename, "BMP"); - else if(filename.endsWith("jpg") || filename.endsWith("jpeg")) - i3.save(filename, "JPG"); - else - i3.save(filename+".bmp", "BMP"); + if(filename.endsWith("png")) + i3.save(filename, "PNG"); + else if(filename.endsWith("bmp")) + i3.save(filename, "BMP"); + else if(filename.endsWith("jpg") || filename.endsWith("jpeg")) + i3.save(filename, "JPG"); + else + i3.save(filename+".bmp", "BMP"); } void GraphWidget::exportToClipboard() { - QImage i3(compoundwidget->rect().size(), QImage::Format_RGB32); + QImage i3(compoundwidget->rect().size(), QImage::Format_RGB32); - i3.fill(QColor(Qt::white).rgb()); - QPainter p(&i3); - QRectF target = QRectF(compoundwidget->gwMain->rect()); - target.moveTo(compoundwidget->gwMain->pos()); - compoundwidget->gwMain->render(&p, target); + i3.fill(QColor(Qt::white).rgb()); + QPainter p(&i3); + QRectF target = QRectF(compoundwidget->gwMain->rect()); + target.moveTo(compoundwidget->gwMain->pos()); + compoundwidget->gwMain->render(&p, target); - p.drawRect(target); + p.drawRect(target); - target = QRectF(compoundwidget->gvLeft->rect()); - target.moveTo(compoundwidget->gvLeft->pos()); - compoundwidget->gvLeft->render(&p, target); + target = QRectF(compoundwidget->gvLeft->rect()); + target.moveTo(compoundwidget->gvLeft->pos()); + compoundwidget->gvLeft->render(&p, target); - target = QRectF(compoundwidget->gvBottom->rect()); - target.moveTo(compoundwidget->gvBottom->pos()); - compoundwidget->gvBottom->render(&p, target); + target = QRectF(compoundwidget->gvBottom->rect()); + target.moveTo(compoundwidget->gvBottom->pos()); + compoundwidget->gvBottom->render(&p, target); - compoundwidget->yLabel->render(&p, compoundwidget->yLabel->pos()); - compoundwidget->xLabel->render(&p, compoundwidget->xLabel->pos()); - compoundwidget->plotTitle->render(&p, compoundwidget->plotTitle->pos()); + compoundwidget->yLabel->render(&p, compoundwidget->yLabel->pos()); + compoundwidget->xLabel->render(&p, compoundwidget->xLabel->pos()); + compoundwidget->plotTitle->render(&p, compoundwidget->plotTitle->pos()); - QList l = compoundwidget->legendFrame->findChildren(); - for(int i = 0; i < l.size(); ++i) - l[i]->render(&p, l[i]->pos()+compoundwidget->legendFrame->pos()); + QList l = compoundwidget->legendFrame->findChildren(); + for(int i = 0; i < l.size(); ++i) + l[i]->render(&p, l[i]->pos()+compoundwidget->legendFrame->pos()); QClipboard *clipboard = QApplication::clipboard(); clipboard->setImage(i3, QClipboard::Clipboard); diff --git a/OMNotebook/Pltpkg2/graphWidget.h b/OMNotebook/Pltpkg2/graphWidget.h index 594512dc997..e07088ebe1a 100644 --- a/OMNotebook/Pltpkg2/graphWidget.h +++ b/OMNotebook/Pltpkg2/graphWidget.h @@ -61,224 +61,224 @@ class CompoundWidget; class GraphWidget: public QGraphicsView { - Q_OBJECT + Q_OBJECT public: - GraphWidget(QWidget* parent = 0); - ~GraphWidget(); + GraphWidget(QWidget* parent = 0); + ~GraphWidget(); - // void printData(QString data); - // void printData2(qreal x0, qreal y0, qreal x1, qreal y1); + // void printData(QString data); + // void printData2(qreal x0, qreal y0, qreal x1, qreal y1); - quint16 serverPort() {return server->serverPort();} + quint16 serverPort() {return server->serverPort();} public slots: - void getData(); - void acCon(); - void drawGraphics(); - void drawLine(QDataStream& ds); - void drawPoint(QDataStream& ds); - void drawText(QDataStream& ds); - void drawRect(QDataStream& ds); - void drawEllipse(QDataStream& ds); - void readPtolemyDataStream(); - void ptolemyDataStreamClosed(); - void plotPtolemyDataStream(); - void dataStreamClosed(); - void graphicsStreamClosed(); - void receiveDataStream(); - - void setLogarithmic(bool); - void setServerState(bool listen, bool graphics = false); - void setStretch(bool b) {stretch = b;} - - void newWindow(); - void zoomIn(QRectF); + void getData(); + void acCon(); + void drawGraphics(); + void drawLine(QDataStream& ds); + void drawPoint(QDataStream& ds); + void drawText(QDataStream& ds); + void drawRect(QDataStream& ds); + void drawEllipse(QDataStream& ds); + void readPtolemyDataStream(); + void ptolemyDataStreamClosed(); + void plotPtolemyDataStream(); + void dataStreamClosed(); + void graphicsStreamClosed(); + void receiveDataStream(); + + void setLogarithmic(bool); + void setServerState(bool listen, bool graphics = false); + void setStretch(bool b) {stretch = b;} + + void newWindow(); + void zoomIn(QRectF); void saveImage(); void exportToClipboard(); - void setExpr(QString); - - void setPan(bool b) - { - pan = b; - if(b) - { - zoom = false; - select=false; - setDragMode(QGraphicsView::ScrollHandDrag); - } - } - - void setSelect(bool b) - { - select = b; - if(b) - { - zoom = false; - pan = false; - setDragMode(QGraphicsView::RubberBandDrag); - setDragMode(QGraphicsView::NoDrag); - } - } - - void setZoom(bool b) - { - zoom = b; - if(b) - { - select = false; - pan = false; - setDragMode(QGraphicsView::RubberBandDrag); - } - } - - void resetZoom(); - - void clear(); - - void showGrid(bool); - void updateGrid(); - - void setArea(const QRectF& r); - void showPreferences(); - void showVariables(); - void setAntiAliasing(bool); - void setHold(bool); - void setHold(QDataStream& ds); - - void originalZoom(); - void addFocusBox(); - void syncCall(); - void enableServers(bool); + void setExpr(QString); + + void setPan(bool b) + { + pan = b; + if(b) + { + zoom = false; + select=false; + setDragMode(QGraphicsView::ScrollHandDrag); + } + } + + void setSelect(bool b) + { + select = b; + if(b) + { + zoom = false; + pan = false; + setDragMode(QGraphicsView::RubberBandDrag); + setDragMode(QGraphicsView::NoDrag); + } + } + + void setZoom(bool b) + { + zoom = b; + if(b) + { + select = false; + pan = false; + setDragMode(QGraphicsView::RubberBandDrag); + } + } + + void resetZoom(); + + void clear(); + + void showGrid(bool); + void updateGrid(); + + void setArea(const QRectF& r); + void showPreferences(); + void showVariables(); + void setAntiAliasing(bool); + void setHold(bool); + void setHold(QDataStream& ds); + + void originalZoom(); + void addFocusBox(); + void syncCall(); + void enableServers(bool); signals: - void showPreferences2(); - void serverState(bool); - void newMessage(QString message); - void resizeY(quint32); - void zoomEvent(QRectF); - void scrolled(); - void scrollBy(int x, int y); - void areaChanged(const QRectF& r); - void setGridVisible(bool); - void holdSet(bool); - void newExpr(QString); - void showGraphics(); - void showVariableButton(bool); -// void serverState(bool); + void showPreferences2(); + void serverState(bool); + void newMessage(QString message); + void resizeY(quint32); + void zoomEvent(QRectF); + void scrolled(); + void scrollBy(int x, int y); + void areaChanged(const QRectF& r); + void setGridVisible(bool); + void holdSet(bool); + void newExpr(QString); + void showGraphics(); + void showVariableButton(bool); +// void serverState(bool); public: - GraphScene* graphicsScene; + GraphScene* graphicsScene; protected: - void resizeEvent ( QResizeEvent * event ); - void mouseReleaseEvent ( QMouseEvent * event ); - void mousePressEvent ( QMouseEvent * event ); + void resizeEvent ( QResizeEvent * event ); + void mouseReleaseEvent ( QMouseEvent * event ); + void mousePressEvent ( QMouseEvent * event ); - void paintEvent(QPaintEvent* pe); + void paintEvent(QPaintEvent* pe); - void showEvent(QShowEvent* event); - quint32 blockSize; + void showEvent(QShowEvent* event); + quint32 blockSize; - QTcpServer* server, *graphicsServer; - QTcpSocket* activeSocket, *graphicsSocket; - QDataStream ds, ds2; + QTcpServer* server, *graphicsServer; + QTcpSocket* activeSocket, *graphicsSocket; + QDataStream ds, ds2; - int tmpint; + int tmpint; - int nr; - bool getNames; - quint32 variableCount; - quint32 packetSize, packetSize2; + int nr; + bool getNames; + quint32 variableCount; + quint32 packetSize, packetSize2; - void createGrid(bool numbersOnly = false); - qreal gridDist(qreal &min, qreal &max, qreal dist = -1); + void createGrid(bool numbersOnly = false); + qreal gridDist(qreal &min, qreal &max, qreal dist = -1); public: - bool getServerState(); - map variables; - map temporaryCurves; + bool getServerState(); + map variables; + map temporaryCurves; - void updatePointSizes(QRect r = QRect()); + void updatePointSizes(QRect r = QRect()); - QRectF currentArea() - { - return currentArea_; - } + QRectF currentArea() + { + return currentArea_; + } - void setCurrentArea(const QRectF& r) - { - currentArea_ = r; - } + void setCurrentArea(const QRectF& r) + { + currentArea_ = r; + } private: - void drawRulers(); - void updateScaleFactors() - { - QPolygonF p = mapToScene(QRect(0,0,10,10)); - xScaleFactor = p.boundingRect().width()/10; - yScaleFactor = p.boundingRect().height()/10; + void drawRulers(); + void updateScaleFactors() + { + QPolygonF p = mapToScene(QRect(0,0,10,10)); + xScaleFactor = p.boundingRect().width()/10; + yScaleFactor = p.boundingRect().height()/10; - } + } - void rescale() - { + void rescale() + { - } + } - bool stretch; - bool hold; - bool zoom; - bool pan; - bool select; - double xScaleFactor, yScaleFactor; + bool stretch; + bool hold; + bool zoom; + bool pan; + bool select; + double xScaleFactor, yScaleFactor; - QList *dataPoints; - QColor generateColor(int index); - QPoint zoomStart; - QMenu* contextMenu; + QList *dataPoints; + QColor generateColor(int index); + QPoint zoomStart; + QMenu* contextMenu; - QRectF currentArea_; - QString zoomStr, gridStr, aAStr; - QRectF range; - double dataStreamVersion; + QRectF currentArea_; + QString zoomStr, gridStr, aAStr; + QRectF range; + double dataStreamVersion; public: - QString currentExpr; + QString currentExpr; - QRectF originalArea; + QRectF originalArea; - QGraphicsItemGroup *graphicsItems; + QGraphicsItemGroup *graphicsItems; - QList variableData; + QList variableData; - QList curves; - bool xLog, yLog; + QList curves; + bool xLog, yLog; - QRectF gridArea; - QRectF manualArea; - bool useManualArea; - bool gridVisible; + QRectF gridArea; + QRectF manualArea; + bool useManualArea; + bool gridVisible; public: - bool antiAliasing; - QString currentXVar, currentYVar; - QStringList yVars; - QGraphicsView *gvLeft, *gvBottom; - QVBoxLayout* legendLayout; - QFrame* legendFrame; - - CompoundWidget* compoundwidget; - - qreal xMajorDist, xMinorDist, yMajorDist, yMinorDist; //grid parameters - bool fixedYSize, fixedXSize; - bool fixedGrid; - - bool doFitInView, doSetArea; - QRectF newRect; - QAction* aaAction; + bool antiAliasing; + QString currentXVar, currentYVar; + QStringList yVars; + QGraphicsView *gvLeft, *gvBottom; + QVBoxLayout* legendLayout; + QFrame* legendFrame; + + CompoundWidget* compoundwidget; + + qreal xMajorDist, xMinorDist, yMajorDist, yMinorDist; //grid parameters + bool fixedYSize, fixedXSize; + bool fixedGrid; + + bool doFitInView, doSetArea; + QRectF newRect; + QAction* aaAction; }; #endif diff --git a/OMNotebook/Pltpkg2/graphWindow.cpp b/OMNotebook/Pltpkg2/graphWindow.cpp index 8a698c83004..e92510e6bbe 100644 --- a/OMNotebook/Pltpkg2/graphWindow.cpp +++ b/OMNotebook/Pltpkg2/graphWindow.cpp @@ -89,22 +89,22 @@ GraphWindow::~GraphWindow() void GraphWindow::showPreferences() { - PreferenceWindow* pw = new PreferenceWindow(compoundWidget, 0); - pw->setAttribute(Qt::WA_DeleteOnClose); - pw->show(); + PreferenceWindow* pw = new PreferenceWindow(compoundWidget, 0); + pw->setAttribute(Qt::WA_DeleteOnClose); + pw->show(); } void GraphWindow::showSimulationData() { - VariableWindow* vw = new VariableWindow(compoundWidget->gwMain, 0); - vw->setAttribute(Qt::WA_DeleteOnClose); - vw->show(); + VariableWindow* vw = new VariableWindow(compoundWidget->gwMain, 0); + vw->setAttribute(Qt::WA_DeleteOnClose); + vw->show(); } void GraphWindow::showMessage(QString message) { - statusbar->showMessage(message); + statusbar->showMessage(message); } void GraphWindow::sceneDestroyed() @@ -115,44 +115,44 @@ void GraphWindow::sceneDestroyed() void GraphWindow::saveImage() { - QString filename = QFileDialog::getSaveFileName(this, "Export image", "untitled", "Portable Network Graphics (*.png);;Windows Bitmap (*.bmp);;Joint Photographic Experts Group (*.jpg)"); + QString filename = QFileDialog::getSaveFileName(this, "Export image", "untitled", "Portable Network Graphics (*.png);;Windows Bitmap (*.bmp);;Joint Photographic Experts Group (*.jpg)"); - if(!filename.size()) - return; + if(!filename.size()) + return; - QImage i3(compoundWidget->rect().size(), QImage::Format_RGB32); - i3.fill(QColor(Qt::white).rgb()); - QPainter p(&i3); - QRectF target = QRectF(compoundWidget->gwMain->rect()); - target.moveTo(compoundWidget->gwMain->pos()); - compoundWidget->gwMain->render(&p, target); + QImage i3(compoundWidget->rect().size(), QImage::Format_RGB32); + i3.fill(QColor(Qt::white).rgb()); + QPainter p(&i3); + QRectF target = QRectF(compoundWidget->gwMain->rect()); + target.moveTo(compoundWidget->gwMain->pos()); + compoundWidget->gwMain->render(&p, target); - p.drawRect(target); + p.drawRect(target); - target = QRectF(compoundWidget->gvLeft->rect()); - target.moveTo(compoundWidget->gvLeft->pos()); - compoundWidget->gvLeft->render(&p, target); + target = QRectF(compoundWidget->gvLeft->rect()); + target.moveTo(compoundWidget->gvLeft->pos()); + compoundWidget->gvLeft->render(&p, target); - target = QRectF(compoundWidget->gvBottom->rect()); - target.moveTo(compoundWidget->gvBottom->pos()); - compoundWidget->gvBottom->render(&p, target); + target = QRectF(compoundWidget->gvBottom->rect()); + target.moveTo(compoundWidget->gvBottom->pos()); + compoundWidget->gvBottom->render(&p, target); - compoundWidget->yLabel->render(&p, compoundWidget->yLabel->pos()); - compoundWidget->xLabel->render(&p, compoundWidget->xLabel->pos()); - compoundWidget->plotTitle->render(&p, compoundWidget->plotTitle->pos()); + compoundWidget->yLabel->render(&p, compoundWidget->yLabel->pos()); + compoundWidget->xLabel->render(&p, compoundWidget->xLabel->pos()); + compoundWidget->plotTitle->render(&p, compoundWidget->plotTitle->pos()); - QList l = compoundWidget->legendFrame->findChildren(); - for(int i = 0; i < l.size(); ++i) - l[i]->render(&p, l[i]->pos()+compoundWidget->legendFrame->pos()); + QList l = compoundWidget->legendFrame->findChildren(); + for(int i = 0; i < l.size(); ++i) + l[i]->render(&p, l[i]->pos()+compoundWidget->legendFrame->pos()); - if(filename.endsWith("png")) - i3.save(filename, "PNG"); - else if(filename.endsWith("bmp")) - i3.save(filename, "BMP"); - else if(filename.endsWith("jpg") || filename.endsWith("jpeg")) - i3.save(filename, "JPG"); - else - i3.save(filename+".bmp", "BMP"); + if(filename.endsWith("png")) + i3.save(filename, "PNG"); + else if(filename.endsWith("bmp")) + i3.save(filename, "BMP"); + else if(filename.endsWith("jpg") || filename.endsWith("jpeg")) + i3.save(filename, "JPG"); + else + i3.save(filename+".bmp", "BMP"); } diff --git a/OMNotebook/Pltpkg2/graphWindow.h b/OMNotebook/Pltpkg2/graphWindow.h index 3e2c9eb5f59..55554c7a88b 100644 --- a/OMNotebook/Pltpkg2/graphWindow.h +++ b/OMNotebook/Pltpkg2/graphWindow.h @@ -41,25 +41,25 @@ class GraphWindow: public QMainWindow, public Ui::graphWindow { - Q_OBJECT + Q_OBJECT public: - GraphWindow(QWidget* parent = 0); - ~GraphWindow(); - int serverPort() {return graphicsView->gwMain->serverPort();} + GraphWindow(QWidget* parent = 0); + ~GraphWindow(); + int serverPort() {return graphicsView->gwMain->serverPort();} signals: - void destroyed2(); + void destroyed2(); public slots: - void showMessage(QString message); - void sceneDestroyed(); - void showPreferences(); - void showSimulationData(); - void saveImage(); + void showMessage(QString message); + void sceneDestroyed(); + void showPreferences(); + void showSimulationData(); + void saveImage(); public: - CompoundWidget* compoundWidget; + CompoundWidget* compoundWidget; }; diff --git a/OMNotebook/Pltpkg2/label.h b/OMNotebook/Pltpkg2/label.h index 59de0377c68..113c4e546fd 100644 --- a/OMNotebook/Pltpkg2/label.h +++ b/OMNotebook/Pltpkg2/label.h @@ -43,38 +43,38 @@ using namespace std; class Label: public QLabel { public: - Label(QWidget * parent = 0, Qt::WindowFlags f = 0 ): QLabel(parent, f) - { + Label(QWidget * parent = 0, Qt::WindowFlags f = 0 ): QLabel(parent, f) + { - } - Label(const QString & text, QWidget * parent = 0, Qt::WindowFlags f = 0): QLabel(text, parent,f) - { + } + Label(const QString & text, QWidget * parent = 0, Qt::WindowFlags f = 0): QLabel(text, parent,f) + { - } - ~Label() - { + } + ~Label() + { - } + } protected: - void paintEvent ( QPaintEvent * event ) - { - QPainter painter(this); - render(&painter); - } + void paintEvent ( QPaintEvent * event ) + { + QPainter painter(this); + render(&painter); + } public: - void render(QPainter* painter, QPointF pos = QPointF()) - { - painter->save(); - painter->translate(pos.x(), pos.y()); + void render(QPainter* painter, QPointF pos = QPointF()) + { + painter->save(); + painter->translate(pos.x(), pos.y()); - painter->setFont(font()); - painter->drawText(rect(), Qt::AlignCenter, text()); + painter->setFont(font()); + painter->drawText(rect(), Qt::AlignCenter, text()); - painter->restore(); - } + painter->restore(); + } }; #endif diff --git a/OMNotebook/Pltpkg2/legendLabel.cpp b/OMNotebook/Pltpkg2/legendLabel.cpp index fd2c522c547..af625eadd52 100644 --- a/OMNotebook/Pltpkg2/legendLabel.cpp +++ b/OMNotebook/Pltpkg2/legendLabel.cpp @@ -40,38 +40,38 @@ LegendLabel::LegendLabel(QColor color_, QString s, QWidget* parent, bool showline, bool showpoints, int maxHeight): QLabel(s, parent), color(color_) { - curve = 0; - state = true; - setContextMenuPolicy(Qt::ActionsContextMenu); - QAction* tmp; - tmp = new QAction(QString("Show line"), this); - tmp->setCheckable(true); - tmp->setChecked(showline); - connect(tmp, SIGNAL(toggled(bool)), this, SLOT(setLineVisible(bool))); - connect(this, SIGNAL(showLine(bool)), tmp, SLOT(setChecked(bool))); - addAction(tmp); + curve = 0; + state = true; + setContextMenuPolicy(Qt::ActionsContextMenu); + QAction* tmp; + tmp = new QAction(QString("Show line"), this); + tmp->setCheckable(true); + tmp->setChecked(showline); + connect(tmp, SIGNAL(toggled(bool)), this, SLOT(setLineVisible(bool))); + connect(this, SIGNAL(showLine(bool)), tmp, SLOT(setChecked(bool))); + addAction(tmp); - tmp = new QAction("Show data points", this); - tmp->setCheckable(true); - tmp->setChecked(showpoints); - connect(tmp, SIGNAL(toggled(bool)), this, SLOT(setPointsVisible(bool))); - connect(this, SIGNAL(showPoints(bool)), tmp, SLOT(setChecked(bool))); - addAction(tmp); + tmp = new QAction("Show data points", this); + tmp->setCheckable(true); + tmp->setChecked(showpoints); + connect(tmp, SIGNAL(toggled(bool)), this, SLOT(setPointsVisible(bool))); + connect(this, SIGNAL(showPoints(bool)), tmp, SLOT(setChecked(bool))); + addAction(tmp); - tmp = new QAction("Change color...", this); - connect(tmp, SIGNAL(triggered()), this, SLOT(selectColor())); - addAction(tmp); - tmp = new QAction(this); - tmp->setSeparator(true); - addAction(tmp); - tmp = new QAction("Delete", this); - connect(tmp, SIGNAL(triggered()), this, SLOT(deleteCurve())); - addAction(tmp); + tmp = new QAction("Change color...", this); + connect(tmp, SIGNAL(triggered()), this, SLOT(selectColor())); + addAction(tmp); + tmp = new QAction(this); + tmp->setSeparator(true); + addAction(tmp); + tmp = new QAction("Delete", this); + connect(tmp, SIGNAL(triggered()), this, SLOT(deleteCurve())); + addAction(tmp); - setMaximumHeight(maxHeight); + setMaximumHeight(maxHeight); - setMinimumWidth((fontMetrics().width(text())+height()+4)); + setMinimumWidth((fontMetrics().width(text())+height()+4)); @@ -86,86 +86,86 @@ LegendLabel::~LegendLabel() void LegendLabel::deleteCurve() { - int t = graphWidget->curves.indexOf(curve); - if(t != -1) - graphWidget->curves.removeAt(t); - qDeleteAll(curve->dataPoints); + int t = graphWidget->curves.indexOf(curve); + if(t != -1) + graphWidget->curves.removeAt(t); + qDeleteAll(curve->dataPoints); - delete curve; -// delete menu; - // deleteLater(); + delete curve; +// delete menu; + // deleteLater(); } void LegendLabel::selectColor() { - QColor c = QColorDialog::getColor(color); - if(c.isValid()) - { - color = c; - curve->setColor(color); - } + QColor c = QColorDialog::getColor(color); + if(c.isValid()) + { + color = c; + curve->setColor(color); + } } void LegendLabel::setLineVisible(bool b) { - curve->showLine(b); + curve->showLine(b); - curve->dataPoints[0]->scene()->update(); - emit showLine(b); + curve->dataPoints[0]->scene()->update(); + emit showLine(b); } void LegendLabel::setPointsVisible(bool b) { - curve->showPoints(b); - if(b) - graphWidget->updatePointSizes(); + curve->showPoints(b); + if(b) + graphWidget->updatePointSizes(); - curve->dataPoints[0]->scene()->update(); - emit showPoints(b); + curve->dataPoints[0]->scene()->update(); + emit showPoints(b); } /* void LegendLabel::showEvent(QShowEvent* event) { - QLabel::showEvent(event); + QLabel::showEvent(event); - graphWidget->originalZoom(); + graphWidget->originalZoom(); } */ void LegendLabel::paintEvent ( QPaintEvent * event ) { - QPainter painter(this); + QPainter painter(this); - render(&painter); + render(&painter); -// graphWidget->originalZoom(); +// graphWidget->originalZoom(); } void LegendLabel::render(QPainter* painter, QPointF pos) { - painter->save(); - painter->translate(pos.x(), pos.y()); - - painter->setPen(Qt::black); - QBrush b; - if(state) - b = QBrush(color); - - painter->setBrush(b); - painter->setRenderHints(QPainter::Antialiasing); - painter->drawEllipse(1, 1, max(0,height()-2), max(0,height()-2)); - - painter->setFont(font()); -// setMinimumWidth(fontMetrics().width(text())+height()+4); - //setMinimumWidth(50); - QRectF r = rect(); - r.setLeft(r.left() + height()+2); - painter->drawText(r, Qt::AlignVCenter, text()); - - painter->restore(); + painter->save(); + painter->translate(pos.x(), pos.y()); + + painter->setPen(Qt::black); + QBrush b; + if(state) + b = QBrush(color); + + painter->setBrush(b); + painter->setRenderHints(QPainter::Antialiasing); + painter->drawEllipse(1, 1, max(0,height()-2), max(0,height()-2)); + + painter->setFont(font()); +// setMinimumWidth(fontMetrics().width(text())+height()+4); + //setMinimumWidth(50); + QRectF r = rect(); + r.setLeft(r.left() + height()+2); + painter->drawText(r, Qt::AlignVCenter, text()); + + painter->restore(); } diff --git a/OMNotebook/Pltpkg2/legendLabel.h b/OMNotebook/Pltpkg2/legendLabel.h index 5f956ef5111..618116a751a 100644 --- a/OMNotebook/Pltpkg2/legendLabel.h +++ b/OMNotebook/Pltpkg2/legendLabel.h @@ -50,45 +50,45 @@ using namespace std; class LegendLabel: public QLabel { - Q_OBJECT + Q_OBJECT public: - LegendLabel(QColor color_, QString s, QWidget* parent, bool showline, bool showpoints, int maxHeight); - ~LegendLabel(); + LegendLabel(QColor color_, QString s, QWidget* parent, bool showline, bool showpoints, int maxHeight); + ~LegendLabel(); - void setCurve(Curve* c) - { - curve = c; - } + void setCurve(Curve* c) + { + curve = c; + } signals: - void showLine(bool); - void showPoints(bool); + void showLine(bool); + void showPoints(bool); public slots: - void setLineVisible(bool b); - void setPointsVisible(bool b); - void selectColor(); - void deleteCurve(); + void setLineVisible(bool b); + void setPointsVisible(bool b); + void selectColor(); + void deleteCurve(); protected: - void paintEvent ( QPaintEvent * event ); + void paintEvent ( QPaintEvent * event ); - void resizeEvent ( QResizeEvent * event ) - { - setIndent(height() +2); - } + void resizeEvent ( QResizeEvent * event ) + { + setIndent(height() +2); + } -// void showEvent(QShowEvent*); +// void showEvent(QShowEvent*); public: - void render(QPainter* painter, QPointF pos = QPointF()); - GraphWidget* graphWidget; + void render(QPainter* painter, QPointF pos = QPointF()); + GraphWidget* graphWidget; private: - QColor color; - QMenu *menu; - Curve* curve; - bool state; + QColor color; + QMenu *menu; + Curve* curve; + bool state; }; diff --git a/OMNotebook/Pltpkg2/line2D.cpp b/OMNotebook/Pltpkg2/line2D.cpp index 45592913520..358799fe35e 100644 --- a/OMNotebook/Pltpkg2/line2D.cpp +++ b/OMNotebook/Pltpkg2/line2D.cpp @@ -49,7 +49,7 @@ Line2D::Line2D(qreal x1, qreal y1, qreal x2, qreal y2, QPen newPen, QGraphicsLineItem(x1, y1, x2, y2, parent, scene) { //setFlag(flag, enabled); - setPen(newPen); + setPen(newPen); pen().setWidth(width); pen().setCosmetic(bCosmetic); } diff --git a/OMNotebook/Pltpkg2/line2D.h b/OMNotebook/Pltpkg2/line2D.h index 39d084b0f76..8294992a2f6 100644 --- a/OMNotebook/Pltpkg2/line2D.h +++ b/OMNotebook/Pltpkg2/line2D.h @@ -42,13 +42,13 @@ class Line2D: public QGraphicsLineItem { - // Q_OBJECT + // Q_OBJECT public: Line2D(qreal x1, qreal y1, qreal x2, qreal y2, - QPen newPen = QPen(Qt::red), + QPen newPen = QPen(Qt::red), qreal width=0, bool bCosmetic = false, - QGraphicsItem* parent=0, QGraphicsScene* scene=0); + QGraphicsItem* parent=0, QGraphicsScene* scene=0); ~Line2D(); QRectF boundingRect() const; }; diff --git a/OMNotebook/Pltpkg2/point.cpp b/OMNotebook/Pltpkg2/point.cpp index 5c37b5ce439..421e32beb18 100644 --- a/OMNotebook/Pltpkg2/point.cpp +++ b/OMNotebook/Pltpkg2/point.cpp @@ -45,7 +45,7 @@ using namespace std; Point::Point(qreal x1, qreal y1,qreal h, qreal w, QColor color_, const GraphWidget* graphwidget_, - QGraphicsItem* parent, QGraphicsScene* scene, const QString& label): + QGraphicsItem* parent, QGraphicsScene* scene, const QString& label): /*label_(label),*/QGraphicsEllipseItem(x1, y1, h, w, parent, scene), graphwidget(graphwidget_) { color = color_; @@ -66,7 +66,7 @@ Point::Point(qreal x1, qreal y1,qreal h, qreal w, QColor color_, const GraphWidg setToolTip(label); else setToolTip(graphwidget->currentXVar + QString(": ") + QVariant(xPos).toString() + QString("\n") + - graphwidget->currentYVar +QString(": ") + QVariant(yPos).toString()); + graphwidget->currentYVar +QString(": ") + QVariant(yPos).toString()); setAcceptsHoverEvents(true); QPen qp; @@ -81,41 +81,41 @@ Point::~Point() void Point::updateSize() { - double xScale = graphwidget->matrix().m11()/125; - double yScale = graphwidget->matrix().m22()/195; + double xScale = graphwidget->matrix().m11()/125; + double yScale = graphwidget->matrix().m22()/195; - double width=150 / xScale; - double height = -200 / yScale; + double width=150 / xScale; + double height = -200 / yScale; - scale(1/xScale, 1/yScale); + scale(1/xScale, 1/yScale); } void Point::move(double x, double y) { - moveBy(-dx +x, -dy +y); - dx = x; - dy = y; + moveBy(-dx +x, -dy +y); + dx = x; + dy = y; } void Point::hoverEnterEvent ( QGraphicsSceneHoverEvent * event ) { - QPen qp; + QPen qp; #if QT_VERSION >= 0x400300 - QBrush b(color.darker()); + QBrush b(color.darker()); #else - QBrush b(color); + QBrush b(color); #endif - setBrush(b); + setBrush(b); } void Point::hoverLeaveEvent ( QGraphicsSceneHoverEvent * event ) { - QBrush b(Qt::NoBrush); - setBrush(b); + QBrush b(Qt::NoBrush); + setBrush(b); - QPen qp; - qp.setColor(color); - setPen(qp); + QPen qp; + qp.setColor(color); + setPen(qp); } void Point::mousePressEvent ( QGraphicsSceneMouseEvent * event ) diff --git a/OMNotebook/Pltpkg2/point.h b/OMNotebook/Pltpkg2/point.h index 0642cfa71af..9bad8cdad07 100644 --- a/OMNotebook/Pltpkg2/point.h +++ b/OMNotebook/Pltpkg2/point.h @@ -46,7 +46,7 @@ class Point: public QGraphicsEllipseItem { public: Point(qreal x1, qreal y1, qreal h, qreal w, QColor color_, const GraphWidget* graphwidget_=0, - QGraphicsItem* parent=0, QGraphicsScene* scene=0, const QString& label = ""); + QGraphicsItem* parent=0, QGraphicsScene* scene=0, const QString& label = ""); ~Point(); double xFactor, yFactor; double xPos, yPos, hgt, wdt; diff --git a/OMNotebook/Pltpkg2/preferenceWindow.cpp b/OMNotebook/Pltpkg2/preferenceWindow.cpp index 5f717e473b0..c87d0747523 100644 --- a/OMNotebook/Pltpkg2/preferenceWindow.cpp +++ b/OMNotebook/Pltpkg2/preferenceWindow.cpp @@ -41,37 +41,37 @@ PreferenceWindow::PreferenceWindow(CompoundWidget* cw, QWidget *parent): QDialog(parent) { - compoundWidget =cw; + compoundWidget =cw; - setupUi(this); + setupUi(this); - vMin->setText(QVariant(compoundWidget->gwMain->currentArea().top()).toString()); - vMax->setText(QVariant(compoundWidget->gwMain->currentArea().bottom()).toString()); - hMin->setText(QVariant(compoundWidget->gwMain->currentArea().left()).toString()); - hMax->setText(QVariant(compoundWidget->gwMain->currentArea().right()).toString()); + vMin->setText(QVariant(compoundWidget->gwMain->currentArea().top()).toString()); + vMax->setText(QVariant(compoundWidget->gwMain->currentArea().bottom()).toString()); + hMin->setText(QVariant(compoundWidget->gwMain->currentArea().left()).toString()); + hMax->setText(QVariant(compoundWidget->gwMain->currentArea().right()).toString()); - hMajorSize->setText(QVariant(compoundWidget->gwMain->xMajorDist).toString()); - hMinorSize->setText(QVariant(compoundWidget->gwMain->xMinorDist).toString()); + hMajorSize->setText(QVariant(compoundWidget->gwMain->xMajorDist).toString()); + hMinorSize->setText(QVariant(compoundWidget->gwMain->xMinorDist).toString()); - vMajorSize->setText(QVariant(compoundWidget->gwMain->yMajorDist).toString()); - vMinorSize->setText(QVariant(compoundWidget->gwMain->yMinorDist).toString()); + vMajorSize->setText(QVariant(compoundWidget->gwMain->yMajorDist).toString()); + vMinorSize->setText(QVariant(compoundWidget->gwMain->yMinorDist).toString()); - hAutoGrid->setChecked(!compoundWidget->gwMain->fixedXSize); - vAutoGrid->setChecked(!compoundWidget->gwMain->fixedYSize); + hAutoGrid->setChecked(!compoundWidget->gwMain->fixedXSize); + vAutoGrid->setChecked(!compoundWidget->gwMain->fixedYSize); - showGrid->setChecked(compoundWidget->gwMain->gridVisible); - showLegend->setChecked(compoundWidget->legendFrame->isVisible()); - plotTitle->setText(compoundWidget->plotTitle->text()); - vLabel->setText(compoundWidget->yLabel->text()); - hLabel->setText(compoundWidget->xLabel->text()); + showGrid->setChecked(compoundWidget->gwMain->gridVisible); + showLegend->setChecked(compoundWidget->legendFrame->isVisible()); + plotTitle->setText(compoundWidget->plotTitle->text()); + vLabel->setText(compoundWidget->yLabel->text()); + hLabel->setText(compoundWidget->xLabel->text()); - hLog->setChecked(compoundWidget->gwMain->xLog); - vLog->setChecked(compoundWidget->gwMain->yLog); + hLog->setChecked(compoundWidget->gwMain->xLog); + vLog->setChecked(compoundWidget->gwMain->yLog); - connect(pbOk, SIGNAL(clicked()), this, SLOT(apply())); - connect(pbApply, SIGNAL(clicked()), this, SLOT(apply())); - connect(this, SIGNAL(setGrid(bool)), compoundWidget->gwMain, SLOT(showGrid(bool))); - connect(this, SIGNAL(setLogarithmic(bool)), compoundWidget->gwMain, SLOT(setLogarithmic(bool))); + connect(pbOk, SIGNAL(clicked()), this, SLOT(apply())); + connect(pbApply, SIGNAL(clicked()), this, SLOT(apply())); + connect(this, SIGNAL(setGrid(bool)), compoundWidget->gwMain, SLOT(showGrid(bool))); + connect(this, SIGNAL(setLogarithmic(bool)), compoundWidget->gwMain, SLOT(setLogarithmic(bool))); } PreferenceWindow::~PreferenceWindow() @@ -81,62 +81,62 @@ PreferenceWindow::~PreferenceWindow() void PreferenceWindow::apply() { - QRectF area = compoundWidget->gwMain->currentArea(); - - double left, right, top, bottom; - left = area.left(); - right = area.right(); - top = area.top(); - bottom = area.bottom(); - - if(vMin->isEnabled()) - { - - top = QVariant(vMin->text()).toDouble(); - bottom = QVariant(vMax->text()).toDouble(); - } - - if(hMin->isEnabled()) - { - left = QVariant(hMin->text()).toDouble(); - right = QVariant(hMax->text()).toDouble(); - } - - QRectF newArea(left, top, right-left, bottom-top); - - if(newArea != compoundWidget->gwMain->currentArea()) - compoundWidget->gwMain->setArea(newArea); - - compoundWidget->gwMain->fixedXSize = !hAutoGrid->isChecked(); - compoundWidget->gwMain->fixedYSize = !vAutoGrid->isChecked(); - - if(!hAutoGrid->isChecked()) - { - compoundWidget->gwMain->xMajorDist = QVariant(hMajorSize->text()).toDouble(); - compoundWidget->gwMain->xMinorDist = QVariant(hMinorSize->text()).toDouble(); - } - - if(!vAutoGrid->isChecked()) - { - compoundWidget->gwMain->yMajorDist = QVariant(vMajorSize->text()).toDouble(); - compoundWidget->gwMain->yMinorDist = QVariant(vMinorSize->text()).toDouble(); - } - - compoundWidget->plotTitle->setText(plotTitle->text()); - compoundWidget->yLabel->setText(vLabel->text()); - compoundWidget->xLabel->setText(hLabel->text()); - - if(vLog->isChecked() != compoundWidget->gwMain->yLog || hLog->isChecked() != compoundWidget->gwMain->xLog) - { - compoundWidget->gwMain->yLog = vLog->isChecked(); - compoundWidget->gwMain->xLog = hLog->isChecked(); - emit setLogarithmic(true); - } - - emit setGrid(showGrid->isChecked()); - - compoundWidget->legendFrame->setVisible(showLegend->isChecked()); - compoundWidget->gwMain->graphicsScene->update(compoundWidget->gwMain->currentArea()); - compoundWidget->gwMain->update(); + QRectF area = compoundWidget->gwMain->currentArea(); + + double left, right, top, bottom; + left = area.left(); + right = area.right(); + top = area.top(); + bottom = area.bottom(); + + if(vMin->isEnabled()) + { + + top = QVariant(vMin->text()).toDouble(); + bottom = QVariant(vMax->text()).toDouble(); + } + + if(hMin->isEnabled()) + { + left = QVariant(hMin->text()).toDouble(); + right = QVariant(hMax->text()).toDouble(); + } + + QRectF newArea(left, top, right-left, bottom-top); + + if(newArea != compoundWidget->gwMain->currentArea()) + compoundWidget->gwMain->setArea(newArea); + + compoundWidget->gwMain->fixedXSize = !hAutoGrid->isChecked(); + compoundWidget->gwMain->fixedYSize = !vAutoGrid->isChecked(); + + if(!hAutoGrid->isChecked()) + { + compoundWidget->gwMain->xMajorDist = QVariant(hMajorSize->text()).toDouble(); + compoundWidget->gwMain->xMinorDist = QVariant(hMinorSize->text()).toDouble(); + } + + if(!vAutoGrid->isChecked()) + { + compoundWidget->gwMain->yMajorDist = QVariant(vMajorSize->text()).toDouble(); + compoundWidget->gwMain->yMinorDist = QVariant(vMinorSize->text()).toDouble(); + } + + compoundWidget->plotTitle->setText(plotTitle->text()); + compoundWidget->yLabel->setText(vLabel->text()); + compoundWidget->xLabel->setText(hLabel->text()); + + if(vLog->isChecked() != compoundWidget->gwMain->yLog || hLog->isChecked() != compoundWidget->gwMain->xLog) + { + compoundWidget->gwMain->yLog = vLog->isChecked(); + compoundWidget->gwMain->xLog = hLog->isChecked(); + emit setLogarithmic(true); + } + + emit setGrid(showGrid->isChecked()); + + compoundWidget->legendFrame->setVisible(showLegend->isChecked()); + compoundWidget->gwMain->graphicsScene->update(compoundWidget->gwMain->currentArea()); + compoundWidget->gwMain->update(); } diff --git a/OMNotebook/Pltpkg2/preferenceWindow.h b/OMNotebook/Pltpkg2/preferenceWindow.h index 16ca0a46d0b..0adadd3f623 100644 --- a/OMNotebook/Pltpkg2/preferenceWindow.h +++ b/OMNotebook/Pltpkg2/preferenceWindow.h @@ -42,22 +42,22 @@ class PreferenceWindow: public QDialog, public Ui::PreferenceDialog { - Q_OBJECT + Q_OBJECT public: - PreferenceWindow(CompoundWidget* cw, QWidget* parent = 0); + PreferenceWindow(CompoundWidget* cw, QWidget* parent = 0); - ~PreferenceWindow(); + ~PreferenceWindow(); public slots: - void apply(); + void apply(); signals: - void setLegend(bool visible); - void setGrid(bool visible); - void setLogarithmic(bool); + void setLegend(bool visible); + void setGrid(bool visible); + void setLogarithmic(bool); private: - CompoundWidget* compoundWidget; + CompoundWidget* compoundWidget; }; diff --git a/OMNotebook/Pltpkg2/variableData.cpp b/OMNotebook/Pltpkg2/variableData.cpp index 462a595a874..e129e7d220d 100644 --- a/OMNotebook/Pltpkg2/variableData.cpp +++ b/OMNotebook/Pltpkg2/variableData.cpp @@ -45,17 +45,17 @@ using namespace std; VariableData::VariableData(QString name_, QString id, QString data) { - name = new QString(name_); + name = new QString(name_); - QByteArray ba = QByteArray::fromBase64( data.toLatin1() ); - QBuffer b(&ba); - b.open(QBuffer::ReadOnly); - QDataStream ds(&b); + QByteArray ba = QByteArray::fromBase64( data.toLatin1() ); + QBuffer b(&ba); + b.open(QBuffer::ReadOnly); + QDataStream ds(&b); - ds >> *this; - b.close(); + ds >> *this; + b.close(); - interpolation = INTERPOLATION_LINEAR; + interpolation = INTERPOLATION_LINEAR; } VariableData::~VariableData() diff --git a/OMNotebook/Pltpkg2/variableData.h b/OMNotebook/Pltpkg2/variableData.h index b77a8969967..e8715f42264 100644 --- a/OMNotebook/Pltpkg2/variableData.h +++ b/OMNotebook/Pltpkg2/variableData.h @@ -44,27 +44,27 @@ enum {INTERPOLATION_NONE, INTERPOLATION_LINEAR, INTERPOLATION_CONSTANT}; class VariableData: public QList { public: - VariableData(QString name_, QColor color_ = Qt::color0) + VariableData(QString name_, QColor color_ = Qt::color0) { currentIndex = 0; name = new QString(name_); color = color_; } - VariableData(QString name_, QString id, QString data); - ~VariableData(); + VariableData(QString name_, QString id, QString data); + ~VariableData(); - QString variableName() {return *name;} - void setVariableName(QString name_) {name = new QString(name_);} + QString variableName() {return *name;} + void setVariableName(QString name_) {name = new QString(name_);} - quint32 currentIndex; - QColor color; + quint32 currentIndex; + QColor color; - int interpolation; - bool drawPoints; + int interpolation; + bool drawPoints; private: - QString *name; + QString *name; }; diff --git a/OMNotebook/Pltpkg2/variablewindow.cpp b/OMNotebook/Pltpkg2/variablewindow.cpp index 854fbdfe262..eca97c6e894 100644 --- a/OMNotebook/Pltpkg2/variablewindow.cpp +++ b/OMNotebook/Pltpkg2/variablewindow.cpp @@ -47,14 +47,14 @@ using namespace std; VariableWindow::VariableWindow(GraphWidget* gw, QWidget *parent): QDialog(parent) { - graphWidget =gw; + graphWidget =gw; - setupUi(this) ; - connect(pbCreate, SIGNAL(clicked()), this, SLOT(createCurve())); - connect(pbColor, SIGNAL(clicked()), this, SLOT(selectColor())); - connect(pbRemove, SIGNAL(clicked()), this, SLOT(removeCurve())); + setupUi(this) ; + connect(pbCreate, SIGNAL(clicked()), this, SLOT(createCurve())); + connect(pbColor, SIGNAL(clicked()), this, SLOT(selectColor())); + connect(pbRemove, SIGNAL(clicked()), this, SLOT(removeCurve())); - updateViews(); + updateViews(); } @@ -66,97 +66,97 @@ VariableWindow::~VariableWindow() void VariableWindow::updateViews() { - QTreeWidgetItem* item; - twVariables->clear(); - cbx->clear(); - cby->clear(); - for(map::iterator i = graphWidget->variables.begin(); i != graphWidget->variables.end(); ++i) - { - item = new QTreeWidgetItem(); - item->setText(0, i->first); - item->setText(1, QVariant(i->second->count()).toString()); + QTreeWidgetItem* item; + twVariables->clear(); + cbx->clear(); + cby->clear(); + for(map::iterator i = graphWidget->variables.begin(); i != graphWidget->variables.end(); ++i) + { + item = new QTreeWidgetItem(); + item->setText(0, i->first); + item->setText(1, QVariant(i->second->count()).toString()); - cbx->addItem(i->first); - cby->addItem(i->first); - twVariables->insertTopLevelItem(0,item); - } + cbx->addItem(i->first); + cby->addItem(i->first); + twVariables->insertTopLevelItem(0,item); + } - twPlotted->clear(); - for(QList::iterator i = graphWidget->curves.begin(); i != graphWidget->curves.end(); ++i) - { + twPlotted->clear(); + for(QList::iterator i = graphWidget->curves.begin(); i != graphWidget->curves.end(); ++i) + { - if(!(*i)) - continue; - item = new QTreeWidgetItem(); + if(!(*i)) + continue; + item = new QTreeWidgetItem(); - item->setText(0, (*i)->x->variableName()); - item->setText(1, (*i)->y->variableName()); - twPlotted->insertTopLevelItem(0, item); + item->setText(0, (*i)->x->variableName()); + item->setText(1, (*i)->y->variableName()); + twPlotted->insertTopLevelItem(0, item); - } + } } void VariableWindow::selectColor() { -// QColorDialog d(this); +// QColorDialog d(this); - QColor c = QColorDialog::getColor(lColor->palette().button().color()); + QColor c = QColorDialog::getColor(lColor->palette().button().color()); - lColor->setPalette(QPalette(c)); + lColor->setPalette(QPalette(c)); } void VariableWindow::createCurve() { - QColor color = lColor->palette().button().color(); - LegendLabel *l = new LegendLabel(color,cby->currentText(),graphWidget->legendFrame, true, true, 12); - graphWidget->legendFrame->setMinimumWidth(max(l->fontMetrics().width(l->text())+41+4, graphWidget->legendFrame->minimumWidth())); - l->graphWidget = graphWidget; - - - Curve* c = new Curve(graphWidget->variables[cbx->currentText()],graphWidget->variables[cby->currentText()],color, l); - l->setCurve(c); - - if(rbLinear->isChecked()) - c->interpolation = INTERPOLATION_LINEAR; - else if(rbConstant->isChecked()) - c->interpolation = INTERPOLATION_CONSTANT; - else - c->interpolation= INTERPOLATION_NONE; - c->drawPoints = cbPoints->isChecked(); - - graphWidget->legendLayout->addWidget(l); - graphWidget->curves.push_back(c); -// graphWidget->showGraphics(); - graphWidget->setLogarithmic(true); - emit showGraphics(); - graphWidget->resetZoom(); - // graphWidget-> - updateViews(); + QColor color = lColor->palette().button().color(); + LegendLabel *l = new LegendLabel(color,cby->currentText(),graphWidget->legendFrame, true, true, 12); + graphWidget->legendFrame->setMinimumWidth(max(l->fontMetrics().width(l->text())+41+4, graphWidget->legendFrame->minimumWidth())); + l->graphWidget = graphWidget; + + + Curve* c = new Curve(graphWidget->variables[cbx->currentText()],graphWidget->variables[cby->currentText()],color, l); + l->setCurve(c); + + if(rbLinear->isChecked()) + c->interpolation = INTERPOLATION_LINEAR; + else if(rbConstant->isChecked()) + c->interpolation = INTERPOLATION_CONSTANT; + else + c->interpolation= INTERPOLATION_NONE; + c->drawPoints = cbPoints->isChecked(); + + graphWidget->legendLayout->addWidget(l); + graphWidget->curves.push_back(c); +// graphWidget->showGraphics(); + graphWidget->setLogarithmic(true); + emit showGraphics(); + graphWidget->resetZoom(); + // graphWidget-> + updateViews(); } void VariableWindow::removeCurve() { - if(!twPlotted->currentItem()) - return; - QString x = twPlotted->currentItem()->text(0); - QString y = twPlotted->currentItem()->text(1); - - for(int i = 0; i < graphWidget->curves.size(); ++i) - { - if(graphWidget->curves[i]->x->variableName() == x && graphWidget->curves[i]->y->variableName() == y) - { - Curve* c = graphWidget->curves.takeAt(i); - delete c; - break; - - } - } - updateViews(); + if(!twPlotted->currentItem()) + return; + QString x = twPlotted->currentItem()->text(0); + QString y = twPlotted->currentItem()->text(1); + + for(int i = 0; i < graphWidget->curves.size(); ++i) + { + if(graphWidget->curves[i]->x->variableName() == x && graphWidget->curves[i]->y->variableName() == y) + { + Curve* c = graphWidget->curves.takeAt(i); + delete c; + break; + + } + } + updateViews(); } diff --git a/OMNotebook/Pltpkg2/variablewindow.h b/OMNotebook/Pltpkg2/variablewindow.h index 01a30b65299..a7581399f58 100644 --- a/OMNotebook/Pltpkg2/variablewindow.h +++ b/OMNotebook/Pltpkg2/variablewindow.h @@ -42,26 +42,26 @@ class VariableWindow: public QDialog, public Ui::NewGraph { - Q_OBJECT + Q_OBJECT public: - VariableWindow(GraphWidget* gw, QWidget* parent = 0); + VariableWindow(GraphWidget* gw, QWidget* parent = 0); - ~VariableWindow(); + ~VariableWindow(); public slots: - void createCurve(); - void selectColor(); - void updateViews(); - void removeCurve(); + void createCurve(); + void selectColor(); + void updateViews(); + void removeCurve(); signals: - void showGraphics(); - // void setLegend(bool visible); -// void setGrid(bool visible); -// void setLogarithmic(bool); + void showGraphics(); + // void setLegend(bool visible); +// void setGrid(bool visible); +// void setLogarithmic(bool); private: - GraphWidget* graphWidget; + GraphWidget* graphWidget; }; diff --git a/OMNotebook/Pltpkg2/verticalLabel.h b/OMNotebook/Pltpkg2/verticalLabel.h index 94bd844b07f..5ce6ea469b0 100644 --- a/OMNotebook/Pltpkg2/verticalLabel.h +++ b/OMNotebook/Pltpkg2/verticalLabel.h @@ -43,50 +43,50 @@ class VerticalLabel: public QLabel { public: - VerticalLabel(QWidget * parent = 0, Qt::WindowFlags f = 0 ): QLabel(parent, f) - { + VerticalLabel(QWidget * parent = 0, Qt::WindowFlags f = 0 ): QLabel(parent, f) + { - } + } - VerticalLabel(const QString & text, QWidget * parent = 0, Qt::WindowFlags f = 0): QLabel(text, parent,f) - { - setText(text); - } + VerticalLabel(const QString & text, QWidget * parent = 0, Qt::WindowFlags f = 0): QLabel(text, parent,f) + { + setText(text); + } - ~VerticalLabel() - { + ~VerticalLabel() + { - } + } protected: - void paintEvent ( QPaintEvent * event ) - { - QPainter painter(this); - render(&painter); - } + void paintEvent ( QPaintEvent * event ) + { + QPainter painter(this); + render(&painter); + } public: - void setText(const QString& text) - { - QLabel::setText(text); - int h = fontMetrics().height(); - - setMaximumWidth(h); - } - - void render(QPainter* painter, QPointF pos = QPointF()) - { - painter->save(); - painter->translate(pos.x(), pos.y()); - painter->translate(width() /2., height() /2.); - - painter->rotate(-90); - painter->translate(height() /-2., width() /-2.); - painter->setFont(font()); - - painter->drawText(QRect(rect().left(), rect().top(), rect().height(),rect().width()), Qt::AlignCenter, text()); - painter->restore(); - } + void setText(const QString& text) + { + QLabel::setText(text); + int h = fontMetrics().height(); + + setMaximumWidth(h); + } + + void render(QPainter* painter, QPointF pos = QPointF()) + { + painter->save(); + painter->translate(pos.x(), pos.y()); + painter->translate(width() /2., height() /2.); + + painter->rotate(-90); + painter->translate(height() /-2., width() /-2.); + painter->setFont(font()); + + painter->drawText(QRect(rect().left(), rect().top(), rect().height(),rect().width()), Qt::AlignCenter, text()); + painter->restore(); + } };